genetic algorithm implementation

This commit is contained in:
Sam Hadow 2024-10-18 11:37:16 +02:00
parent 3b4bc26cff
commit 1a46936216

View File

@ -18,3 +18,27 @@ def mutation(solution, k):
i = random.randint(0,len(solution)-1) i = random.randint(0,len(solution)-1)
solution[i] = random.choice(list({i for i in range(k)} - {solution[i]})) solution[i] = random.choice(list({i for i in range(k)} - {solution[i]}))
return solution return solution
def genetic(problem_data, k, popsize, mutation_chance, stop, reproduce):
population = generate_initial_population(problem_data, k, popsize)
population.sort(key = lambda x : fitness(x, problem_data, k), reverse=True)
loop = 0
while loop<stop:
best = fitness(population[-1], problem_data, k)
new = []
for _ in range(reproduce):
parents = random.choices(population, cum_weights=[1]*popsize, k=2)
x = random.random()
offspring = crossover(*parents)
new.append(mutation(offspring, k) if mutation_chance>x else offspring)
population = sorted(population + new, key=lambda x: fitness(x, problem_data, k), reverse=True)[-4:]
new_best = fitness(population[-1], problem_data, k)
loop = loop + 1 if best<=new_best else 0
best = new_best
return(population[-1])
ans = genetic(tasks, 2, 4, 0.2, 10, 4)
print(ans)
print(fitness(ans, tasks, 2))