From ccf3a18a59d8cdc15908d4ef6f9a5d616942fd1a Mon Sep 17 00:00:00 2001 From: coolneng Date: Fri, 18 Jun 2021 19:33:26 +0200 Subject: [PATCH] Implement population selection --- src/genetic_algorithm.py | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/src/genetic_algorithm.py b/src/genetic_algorithm.py index fe0dd47..1a170be 100644 --- a/src/genetic_algorithm.py +++ b/src/genetic_algorithm.py @@ -148,10 +148,10 @@ def mutate(population, n, probability=0.001): return population -def tournament_selection(population): - individuals = population.sample(n=2) - best_index = population["distance"].idxmax() - return individuals.iloc[best_index] +def tournament_selection(m, population): + individuals = [population[randint(m)] for _ in range(2)] + best_index = population.index(max(population, key=lambda x: all(x.fitness))) + return individuals[best_index] def generational_replacement(previous_population, current_population): @@ -200,12 +200,20 @@ def evaluate_population(population, data, cores=4): return evaluated_population +def select_new_population(population, n, m, mode): + if mode == "generational": + parents = [tournament_selection(m, population) for _ in range(n)] + else: + parents = [tournament_selection(m, population) for _ in range(2)] + return parents + + def genetic_algorithm(n, m, data, mode, max_iterations=100000): population = [generate_individual(n, m, data) for _ in range(n)] population = evaluate_population(population, data) for _ in range(max_iterations): - pass + parents = select_new_population(population, n, m, mode) n, m, data = parse_file("data/GKD-c_11_n500_m50.txt") -genetic_algorithm(n=10, m=5, data=data, mode="") +genetic_algorithm(n=10, m=5, data=data, mode="generational", max_iterations=1)