Reputation: 23
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?
Upvotes: 2
Views: 2377
Reputation: 301
I found that the provided solution does not work (anymore?) for a parallel execution of the GA, i.e. using the parallel_processing
argument. This is because the local function cannot be pickled.
Instead one can use global variables:
import pygad
# initialize global attributes
arg1, arg2, ... = None, None, ...
# define a fitness function
def fitness_func(ga_instance, solution, solution_idx):
global arg1, arg2, ...
...
return fitness
# assign values to the global arguments
arg1, arg2, ... = ...
ga_instance = pygad.GA(
...
fitness_func = fitness_func,
parallel_processing=['process', 12]
...
)
I tried a solution with partial
which does seem to work but later shows a weird bug (genes in the population change to values in [-1e-35, 1e-35]
).
Upvotes: 0
Reputation: 1842
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)
Upvotes: 4