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