python SciPy curve_fit with np.exp 返回 pcov = inf

Wen*_* Li 5 python exponential scipy-optimize

我正在尝试使用 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()
Run Code Online (Sandbox Code Playgroud)

然后我得到这样的结果:

在此输入图像描述

结果表明:

pcov = [[inf inf inf] [inf inf inf] [inf inf inf]]
popt = [1  1  611.83784]
Run Code Online (Sandbox Code Playgroud)

我不知道如何让我的曲线很好地拟合。你能打招呼吗?谢谢你!

Ger*_*ges 2

该方法没有找到最佳点。要尝试的一件事是更改初始猜测,使 b 开始为负数,因为从您的数据来看,b 必须为负数,这样才能func正确拟合。另外,根据 的文档curve_fit,如果未指定,则默认情况下初始猜测为 1。一个好的初步猜测是:

popt, pcov = curve_fit(func, xdata, ydata, p0=[1, -0.05, 1])
Run Code Online (Sandbox Code Playgroud)

这使

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]])
Run Code Online (Sandbox Code Playgroud)

还有情节

在此输入图像描述