You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何PyGad的fitness_function置于类内无法正常运行?

问题原因

类内定义的fitness_func是实例方法,Python会自动将实例对象self作为第一个隐式参数传入该方法,导致实际参数数量为3个(self, solution, solution_idx)。而pygad要求适应度函数必须严格接收2个参数(解决方案本身及其在种群中的索引),因此触发参数数量不匹配的ValueError。

类外的fitness_func是普通函数,不存在隐式传入的self参数,参数数量正好符合pygad的要求,所以可以正常运行。

解决办法

提供3种可行的修复方案,根据你的实际需求选择:

方案1:将适应度函数改为静态方法

使用@staticmethod装饰器标记fitness_func,这样Python不会自动传入self参数,参数数量变为2个,符合pygad要求:

import torch
import torch.nn as nn
import pygad.torchga
import pygad

class NN(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super().__init__()
        self.linear1 = nn.Linear(input_size, hidden_size)
        self.linear2 = nn.Linear(hidden_size, hidden_size)
        self.linear3 = nn.Linear(hidden_size, hidden_size)
        self.linear4 = nn.Linear(hidden_size, output_size)

    def forward(self, x):
        x = self.linear1(x)
        x = self.linear2(x)
        x = self.linear3(x)
        x = self.linear4(x)
        return x

class Coin:
    def __init__(self):
        self.NeuralNet = NN(1440, 1440, 3)

    @staticmethod
    def fitness_func(solution, solution_idx):
        return 0

    def trainModel(self):
        torch_ga = pygad.torchga.TorchGA(model=self.NeuralNet, num_solutions=10)

        ga_instance = pygad.GA(num_generations=10,
                               num_parents_mating=2,
                               initial_population=torch_ga.population_weights,
                               fitness_func=self.fitness_func)

        ga_instance.run()

if __name__ == "__main__":
    coin = Coin()
    coin.trainModel()

方案2:用Lambda表达式包装实例方法

如果fitness_func需要访问类实例的属性(比如self.NeuralNet),静态方法无法满足需求,可以用lambda表达式包装实例方法,手动处理参数传递:

# 在Coin类的trainModel方法中修改GA实例化代码:
ga_instance = pygad.GA(num_generations=10,
                       num_parents_mating=2,
                       initial_population=torch_ga.population_weights,
                       fitness_func=lambda solution, solution_idx: self.fitness_func(solution, solution_idx))

lambda表达式接收pygad要求的2个参数,内部调用实例方法时传递这两个参数,同时保留了对self的引用,可正常访问实例属性。

方案3:使用functools.partial绑定实例

导入functools.partial来绑定实例对象,将实例方法转换为符合参数要求的可调用对象:

import functools

# 在Coin类的trainModel方法中:
bound_fitness = functools.partial(self.fitness_func)
ga_instance = pygad.GA(num_generations=10,
                       num_parents_mating=2,
                       initial_population=torch_ga.population_weights,
                       fitness_func=bound_fitness)

内容的提问来源于stack exchange,提问作者BennyC20

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 21:40:47