Skip to content

Commit

Permalink
Add elitism
Browse files Browse the repository at this point in the history
  • Loading branch information
manuel-calzolari committed Apr 3, 2021
1 parent 7cd52d5 commit 3b39fe4
Showing 1 changed file with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions genetic_selection/gscv.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,11 @@ def _eaFunction(population, toolbox, cxpb, mutpb, ngen, ngen_no_change=None, sta
for ind, fit in zip(invalid_ind, fitnesses):
ind.fitness.values = fit

if halloffame is not None:
halloffame.update(population)
if halloffame is None:
raise ValueError("The 'halloffame' parameter should not be None.")

halloffame.update(population)
hof_size = len(halloffame.items) if halloffame.items else 0

record = stats.compile(population) if stats else {}
logbook.record(gen=0, nevals=len(invalid_ind), **record)
Expand All @@ -67,7 +70,7 @@ def _eaFunction(population, toolbox, cxpb, mutpb, ngen, ngen_no_change=None, sta
wait = 0
for gen in range(1, ngen + 1):
# Select the next generation individuals
offspring = toolbox.select(population, len(population))
offspring = toolbox.select(population, len(population) - hof_size)

# Vary the pool of individuals
offspring = algorithms.varAnd(offspring, toolbox, cxpb, mutpb)
Expand All @@ -78,12 +81,14 @@ def _eaFunction(population, toolbox, cxpb, mutpb, ngen, ngen_no_change=None, sta
for ind, fit in zip(invalid_ind, fitnesses):
ind.fitness.values = fit

# Add the best back to population
offspring.extend(halloffame.items)

# Get the previous best individual before updating the hall of fame
prev_best = halloffame[0]

# Update the hall of fame with the generated individuals
if halloffame is not None:
halloffame.update(offspring)
halloffame.update(offspring)

# Replace the current population by the offspring
population[:] = offspring
Expand Down

1 comment on commit 3b39fe4

@manuel-calzolari
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.