|
| 1 | +import pygad |
| 2 | +import numpy |
| 3 | + |
| 4 | +""" |
| 5 | +Use a method to build the lifecycle. |
| 6 | +""" |
| 7 | + |
| 8 | +class GAOperations: |
| 9 | + def fitness_func(self, ga_instance, solution, solution_idx): |
| 10 | + fitness = numpy.sum(solution) |
| 11 | + return fitness |
| 12 | + |
| 13 | + def crossover(self, parents, offspring_size, ga_instance): |
| 14 | + return numpy.random.rand(offspring_size[0], offspring_size[1]) |
| 15 | + |
| 16 | + def mutation(self, offspring, ga_instance): |
| 17 | + return offspring |
| 18 | + |
| 19 | +class Lifecycle: |
| 20 | + def on_start(self, ga_instance): |
| 21 | + print("on_start") |
| 22 | + |
| 23 | + def on_fitness(self, ga_instance, fitness): |
| 24 | + print("on_fitness") |
| 25 | + |
| 26 | + def on_crossover(self, ga_instance, offspring): |
| 27 | + print("on_crossover") |
| 28 | + |
| 29 | + def on_mutation(self, ga_instance, offspring): |
| 30 | + print("on_mutation") |
| 31 | + |
| 32 | + def on_parents(self, ga_instance, parents): |
| 33 | + print("on_parents") |
| 34 | + |
| 35 | + def on_generation(self, ga_instance): |
| 36 | + print("on_generation") |
| 37 | + |
| 38 | + def on_stop(self, ga_instance, fitness): |
| 39 | + print("on_stop") |
| 40 | + |
| 41 | +ga_obj = GAOperations() |
| 42 | +lifecycle_obj = Lifecycle() |
| 43 | + |
| 44 | +num_generations = 10 # Number of generations. |
| 45 | +num_parents_mating = 5 # Number of solutions to be selected as parents in the mating pool. |
| 46 | + |
| 47 | +sol_per_pop = 10 # Number of solutions in the population. |
| 48 | +num_genes = 5 |
| 49 | + |
| 50 | +ga_instance = pygad.GA(num_generations=num_generations, |
| 51 | + num_parents_mating=num_parents_mating, |
| 52 | + sol_per_pop=sol_per_pop, |
| 53 | + num_genes=num_genes, |
| 54 | + |
| 55 | + fitness_func=ga_obj.fitness_func, |
| 56 | + |
| 57 | + crossover_type=ga_obj.crossover, |
| 58 | + mutation_type=ga_obj.mutation, |
| 59 | + |
| 60 | + on_start=lifecycle_obj.on_start, |
| 61 | + on_fitness=lifecycle_obj.on_fitness, |
| 62 | + on_crossover=lifecycle_obj.on_crossover, |
| 63 | + on_mutation=lifecycle_obj.on_mutation, |
| 64 | + on_parents=lifecycle_obj.on_parents, |
| 65 | + on_generation=lifecycle_obj.on_generation, |
| 66 | + on_stop=lifecycle_obj.on_stop, |
| 67 | + |
| 68 | + suppress_warnings=True) |
| 69 | + |
| 70 | +# Running the GA to optimize the parameters of the function. |
| 71 | +ga_instance.run() |
| 72 | + |
| 73 | +ga_instance.plot_fitness() |
0 commit comments