DEV Community

Cover image for Python's random.choices is Awesome

Python's random.choices is Awesome

Ryan Palo on March 26, 2019

I'm reading through Classic Computer Science Problems in Python (affiliate link) by David Kopec, and I'm working on his Genetic Algorithm examples....
Collapse
 
minterciso profile image
Mateus Interciso

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] 
print(idx)
>>> 21

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

Collapse
 
dowenb profile image
Ben Dowen

100%! I have found random.choice is very useful for generating test data.