GeneticAlgorithmPython icon indicating copy to clipboard operation
GeneticAlgorithmPython copied to clipboard

How to get multiple best solutions in a generation?

Open JimmyChine opened this issue 1 year ago • 1 comments

Hi All,

I am a new on in PyGAD, and now I am using PyGAD to implement my multiple objective optimization problem. In your example, I learned how to the funcion on_generation() to get one best fitness of each generation:

def on_generation(ga_instance): global last_fitness print("Generation = {generation}".format(generation=ga_instance.generations_completed)) print("Fitness = {fitness}".format(fitness=ga_instance.best_solution(pop_fitness=ga_instance.last_generation_fitness)[1])) print("Change = {change}".format(change=ga_instance.best_solution(pop_fitness=ga_instance.last_generation_fitness)[1] - last_fitness)) solution, solution_fitness, solution_idx = ga_instance.best_solution(pop_fitness=ga_instance.last_generation_fitness)

My question is that: can I get multiple best solutions (for example, I want to get best three solutions) in PyGAD?

Any suggestions would be greatly appreciated. Thanks

JimmyChine avatar Nov 20 '24 10:11 JimmyChine

This can be achieved by calling the pygad.utils.ParentSelection.steady_state_selection() method.

class ParentSelection:

    def __init__():
        pass

    def steady_state_selection(self, fitness, num_parents):
        ...
    return parents, numpy.array(fitness_sorted[:num_parents])

If you need the top 3 solutions, you can set num_parents=3. The method returns the selected parents and their fitness.

ahmedfgad avatar Jan 07 '25 18:01 ahmedfgad