scipy curve_fit 简单线性拟合失败?
scipy curve_fit fails on easy linear fit?
我打算用两个长度为 54 的 numpy 数组 y1
和 y2
做一个简单的线性拟合。函数定义如下:
def f(x,b):
return b*x
数据绘制在这里:
然后我尝试通过以下方式进行拟合:
popt, pcov = scop.curve_fit(f,y2,y1) # yes y1 and y2 are in right order
结果:popt = 1., pcov = inf
我尝试了 p0 = -833
,这或多或少应该是结果,但它给了我 popt = -833, pcov = inf
。
我用示例函数尝试了一些示例数据:
x = np.array(range(10))
y = x**2 + 3
def fu(x,b):
return x**2 + b
po, pc = scop.curve_fit(fu,x,y)
print po, pc
结果很好:3 和 2e-33
有人知道一审出了什么问题吗?我还没有找到任何有用的或与我的问题相关的东西...
NaN 值将产生无意义的结果 - 在进行任何拟合之前,您需要将它们从数据中排除。您使用布尔索引来执行此操作:
valid = ~(np.isnan(y1) | np.isnan(y2))
popt, pcov = scop.curve_fit(f, y2[valid], y1[valid])
如评论中所述,in versions of scipy newer than 0.15.0 curve_fit
will automatically check for NaNs and Infs in your input arrays and will raise a ValueError
if they are found. This behavior can be optionally disabled using the check_finite
parameter。
根据您的问题和评论,我假设您一定使用的是旧版本 - 您可能应该考虑升级。
我打算用两个长度为 54 的 numpy 数组 y1
和 y2
做一个简单的线性拟合。函数定义如下:
def f(x,b):
return b*x
数据绘制在这里:
然后我尝试通过以下方式进行拟合:
popt, pcov = scop.curve_fit(f,y2,y1) # yes y1 and y2 are in right order
结果:popt = 1., pcov = inf
我尝试了 p0 = -833
,这或多或少应该是结果,但它给了我 popt = -833, pcov = inf
。
我用示例函数尝试了一些示例数据:
x = np.array(range(10))
y = x**2 + 3
def fu(x,b):
return x**2 + b
po, pc = scop.curve_fit(fu,x,y)
print po, pc
结果很好:3 和 2e-33
有人知道一审出了什么问题吗?我还没有找到任何有用的或与我的问题相关的东西...
NaN 值将产生无意义的结果 - 在进行任何拟合之前,您需要将它们从数据中排除。您使用布尔索引来执行此操作:
valid = ~(np.isnan(y1) | np.isnan(y2))
popt, pcov = scop.curve_fit(f, y2[valid], y1[valid])
如评论中所述,in versions of scipy newer than 0.15.0 curve_fit
will automatically check for NaNs and Infs in your input arrays and will raise a ValueError
if they are found. This behavior can be optionally disabled using the check_finite
parameter。
根据您的问题和评论,我假设您一定使用的是旧版本 - 您可能应该考虑升级。