GeneticAlgorithmPython icon indicating copy to clipboard operation
GeneticAlgorithmPython copied to clipboard

Accessing population of previous generation in fitness_func

Open lukethomrichardson opened this issue 2 years ago • 6 comments

I am trying to find a way to access the entire population of the previous generation (not just the calculated fitness or kept parents) to use in the evaluation of fitness in each generation. Is this possible in the current release?

lukethomrichardson avatar Mar 19 '23 12:03 lukethomrichardson

There is no property that saves the population in the previous generation is not saved. But you can still access it. Here are 2 ways.

First way

  1. Set save_solutions=True in the constructor of the pygad.GA class. This saves the solutions from each population in the solutions property.
  2. For each generation, find the index of the first and last solution in the population. Let's assume the indices are x and y.
  3. Return the last generation's population: ga_instance.solutions[x:y, :]

If you have 10 solutions per population, then the first and last solution indices are:

  1. 0 and 9 for the first generation.
  2. 10 and 19 for the second generation.
  3. 20 and 29 for the third generation.

And so on.

Second way

Create a new property in the ga_instance attribute that saves the previous generation's population. This can be done at the end of each generation inside the on_generation() callback function/method.

Hope this helps.

ahmedfgad avatar Apr 09 '23 18:04 ahmedfgad

Does pygad automatically skipping evaluate solution that has been calculated from previous solution?

yasirroni avatar May 28 '23 08:05 yasirroni

Does pygad automatically skipping evaluate solution that has been calculated from previous solution?

@yasirroni, PyGAD skips evaluation the fitness for a previous solution if any of these conditions hold:

  1. The solution is a parent in the last population. The keep_parents parameter must be -1 or a positive integer.
  2. The solution is an elitism in the last population. The keep_elitism parameter must be a positive integer.
  3. The solution exists in the self.solutions list given that save_solutions=True.
  4. The solution exists in the self.best_solutions list given that save_best_solutions=True.

ahmedfgad avatar Jun 24 '23 15:06 ahmedfgad

@ahmedfgad Adding this kind of information to the docs seems good I think. Thanks for clarifying.

yasirroni avatar Jun 26 '23 04:06 yasirroni

The documentation is already updated to reflect this: https://github.com/ahmedfgad/GeneticAlgorithmPython/commit/d3b9ec0533d0d87b91298e8db1a6852947c93570

ahmedfgad avatar Jun 27 '23 17:06 ahmedfgad

Vote to close this issue.

yasirroni avatar Jul 01 '23 03:07 yasirroni