Skip to content

Instantly share code, notes, and snippets.

@thieu1995
Created May 22, 2020 12:46
Show Gist options
  • Save thieu1995/43c7d78e5782941d4db37942a5a855b0 to your computer and use it in GitHub Desktop.
Save thieu1995/43c7d78e5782941d4db37942a5a855b0 to your computer and use it in GitHub Desktop.
In Roulette Wheel Selection, this is the best way to deal with negative fitness values
from numpy import min, sum, ptp, array
from numpy.random import uniform
list_fitness1 = array([-12, -45, 0, 72.1, -32.3])
list_fitness2 = array([0.5, 6.32, 988.2, 1.23])
def get_index_roulette_wheel_selection(list_fitness=None):
""" It can handle negative also. Make sure your list fitness is 1D-numpy array"""
scaled_fitness = (list_fitness - min(list_fitness)) / ptp(list_fitness)
minimized_fitness = 1.0 - scaled_fitness
total_sum = sum(minimized_fitness)
r = uniform(low=0, high=total_sum)
for idx, f in enumerate(minimized_fitness):
r = r + f
if r > total_sum:
return idx
get_index_roulette_wheel_selection(list_fitness1)
get_index_roulette_wheel_selection(list_fitness2)
#1. Make sure your fitness list is 1D-numpy array
#2. Scaled the fitness list to the range [0, 1]
#3. Transform maximum problem to minimum problem by 1.0 - scaled_fitness_list
#4. Random a number between 0 and sum(minimizzed_fitness_list)
#5. Keep adding element in minimized fitness list until we get the value greater than the total sum
#6. You can see if the fitness is small --> it has bigger value in minimized_fitness --> It has a bigger chance to add and make the value greater than the total sum.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment