pythonmachine-learningartificial-intelligencegenetic-programmingpygad

PYGAD how to debug the built-in parent selection method


I am using PYGAD GA module to write a genetic programming, I want to use the tournament selection for my parent matching, I do not known how to use print() to debug the parent selection method, here is my code:

import numpy as np
import pygad


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

population = np.array([[9, 9, 9], [6, 6, 6], [7, 7, 7], [8, 8, 8],[1,1,1],[2,2,2],[3,3,3],[0,0,0],[4,4,4],[5,5,5]])


ga_instance = pygad.GA(initial_population=population,
                       parent_selection_type="tournament",
                       K_tournament = 3)

# Calculate the fitness of the initial population
fitness = ga_instance.cal_pop_fitness()

I want to see the selected parent for the next generation, how can print them out for debugging the built-in parent selection method, many thanks


Solution

  • There are 2 ways:

    1. Use the on_parents() parameter. It is assigned a callback function/method that receives the selected parents.
    
    def on_parents(ga_instance, selected_parents):
        print("on_parents()")
    
    ga_instance = pygad.GA(...,
                           on_parents=on_parents,
                           ...)
    
    1. Use the last_generation_parents instance attribute. You can fetch the value of this attribute from anywhere using the instance of the pygad.GA class.