Skip to content

re: Python's random.choices is Awesome VIEW POST


Found this post searching specifically for GA selection techniques, just wanted to say that the choices() is great, but it's really not a roulette selection, it's just selecting 2 candidates with probability being equal to the fitness. In order to make a roulette wheel selection, you have to be a little more complex than that, mainly:

  1. Create the probabilities (or weights) based on the fitness values
  2. Select a random number
  3. Keep accumulating the probability (or weights), until you reach the number
  4. That's your selected candidate

Very simple code:

import numpy as np

fitness = np.random.rand(50)
total_fitness = sum(fitness)
weights = fitness/total_fitness
r = np.random.rand()
acc = 0
idx = -1
while acc < r: 
    idx += 1 
    acc += weights[idx] 
>>> 21

This is a very simple algorithm, and there are other implementations (way faster and better), but it shows the point ;).

code of conduct - report abuse