Skip to content

ga_instance.best_solution() only returning best parameters and fitness of previous Generation #291

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

Open
Resch-Said opened this issue Apr 30, 2024 · 2 comments
Labels
bug Something isn't working

Comments

@Resch-Said
Copy link

So, I played around with pygad a bit and realized that you only get the best solution of the previous generation. This is particularly noticeable with a stop criteria.

I would like to put the stress especially on the part stop_criteria="reach_500". I put some prints in the on_generation method, so you can see that the limit is reached and the final solution is printed, but when I run the ga_instance.best_solution(), I only get the result of the previous generation.

I have uploaded a sample code here and the output as an image which makes it easy to recognize.

image

import pygad
import numpy

function_inputs = [2, 8, 9, 5]
desired_output = 10


def fitness_func(ga_instance, solution, solution_idx):
    output = numpy.sum(solution * function_inputs)
    fitness = 1.0 / (numpy.abs(output - desired_output) + 0.000001)
    return fitness


fitness_function = fitness_func


def _on_generation(ga_instance):
    print("Generation : ", ga_instance.generations_completed)
    print("Fitness of the best solution :", ga_instance.best_solution()[1])
    print("Best solution :", ga_instance.best_solution()[0])
    print("--------------------------------------------------")


ga_instance = pygad.GA(
    num_generations=5000,
    num_parents_mating=5,
    fitness_func=fitness_function,
    sol_per_pop=10,
    num_genes=len(function_inputs),
    stop_criteria="reach_500",
    on_generation=_on_generation,
)


ga_instance.run()

solution, solution_fitness, solution_idx = ga_instance.best_solution()
print(f"Parameters of the best solution : {solution}")
print(f"Fitness value of the best solution = {solution_fitness}")
print(f"best_solutions_fitness[-1] : {ga_instance.best_solutions_fitness[-1]}") # You can get the best fitness like this
print(f"Index of the best solution : {solution_idx}")

prediction = numpy.sum(numpy.array(function_inputs) * solution)
print(f"Predicted output based on the best solution : {prediction}")

print(
    f"Best fitness value reached after {ga_instance.best_solution_generation} generations."
)
@moritz-weber
Copy link

Not really an explanation for this weird behavior, but maybe a workaround.
In the multi-objective example (https://pygad.readthedocs.io/en/latest/pygad_more.html#multi-objective-optimization), they use:

solution, solution_fitness, solution_idx = ga_instance.best_solution(ga_instance.last_generation_fitness)

This works well for me and (seemingly) always returns the best solution of the last generation.

@ahmedfgad
Copy link
Owner

The issue was in the previous_generation_fitness attribute where it was not updated after the GA completes its lifecycle. The issue is solved and will be available in the next release!

@ahmedfgad ahmedfgad added the bug Something isn't working label Jan 7, 2025
ahmedfgad added a commit that referenced this issue Jan 7, 2025
1. The `delay_after_gen` parameter is removed from the `pygad.GA` class constructor. As a result, it is no longer an attribute of the `pygad.GA` class instances. To add a delay after each generation, apply it inside the `on_generation` callback. #283
2. In the `single_point_crossover()` method of the `pygad.utils.crossover.Crossover` class, all the random crossover points are returned before the `for` loop. This is by calling the `numpy.random.randint()` function only once before the loop to generate all the K points (where K is the offspring size). This is compared to calling the `numpy.random.randint()` function inside the `for` loop K times, once for each individual offspring.
3. Bug fix in the `examples/example_custom_operators.py` script. #285
4. While making prediction using the `pygad.torchga.predict()` function, no gradients are calculated.
5. The `gene_type` parameter of the `pygad.helper.unique.Unique.unique_int_gene_from_range()` method accepts the type of the current gene only instead of the full gene_type list.
6. Created a new method called `unique_float_gene_from_range()` inside the `pygad.helper.unique.Unique` class to find a unique floating-point number from a range.
7. Fix a bug in the `pygad.helper.unique.Unique.unique_gene_by_space()` method to return the numeric value only instead of a NumPy array.
8. Refactoring the `pygad/helper/unique.py` script to remove duplicate codes and reformatting the docstrings.
9. The plot_pareto_front_curve() method added to the pygad.visualize.plot.Plot class to visualize the Pareto front for multi-objective problems. It only supports 2 objectives. #279
10. Fix a bug converting a nested NumPy array to a nested list. #300
11. The `Matplotlib` library is only imported when a method inside the `pygad/visualize/plot.py` script is used. This is more efficient than using `import matplotlib.pyplot` at the module level as this causes it to be imported when `pygad` is imported even when it is not needed. #292
12. Fix a bug when minus sign (-) is used inside the `stop_criteria` parameter (e.g. `stop_criteria=["saturate_10", "reach_-0.5"]`). #296
13. Make sure `self.best_solutions` is a list of lists inside the `cal_pop_fitness` method. #293
14. Fix a bug where the `cal_pop_fitness()` method was using the `previous_generation_fitness` attribute to return the parents fitness. This instance attribute was not using the fitness of the latest population, instead the fitness of the population before the last one. The issue is solved by updating the `previous_generation_fitness` attribute to the latest population fitness before the GA completes. #291
@ahmedfgad ahmedfgad mentioned this issue Jan 7, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

3 participants