将参数传递给 PyGAD 适应度函数

Passing arguments to PyGAD fitness function

我很好奇你如何向 PyGAD 中的适应度函数发送参数,即

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,))

我对这段代码的期望是每次调用适应度函数时我都会打印 15(只是为了确保传递的参数正常工作)。

但我得到

 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'

有什么建议吗?

像这样使你的适应度函数参数化:

def fitness_function_factory(num):

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

    return fitness_function

然后像这样把它交给 GA:

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