Tuesday, September 3, 2013

python list comprehension for loop

Let's make a 'python list & dictionary comprehension for loop' example. It selects equal or greater than average value, then returns max 50 elements from dictionary.

def pick_biggest_elements(my_dict):
    values = [x for x in my_dict.values()]
    values.sort()
    average = sum(values) / float(len(values))
    upper_side = [el for el in values if el >= average]
    temp = [key for key, value in my_dict.items() if value in upper_side]
    if len(temp) > 50:
        temp = temp[-50:]
    return [eval(a) for a in temp]

Monday, September 2, 2013

python roulette wheel selection

Selection operator picks out individuals in the population for reproduction in genetic algorithms. Roulette wheel selection that an imaginary proportion of the wheel is assigned to each of the chromosomes based on their fitness value. The fitter chromosome has more chance to select than worse one. Roulette wheel selection is a kind of elitist selection that retaining the best individuals in a generation unchanged in the next generation.

Here an example of roulette wheel selection via pyhton. Imagine that you have population like

population = [[0,0,1,0,0,0,1],[0,1,0,0,0,0,0]]

And you use a proper fitness function regarding to your problem, and get a python dictionary to wrap your individuals and their fitness values like

population_fitness_dictionary = {"0,0,1,0,0,0,1": 1.245, "0,1,0,0,0,0,0":1.658}

Firstly, we can create a probability list (imaginary proportion of the wheel)

def get_probability_list():
    fitness = population_fitness_dictionary.values()
    total_fit = float(sum(fitness))
    relative_fitness = [f/total_fit for f in fitness]
    probabilities = [sum(relative_fitness[:i+1]) 
                     for i in range(len(relative_fitness))]
    return probabilities

After that, we can write the roulette wheel selection function. Parameters of the function are our population, probability list of the population and a number to select desired individuals for reproduction.

def roulette_wheel_pop(population, probabilities, number):
    chosen = []
    for n in xrange(number):
        r = random.random()
        for (i, individual) in enumerate(population):
            if r <= probabilities[i]:
                chosen.append(list(individual))
                break
    return chosen