Fix uniform crossover function
This commit is contained in:
parent
046b1a043a
commit
5f89731f77
|
@ -5,6 +5,7 @@ from math import ceil
|
|||
from functools import partial
|
||||
from multiprocessing import Pool
|
||||
from copy import deepcopy
|
||||
from itertools import chain, repeat
|
||||
|
||||
from preprocessing import parse_file
|
||||
|
||||
|
@ -130,12 +131,15 @@ def position_crossover(parents, m):
|
|||
|
||||
|
||||
def crossover(mode, parents, m):
|
||||
split_parents = zip(*[iter(parents)] * 2)
|
||||
split_parents = list(zip(*[iter(parents)] * 2))
|
||||
offspring = []
|
||||
if mode == "uniform":
|
||||
crossover_func = partial(uniform_crossover, m=m)
|
||||
for i in range(len(split_parents)):
|
||||
offspring.append(uniform_crossover(split_parents[i], m))
|
||||
offspring.append(uniform_crossover(split_parents[i], m))
|
||||
else:
|
||||
crossover_func = partial(position_crossover, m=m)
|
||||
offspring = [*map(crossover_func, split_parents)]
|
||||
offspring = [*map(crossover_func, split_parents)]
|
||||
return offspring
|
||||
|
||||
|
||||
|
@ -211,18 +215,26 @@ def get_best_elements(population):
|
|||
|
||||
|
||||
def get_worst_elements(population):
|
||||
first_index = population.index(min(population, key=lambda x: all(x.fitness)))
|
||||
population.pop(first_index)
|
||||
second_index = population.index(min(population, key=lambda x: all(x.fitness)))
|
||||
select_population = deepcopy(population)
|
||||
first_element = min(select_population, key=lambda x: x.fitness.values[0])
|
||||
first_index = get_individual_index(first_element, select_population)
|
||||
select_population.pop(first_index)
|
||||
second_element = min(select_population, key=lambda x: x.fitness.values[0])
|
||||
second_index = get_individual_index(second_element, select_population)
|
||||
return first_index, second_index
|
||||
|
||||
|
||||
def stationary_replacement(prev_population, current_population):
|
||||
new_population = prev_population
|
||||
worst_indexes = get_worst_elements(prev_population)
|
||||
best_indexes = get_best_elements(current_population)
|
||||
first_worst, second_worst = get_worst_elements(prev_population)
|
||||
first_best, second_best = get_best_elements(current_population)
|
||||
worst_indexes = [first_worst, second_worst]
|
||||
best_indexes = [first_best, second_best]
|
||||
for worst, best in zip(worst_indexes, best_indexes):
|
||||
if current_population[best].fitness > prev_population[worst].fitness:
|
||||
if (
|
||||
current_population[best].fitness.values[0]
|
||||
> prev_population[worst].fitness.values[0]
|
||||
):
|
||||
new_population[worst] = current_population[best]
|
||||
return new_population
|
||||
|
||||
|
@ -276,5 +288,5 @@ genetic_algorithm(
|
|||
data=data,
|
||||
select_mode="generational",
|
||||
crossover_mode="uniform",
|
||||
max_iterations=1,
|
||||
max_iterations=10,
|
||||
)
|
||||
|
|
Loading…
Reference in New Issue