Pygad create new population if fitness is saturated

77 Views Asked by At

I am using Pygad to compute an optimization problem, however the algorithm is reaching local minima (not the ideal solution) before all the generations have run. I would like to be able to check after each generation if the fitness has saturated for a certain number of generations and if so reinitialize a new population using the 'sol per pop', 'gene number', and 'gene space' from the current instance. Is this possible to do in Pygad? Any help would be appreciated.

I have tried to setup the 'On Generation' callback, but I can't seem to find anyway to call a new population initialization and pass it back into the 'population' attribute.

1

There are 1 best solutions below

3
On

This is an example that applies what you mentioned. If the fitness saturates for 10 generations, a new population is generated.

import pygad

def fitness_func(ga_instance, solution, solution_idx):
    return 5

def on_generation(ga_i):
    if ga_i.generations_completed > 10:
        # Check if the fitness is saturated
        if ga_i.best_solutions_fitness[-1] == ga_i.best_solutions_fitness[-10]:
            # reinitialize a new population using the 'sol per pop', 'gene number', and 'gene space'
            ga_i.initialize_population(low=ga_i.init_range_low,
                                       high=ga_i.init_range_high,
                                       allow_duplicate_genes=ga_i.allow_duplicate_genes,
                                       mutation_by_replacement=True,
                                       gene_type=ga_i.gene_type)
            # At this point, a new population is created and assigned to the 'population' parameter.


ga_instance = pygad.GA(num_generations=20,
                       sol_per_pop=5,
                       num_genes=2,
                       num_parents_mating=2,
                       fitness_func=fitness_func,
                       on_generation=on_generation)

ga_instance.run()