Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 字典迭代Lambda函数_Python_Dictionary_For Loop_Lambda_Scikit Learn - Fatal编程技术网

Python 字典迭代Lambda函数

Python 字典迭代Lambda函数,python,dictionary,for-loop,lambda,scikit-learn,Python,Dictionary,For Loop,Lambda,Scikit Learn,我一直在迭代数组字典,并对字典中的每个数组元素应用线性回归 from sklearn.linear_model import LinearRegression model = LinearRegression() for i in my_dict.keys(): test = model.fit(x_val.reshape(-1,1), my_dict[i].reshape(-1,1)) coeff = float(test.coef_) intercept = floa

我一直在迭代数组字典,并对字典中的每个数组元素应用线性回归

from sklearn.linear_model import LinearRegression
model = LinearRegression()
for i in my_dict.keys():
    test = model.fit(x_val.reshape(-1,1), my_dict[i].reshape(-1,1))
    coeff = float(test.coef_)
    intercept = float(test.intercept_)
    my_dict[i] = lambda x: coeff * x  + intercept
在每一次迭代中,我都非常确信适当的系数和截距被分配给lambda函数。然而,似乎字典中存储的每个lambda函数都在使用系数,并截取字典中的“最后一个”键。我似乎不知道这是为什么。谢谢

编辑:我知道我可以将线性回归器对象分配给每个键,而不是使用lambda函数(我只是更喜欢lambda函数)。然而,这并没有解决这个问题

请参阅和

这在Python中有点奇怪——闭包中的变量查找是基于包含范围和变量名的组合。由于lambda是在模块作用域中定义的(请注意,
for
循环不会创建新的作用域),并且名称
coeff
intercept
不会更改,因此每次查找将始终是循环最后一次迭代的值

要解决此问题,您可以执行以下操作之一:

  • 通过在局部函数中包装
    my_dict[i]=lambda x:coeff*x+intercept
    ,每次迭代强制一个新范围
  • coeff
    intercept
    作为默认参数捕获到lambda的定义中:
    my_dict[i]=lambda x,coeff=coeff,intercept=intercept:coeff*x+intercept
  • 保存
    my_dict
    中的单个
    coeff
    intercept
    值(或其他容器),然后在需要时将其取出

  • 非常感谢。我没有意识到这个怪癖。