我正在尝试使用scipy.optimize.curve_fit优化指数拟合。但是结果是不好的。我的代码是:
def func(x, a, b, c):
return a * np.exp(-b * x) + c
# xdata and data is obtain from another dataframe and their type is nparray
xdata =[36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70 ,71,72]
ydata = [4,4,4,6,6,13,22,22,26,28,38,48,55,65,65,92,112,134,171,210,267,307,353,436,669,669,818,1029,1219,1405,1617,1791,2032,2032,2182,2298,2389]
popt, pcov = curve_fit(func, xdata, ydata)
plt.plot(xdata, func(xdata, *popt), 'r-', label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
plt.scatter(xdata, ydata, s=1)
plt.show()
然后我得到了这样的结果:
结果表明:
pcov = [[inf inf inf] [inf inf inf] [inf inf inf]]
popt = [1 1 611.83784]
我不知道如何使曲线拟合得很好。你可以帮我吗?谢谢!
该方法未找到最佳点。可以尝试的一件事是更改初始猜测,以使b开始为负数,因为从您的数据来看,b必须为负数,以便func
恰好适合它。另外,根据curve_fit
的文档,如果未指定,默认情况下初始猜测为1。所以你应该有:
popt, pcov = curve_fit(func, xdata, ydata, p0=[1, -0.05, 1])
给出
popt
array([ 1.90782987e+00, -1.01639857e-01, -1.73633728e+02])
pcov
array([[ 1.08960274e+00, 7.93580944e-03, -5.24526701e+01],
[ 7.93580944e-03, 5.79450721e-05, -3.74693994e-01],
[-5.24526701e+01, -3.74693994e-01, 3.34388178e+03]])
和情节