pythongenetic-algorithm

Passing arguments to PyGAD fitness function


I'm curious how you send arguments to the fitness function in PyGAD i.e

import pygad

def fitness_function(solution, solution_idx,num):
    print(num+10)
    return sum(solution)

ga_instance = pygad.GA(num_generations=1,
                       num_parents_mating=2,
                       sol_per_pop=3,
                       num_genes=4,
                       fitness_func=fitness_function,

                       init_range_low=5,
                       init_range_high=15,args=(5,))

What I expected from this piece of code was that I'd print 15 every time the fitness function would be called (just to make sure passing parameters was working correctly).

but instead I get

 python gaex.py
Traceback (most recent call last):
  File "gaex.py", line 14, in <module>
    init_range_high=15,arg=(5,))
TypeError: __init__() got an unexpected keyword argument 'args'

Any suggestions?


Solution

  • Make your fitness function parametrizable like that:

    def fitness_function_factory(num):
    
        def fitness_function(solution, solution_idx):
            print(num + 10)
            return sum(solution)
    
        return fitness_function
    

    Then give it to the GA it like that:

    ga_instance = pygad.GA(num_generations=1,
                           ...
                           fitness_func=fitness_function_factory(5),
                           ...
                           init_range_high=15)