Saturday, August 31, 2013

python comprehension split list

I have recently finished a master thesis about genetic algorithms for text segmentation via python, so I have a complicated relationship with python. Actually it always helps to me. This post consists of some python especially list and dictionary comprehensions.

First of all, splitting a list regarding with given another list. For example, you have a list which has sentences as elements. Another list is reference splitter and consists of 0s and 1s.
sentences = ["first sentence", "second sentence", "third sentence",
             "fourth sentence", "fifth sentence"] 
reference = [0,0,1,0]
This list indicates that cut the number of index of '1' at the gap in the sentences list and result list will include two sublists
result = [["first sentence", "second sentence", "third sentence"],
          ["fourth sentence", "fifth sentence"]] 
def split_segments_according_to_reference(reference, sentences):
        temp = []
        result = []
        for i, j in zip(reference,range(len(sentences))):
            temp.append(sentences[j])
            if i == 1:
                result.append(temp)
                temp = []
        if len(sentences) == len(reference)+1:
            temp.append(sentences[-1])
            result.append(temp)
            temp = []
        return result

Thursday, April 25, 2013

Pareto frontier graphic via python

Pareto frontiers are not strictly dominated by any others. An element is dominated if there exists an other element in the set of elements having a better score on one criterion and at least the same score on the others. Here a little example Python Pareto frontier code.
import matplotlib.pyplot as plt

def plot_pareto_frontier(Xs, Ys, maxX=True, maxY=True):
    '''Pareto frontier selection process'''
    sorted_list = sorted([[Xs[i], Ys[i]] for i in range(len(Xs))], reverse=maxY)
    pareto_front = [sorted_list[0]]
    for pair in sorted_list[1:]:
        if maxY:
            if pair[1] >= pareto_front[-1][1]:
                pareto_front.append(pair)
        else:
            if pair[1] <= pareto_front[-1][1]:
                pareto_front.append(pair)
    
    '''Plotting process'''
    plt.scatter(Xs,Ys)
    pf_X = [pair[0] for pair in pareto_front]
    pf_Y = [pair[1] for pair in pareto_front]
    plt.plot(pf_X, pf_Y)
    plt.xlabel("Objective 1")
    plt.ylabel("Objective 2")
    plt.show()


An example Pareto frontier graphic is produced by above python function.

Reference 1. http://code.activestate.com/recipes/578230-pareto-front/