Closed yasirroni closed 1 year ago
@yasirroni, this is indeed a good question.
To save time re-calculating the fitness values when calling the best_solution()
method, it is recommended to set pop_fitness=ga_instance.last_generation_fitness
. This way it just re-uses the fitness instead of re-calculating it.
The reason why this is not set as default is because sometimes the user changes the population before calculating the last_generation_fitness
attribute. Let's explain it by an example.
Assume the we have self.population = pop1
and its fitness is calculated and saved into self.last_generation_fitness = fit1
.
The user decided to change the population after self.last_generation_fitness
is calculated. Thus, we have self.population = pop2
.
Because pop2
might have different fitness than pop1
, then the fitness values in self.last_generation_fitness
will not be valid for pop2
.
As a result, we cannot set the pop_fitness
parameter to default to last_generation_fitness
. The user has to arrange this according to the best situation.
Okay. Thanks for clarification with use case.
Maybe, we can add the code snippet below to the doc?
ga_instance.best_solution(pop_fitness=ga_instance.last_generation_fitness)
? If you are agreed, I might be able to make a PR. Thanks.
Yes please open a PR.
The default behavior of
best_solution()
is to re-runcal_pop_fitness()
to get the best_solution. This is explained on the docs too in https://pygad.readthedocs.io/en/latest/README_pygad_ReadTheDocs.html?highlight=gene_type#best-solution. Workaround is to use:Why this is chosen as the default?