GeneticAlgorithmPython icon indicating copy to clipboard operation
GeneticAlgorithmPython copied to clipboard

Manipulating the population

Open davidoskky opened this issue 2 years ago • 3 comments

Hello, is there any way to manually edit the population during the calculation? I'd like to be able to drop a part of the lowest scoring chromosomes after the mutation and replace them with custom crafted chromosomes which I would define; this is because I wish to guide the exploration towards some particular spatial directions. Is this currently possible? Thank you

davidoskky avatar Apr 19 '23 07:04 davidoskky

Hello,

Yes, you can.

The population is saved into the population attribute of the pygad.GA instance. You can get and set it at any time.

If you wish to replace the chromosomes after mutation, then I advise you to use the on_generation parameter. This is an example.

This is an example that edits the population by setting the genes of 6 chromosomes to 1.

import pygad
import numpy

function_inputs = [4,-2,3.5,5,-11,-4.7]
desired_output = 44

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

def on_generation(ga_instance):
    ga_instance.population[4:] = numpy.ones((6, num_genes))

num_genes = len(function_inputs)
sol_per_pop = 10

ga_instance = pygad.GA(num_generations=3,
                       num_parents_mating=5,
                       fitness_func=fitness_func,
                       sol_per_pop=sol_per_pop,
                       num_genes=num_genes,
                       on_generation=on_generation,
                       suppress_warnings=True)

ga_instance.run()

ahmedfgad avatar Apr 20 '23 18:04 ahmedfgad

Thank you very much for your clear reply and the code example. I did imagine this would be the way to go, but I was afraid in creating some problems difficult to backtrace by editing the population with the process running. It is what I do when I load from a save file. One thing that is particularly annoying is that changing the population size in this way causes an error, not really a huge problem though.

davidoskky avatar Apr 21 '23 09:04 davidoskky

Yes, you can do the same after loading the saved file.

It is expected to see some errors after changing the population size. This is because there are other variables that you need to change too. For example, last_generation_offspring_mutation.

ahmedfgad avatar Apr 26 '23 03:04 ahmedfgad