Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rocreguant/e9f2481f4e9842dd76e9c61f653eb7c0 to your computer and use it in GitHub Desktop.
Save rocreguant/e9f2481f4e9842dd76e9c61f653eb7c0 to your computer and use it in GitHub Desktop.
Roulette wheel selection example in python for minimisation problems
import numpy as np
def roulette_wheel_selection(population):
# Computes the totallity of the population fitness
population_fitness = sum([chromosome.fitness for chromosome in population])
# Computes for each chromosome the probability
chromosome_probabilities = [chromosome.fitness/population_fitness for chromosome in population]
# Making the probabilities for a minimization problem
chromosome_probabilities = 1 - np.array(chromosome_probabilities)
# Selects one chromosome based on the computed probabilities
return np.random.choice(population p=chromosome_probabilities)
@rocreguant
Copy link
Author

This function is throwing errors for me. chromosome.fitness.values[0] in place of chromosome.fitness is working.

Also, sum of probabilities is not one. Hence, this is not working.

Maybe you would be interested in checking the full code and adapt it to yours.
https://github.com/rocreguant/personal_blog/tree/main/Genetic_Algorithm_Python_Example
If you have more questions I'm glad to answer them ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment