简体   繁体   English

scipy curve_fit在简单的线性拟合中失败了吗?

[英]scipy curve_fit fails on easy linear fit?

I intend to do a simple linear fit with two numpy arrays y1 and y2 of length 54 each. 我打算对每个长度为54的两个numpy数组y1y2进行简单的线性拟合。 The function is defined as follows: 该函数定义如下:

def f(x,b):
    return b*x

The data are plotted here: 数据绘制在这里:

在此处输入图片说明

Then I tried fitting via: 然后我尝试通过以下方式拟合:

popt, pcov = scop.curve_fit(f,y2,y1)  # yes y1 and y2 are in right order

Result: popt = 1., pcov = inf 结果: popt = 1., pcov = inf

I tried with p0 = -833 , which is more or less what the result should be, but it gives me popt = -833, pcov = inf . 我尝试使用p0 = -833 ,或多或少应该是结果,但是它给我popt = -833, pcov = inf

I tried some sample data with a sample function: 我使用示例函数尝试了一些示例数据:

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

Result is just fine: 3 and 2e-33 结果很好:3和2e-33

Does anybody have an idea as to what went wrong with the first trial? 有人对第一次审判出了什么问题有想法吗? I haven't found anything useful or connected to my problem yet... 我还没有发现任何有用的东西或与我的问题有关的信息...

NaN values will produce meaningless results - you need to exclude them from your data before doing any fitting. NaN值将产生毫无意义的结果-您需要在进行任何拟合之前将其从数据中排除。 You use boolean indexing to do this: 您可以使用布尔索引来执行此操作:

valid = ~(np.isnan(y1) | np.isnan(y2))
popt, pcov = scop.curve_fit(f, y2[valid], y1[valid])

As mentioned in the comments, 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. 如评论中所述, 在低于 curve_fit 的scipy版本中,curve_fit将自动检查输入数组中的NaN和Infs,如果找到,则会引发ValueError This behavior can be optionally disabled using the check_finite parameter . 可以选择使用check_finite参数禁用此行为。

Based on your question and comments, I'm assuming you must be using an older version - you should probably consider upgrading. 根据您的问题和评论,我假设您必须使用旧版本-您可能应该考虑升级。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM