|
| 1 | +import pygad |
| 2 | +import numpy |
| 3 | + |
| 4 | +""" |
| 5 | +This is an example to dynamically change the population size (i.e. number of solutions/chromosomes per population) during runtime. |
| 6 | +The following 2 instance attributes must be changed to meet the new desired population size: |
| 7 | + 1) population: This is a NumPy array holding the population. |
| 8 | + 2) num_offspring: This represents the number of offspring to produce during crossover. |
| 9 | +For example, if the population initially has 20 solutions and 6 genes. To change it to have 30 solutions, then: |
| 10 | + 1)population: Create a new NumPy array with the desired size (30, 6) and assign it to the population instance attribute. |
| 11 | + 2)num_offspring: Set the num_offspring attribute accordingly (e.g. 29 assuming that keep_elitism has the default value of 1). |
| 12 | +""" |
| 13 | + |
| 14 | +def fitness_func(ga_instance, solution, solution_idx): |
| 15 | + return [numpy.random.rand(), numpy.random.rand()] |
| 16 | + |
| 17 | +def on_generation(ga_i): |
| 18 | + # The population starts with 20 solutions. |
| 19 | + print(ga_i.generations_completed, ga_i.num_offspring, ga_i.population.shape) |
| 20 | + # At generation 15, increase the population size to 40 solutions. |
| 21 | + if ga_i.generations_completed >= 15: |
| 22 | + ga_i.num_offspring = 49 |
| 23 | + new_population = numpy.zeros(shape=(ga_i.num_offspring+1, ga_i.population.shape[1]), dtype=ga_i.population.dtype) |
| 24 | + new_population[:ga_i.population.shape[0], :] = ga_i.population |
| 25 | + ga_i.population = new_population |
| 26 | + elif ga_i.generations_completed >= 10: |
| 27 | + ga_i.num_offspring = 39 |
| 28 | + new_population = numpy.zeros(shape=(ga_i.num_offspring+1, ga_i.population.shape[1]), dtype=ga_i.population.dtype) |
| 29 | + new_population[:ga_i.population.shape[0], :] = ga_i.population |
| 30 | + ga_i.population = new_population |
| 31 | + # At generation 10, increase the population size to 30 solutions. |
| 32 | + elif ga_i.generations_completed >= 5: |
| 33 | + ga_i.num_offspring = 29 |
| 34 | + new_population = numpy.zeros(shape=(ga_i.num_offspring+1, ga_i.population.shape[1]), dtype=ga_i.population.dtype) |
| 35 | + new_population[:ga_i.population.shape[0], :] = ga_i.population |
| 36 | + ga_i.population = new_population |
| 37 | + |
| 38 | +ga_instance = pygad.GA(num_generations=20, |
| 39 | + sol_per_pop=20, |
| 40 | + num_genes=6, |
| 41 | + num_parents_mating=10, |
| 42 | + fitness_func=fitness_func, |
| 43 | + on_generation=on_generation, |
| 44 | + parent_selection_type='nsga2') |
| 45 | + |
| 46 | +ga_instance.run() |
0 commit comments