Skip to content

Commit 539b233

Browse files
authored
Bug fixes when save_best_solutions=True
Some bug fixes when setting the save_best_solutions parameter to True. Previously, the best solution for generation i was added into the best_solutions attribute at generation i+1. Now, the best_solutions attribute is updated by each solution at its exact generation.
1 parent 6c620f3 commit 539b233

File tree

2 files changed

+13
-7
lines changed

2 files changed

+13
-7
lines changed

__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
from .pygad import * # Relative import.
22

3-
__version__ = "2.14.2"
3+
__version__ = "2.14.3"

pygad.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -937,19 +937,19 @@ def run(self):
937937
# Measuring the fitness of each chromosome in the population. Save the fitness in the last_generation_fitness attribute.
938938
self.last_generation_fitness = self.cal_pop_fitness()
939939

940+
best_solution, best_solution_fitness, best_match_idx = self.best_solution(pop_fitness=self.last_generation_fitness)
941+
942+
# Appending the best solution in the initial population to the best_solutions list.
943+
if self.save_best_solutions:
944+
self.best_solutions.append(best_solution)
945+
940946
for generation in range(self.num_generations):
941947
if not (self.on_fitness is None):
942948
self.on_fitness(self, self.last_generation_fitness)
943949

944-
best_solution, best_solution_fitness, best_match_idx = self.best_solution(pop_fitness=self.last_generation_fitness)
945-
946950
# Appending the fitness value of the best solution in the current generation to the best_solutions_fitness attribute.
947951
self.best_solutions_fitness.append(best_solution_fitness)
948952

949-
# Appending the best solution to the best_solutions list.
950-
if self.save_best_solutions:
951-
self.best_solutions.append(best_solution)
952-
953953
# Selecting the best parents in the population for mating.
954954
self.last_generation_parents = self.select_parents(self.last_generation_fitness, num_parents=self.num_parents_mating)
955955
if not (self.on_parents is None):
@@ -993,6 +993,12 @@ def run(self):
993993
# Measuring the fitness of each chromosome in the population. Save the fitness in the last_generation_fitness attribute.
994994
self.last_generation_fitness = self.cal_pop_fitness()
995995

996+
best_solution, best_solution_fitness, best_match_idx = self.best_solution(pop_fitness=self.last_generation_fitness)
997+
998+
# Appending the best solution to the best_solutions list.
999+
if self.save_best_solutions:
1000+
self.best_solutions.append(best_solution)
1001+
9961002
# If the callback_generation attribute is not None, then cal the callback function after the generation.
9971003
if not (self.on_generation is None):
9981004
r = self.on_generation(self)

0 commit comments

Comments
 (0)