Skip to content

Calling best_solution() after a run with elitism doesn't return best solution #337

@raphaelboudreault

Description

@raphaelboudreault

Hello and thanks for that fantastic library!

I believe I found a bug using the best_solution() method. When it is called after a run where elitism was activated (as per default) without providing the pop_fitness optional parameter, the cal_pop_fitness() method is called, where the fitness value of the elites in the population are not re-computed (as expected). However, at the end of a run, more precisely at the end of the last generation, the previous_generation_fitness attribute is set equal to last_generation_fitness (line 1926 of pygad.py), which leads to an incoherent definition of previous_generation_fitness that is not equal to the "fitness value of the generation before the last", and thus leading to elites that are given the incorrect fitness values, providing a wrong best solution.

While this is an unexpected behavior (in my opinion), a workaround is to always use ga_instance.best_solution(ga_instance.last_generation_fitness) once the GA run is completed, as used in the examples in the docs.

Looking closely to the code, self.previous_generation_fitness = self.last_generation_fitness.copy() is called both at line 1812 and line 1926 of pygad.py, and I believe only the first call should be kept (at the beginning of the loop, before computing the new fitness values).

Thanks in advance!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions