我正在使用python 2.7,偶然发现了这个问题,我什至不明白为什么以下命令不起作用的逻辑。
我需要适应不同的数据集,我想在for循环中动态地进行操作。 这是重复出现问题的MWE:
import numpy as np
from scipy.optimize import curve_fit
def func_to_fit(x, a):
return x ** a
x = np.arange(0, 10)
dummy_dataset = {1: x ** 2,
2: x ** 3}
param = {}
fitted_func = {}
print "First loop"
for i in [1, 2]:
if i == 1:
idx = "Ex"
else:
idx = "Ez"
# store the results in different items in a dictionary to avoid the usual copying issues in Python
param[idx] = curve_fit(func_to_fit, x, dummy_dataset[i])[0]
fitted_func[idx] = lambda x: func_to_fit(x, *param[idx])
print idx, fitted_func[idx](x)
print param
print fitted_func
print "Ex", fitted_func["Ex"](x)
print "Ez", fitted_func["Ez"](x)
输出为
First loop
Ex [ 0. 1. 4. 9. 16. 25. 36. 49. 64. 81.]
Ez [ 0. 1. 8. 27. 64. 125. 216. 343. 512. 729.]
{'Ex': array([ 2.]), 'Ez': array([ 3.])}
{'Ex': <function <lambda> at 0x0000000015989EB8>, 'Ez': <function <lambda> at 0x0000000015989F98>}
Ex [ 0. 1. 8. 27. 64. 125. 216. 343. 512. 729.]
Ez [ 0. 1. 8. 27. 64. 125. 216. 343. 512. 729.]
打印“第二个循环” 之前的行为是我所期望的:在进行拟合的循环之外,存储在 param 中的参数是正确的( “ Ex” = 2和“ Ez” = 3), fitted_func 中的函数存储在不同的内存位置,当我在第一个循环中调用它们时,它们会给出正确的结果,即fit_func [“ Ex“](x)= x ^ 2和fit_func [” Ez“](x)= x ^ 3。
但是,如果我像调用最后两行代码那样分别调用每个拟合的函数,并且尝试计算这些函数的值,则结果错误,即两者函数返回x ^ 3。
我认为此行为与Python处理内存的方式和某种竞争条件有关,即Python每次在fit_func [idx]中计算lambda函数并记住上一个有效结果(在这种情况下,适合x ^ 3)。 无论如何,我不太了解确切的问题是什么以及如何解决它。
希望我设法正确地说明了这个问题,有人对 1.导致此问题的原因是什么? 2.如何克服?
非常感谢!