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
值(或其他容器),然后在需要时将其取出非常感谢。我没有意识到这个怪癖。