python(scipy)曲线拟合的奇怪结果 [英] Strange result with python's (scipy) curve fitting
问题描述
这是我的代码(这是较大代码的示例):
This is my code (it's an example of a larger piece of code):
from scipy.optimize import curve_fit
def func(x, a, b):
return a + b*x
xlist = [10, 30, 50, 70, 90, 110, 130, 150, 170, 190, 210, 230]
ylist = [0.0074999999999999997, 0.011875, 0.0057812499999999999, 0.0036458333333333334, 0.0020312500000000001, 0.0013125000000000001, 0.00098958333333333342, 0.00089285714285714283, 0.00074218750000000001, 0.00093749999999999997, 0.00071874999999999999, 0.00088068181818181821]
popt, pcov = curve_fit(func, xlist, ylist)
print(popt[0], popt[1])
如您所见,我正在尝试使用非常简单的 a + b * x
函数进行非常简单的拟合。问题是这会返回值:
As you can see I'm attempting a very simple fit with a very simple a + b*x
function. The issue is that this returns the values:
(-119.99689110581872, 1.0)
对于 a = popt [0]
和 b = popt [1 ]
,但与zunzun.com的拟合度却给出了更为合理的值:
for a=popt[0]
and b=popt[1]
but the same fit with zunzun.com gives much more reasonable values:
a = 7.8372289537296004E-03
b = -3.9402329475524466E-05
完全相同的功能。
我在这里做什么错了?
以下警告称这可能是错误。我应该这样报告还是应该这样?
Warren below stated this might be a bug. Should I report it as such or is this the expected behaviour?
推荐答案
如果您更改<$ c $中的值,则可以使用c> xlist 到一个numpy数组:
It works if you change the values in xlist
to a numpy array:
In [38]: popt, pcov = curve_fit(func, array(xlist, dtype=float), ylist)
In [39]: popt
Out[39]: array([ 7.83722896e-03, -3.94023294e-05])
起初,这看起来像是个错误,但实际情况是底层代码采用了参数 xdata
并将其未更改传递给您的函数。在您的示例中,这意味着在表达式 a + b * x
中, x
是Python列表。 那表示 b * x
不在进行所需的计算。
At first this looks like a bug, but what's happening is that the underlying code takes the argument xdata
and passes it unchanged to your function. In your example, this means in the expression a + b*x
, x
is a Python list. That means that b*x
is not doing the calculation that you want.
因此,为了使 func
的定义起作用,参数 xdata
必须是一个numpy数组。或者,您可以这样定义 func
:
So to make your definition of func
work, the argument xdata
must be a numpy array. Or, you could define func
this way:
def func(x, a, b):
return a + b*np.asarray(x)
这篇关于python(scipy)曲线拟合的奇怪结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!