I'm trying to implement a genetic algorithm, the problem is when population gets smaller, my function tournament_selection return the same parents. Here is the two main function
def crossover(agents, x):
offspring = []
for _ in range(len(agents)):
p1 = tournament_selection(agents)
p2 = tournament_selection(agents)
split = random.randint(0, len(p2.individual) - 1)
child1 = p1
child1.individual = p1.individual[0:split] + p2.individual[split:len(p1.individual)]
offspring.append(child1)
agents = offspring
return agents
def tournament_selection(population):
parents = random.choices(population, k=5)
parents = sorted(parents, key=lambda agent: agent.fitness, reverse=True)
bestparent = parents[0]
return bestparent
Aucun commentaire:
Enregistrer un commentaire