Skip to content

Instantly share code, notes, and snippets.

@fedden
Created November 27, 2017 13:30
Show Gist options
  • Select an option

  • Save fedden/786f2070df129fa39b199f547f903caf to your computer and use it in GitHub Desktop.

Select an option

Save fedden/786f2070df129fa39b199f547f903caf to your computer and use it in GitHub Desktop.
# Create a random population of genes, with each genotype having 2 elements.
population_size = 200
population = np.random.standard_normal((population_size, 2))
# Some objective measure of the genes performance or fitness. This is dependant
# on the environment or optimsation problem that you have, and I do not define
# the function in this snippet.
fitnesses = evaluate_fitness(population)
# Sort the list of fitnesses and create a probability distribution based on
# how fit each gene is.
fitnesses_indices = fitnesses.argsort()
sorted_fitnesses = fitnesses[fitnesses_indices]
fitnesses_weighting = np.maximum(0, 1 - sorted_fitnesses / self.fitnesses.sum())
fitnesses_weighting /= fitnesses_weighting.sum()
# Sort the population by their fitness.
sorted_population = population[fitnesses_indices]
# How many new genes to make and a container to hold them.
amount_of_new_genes = 100
new_population = []
# Loop and select successful parents.
for _ in range(amount_new):
# The probability of selecting a parent is proprotonate to the parents
# objective fitness.
i0 = np.random.choice(sorted_population.shape[0], p=fitnesses_weighting)
i1 = np.random.choice(sorted_population.shape[0], p=fitnesses_weighting)
# We now have parents, ready to 'mate'
parent_one = population[i0]
parent_two = population[i1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment