ahmedfgad / GeneticAlgorithmPython

Source code of PyGAD, a Python 3 library for building the genetic algorithm and training machine learning algorithms (Keras & PyTorch).
https://pygad.readthedocs.io
BSD 3-Clause "New" or "Revised" License
1.79k stars 451 forks source link

`best_solution()` unecessarily run `cal_pop_fitness()` #204

Closed yasirroni closed 1 year ago

yasirroni commented 1 year ago

The default behavior of best_solution() is to re-run cal_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:

ga_instance.best_solution(pop_fitness=ga_instance.last_generation_fitness)

Why this is chosen as the default?

ahmedfgad commented 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.

yasirroni commented 1 year ago

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.

ahmedfgad commented 1 year ago

Yes please open a PR.

yasirroni commented 1 year ago

PR on https://github.com/ahmedfgad/GeneticAlgorithmPython/pull/216