You need to enable JavaScript to run this app. 为什么这段线性回归投毒Python代码运行时报AttributeError属性错误?
优惠活动
大模型
产品
解决方案
定价
更多

为什么这段线性回归投毒Python代码运行时报AttributeError属性错误?

LinRegGDPoisoner 类属性错误排查

问题场景

开发面向机器学习投毒场景的普通最小二乘回归实现类LinRegGDPoisoner时,运行代码抛出指定属性错误,相关代码与报错信息如下。

出错代码片段

def __init__(self, x, y, testx, testy, validx, validy, \
                eta, beta, sigma, eps, \
                mproc, \
                trainfile, resfile, \
                objective, opty, colmap):
        """
        LinRegGDPoisoner implements computations for ordinary least
        squares regression. Computations involving regularization are
        handled in the respective children classes

        for input description, see GDPoisoner.__init__
        """

        GDPoisoner.__init__(self, xx, yy, testx, testy, validx, validy, \
                            eta, beta, sigma, eps, mproc, \
                            trainfile, resfile, \
                            objective, opty, colmap)
        self.initclf, self.initlam = self.learn_model(self.x,self.y,None)

完整报错栈

Traceback (most recent call last):
  File "poison.py", line 540, in <module>
    main(args)
  File "poison.py", line 455, in main
    trainfile,resfile,args.objective,args.optimizey, colmap)
  File "/content/drive/My Drive/Colab Notebooks/Poisoning regression/manip-ml-master/poisoning/gd_poisoners.py", line 674, in __init__
    self.initclf, self.initlam = self.learn_model(self.x,self.y,None)
AttributeError: 'LinRegGDPoisoner' object has no attribute 'x'

报错根因与修复方案

参数名拼写错误是触发本次异常的核心原因:

  • 子类__init__方法的入参里,训练集、训练标签的参数名是x、y,但在调用父类GDPoisoner的初始化方法时,错误传入了和当前作用域不匹配的xx、yy变量。
  • 父类GDPoisoner的初始化逻辑本身,会将传入的训练集、训练标签挂载为实例属性self.x、self.y。因为传参错误,父类要么无法按预期接收正确的训练集数据,要么没有触发属性赋值的分支逻辑,最终不会生成预设的实例属性self.x。
  • 父类初始化流程结束后,代码直接尝试读取self.x、self.y训练初始模型,自然会因为属性不存在抛出对应错误。

修复时只需要将父类初始化调用的入参做匹配调整,把原来传入的xx, yy改为x, y,和当前子类__init__接收到的参数名保持一致即可。


内容的提问来源于stack exchange,提问作者mustain billah rubel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.19 09:24:07