Skip to content

best_solution() unecessarily run cal_pop_fitness() #204

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
yasirroni opened this issue May 28, 2023 · 4 comments
Closed

best_solution() unecessarily run cal_pop_fitness() #204

yasirroni opened this issue May 28, 2023 · 4 comments

Comments

@yasirroni
Copy link
Contributor

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
Copy link
Owner

@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
Copy link
Contributor Author

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
Copy link
Owner

Yes please open a PR.

@yasirroni
Copy link
Contributor Author

PR on #216

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants