Skip to content

Instantly share code, notes, and snippets.

@fedden
Created December 11, 2017 00:34
Show Gist options
  • Save fedden/f1f8a4e5f44f445bcef948d405787bf2 to your computer and use it in GitHub Desktop.
Save fedden/f1f8a4e5f44f445bcef948d405787bf2 to your computer and use it in GitHub Desktop.
def run_experiments(population_size,
mutation_rate,
elitism,
amount_iteration,
amount_experiements):
experiment_data = []
for experiment in range(amount_experiements):
population = create_random_population(population_size)
completed = False
for iteration in range(amount_iterations):
fitnesses = np.array([get_fitness(dna) for dna in population])
fitnesses_indices = fitnesses.argsort()
fitnesses_total = fitnesses.sum()
sorted_fitnesses = fitnesses[fitnesses_indices]
fitnesses_weighting = 1 - sorted_fitnesses / fitnesses_total
fitnesses_weighting /= fitnesses_weighting.sum()
fitnesses_weighting.sum()
sorted_population = population[fitnesses_indices]
# Done?
if sorted_fitnesses[0] == 0:
completed = True
best_result = sorted_population[0]
completed_iteration = iteration
break
amount_new = int((1 - elitism) * population_size)
new_population = []
for _ in range(amount_new):
i0 = np.random.choice(sorted_population.shape[0], p=fitnesses_weighting)
i1 = np.random.choice(sorted_population.shape[0], p=fitnesses_weighting)
new_dna = crossover(population[i0], population[i1])
new_dna = mutate(new_dna, mutation_rate)
new_population.append(new_dna)
amount_old = population_size - amount_new
new_population = np.array(new_population + population[:amount_old].tolist())
assert new_population.shape == population.shape
population = new_population
if not completed:
best_result = sorted_population[0]
completed_iteration = iteration
experiment_data.append((completed, completed_iteration, best_result))
return experiment_data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment