scipy.optimize.curve_fit无法拟合指数函数

问题描述

我正在尝试使用scipy.optimize.curve_fit()(下面的示例数据和代码)来拟合指数函数。但是它始终显示如下所示的RuntimeErrorRuntimeError: Optimal parameters not found: Number of calls to function has reached maxfev = 5000.我不确定我要去哪里。

import numpy as np
from scipy.optimize import curve_fit

x = np.arange(-1,1,.01)
param1 = [-1,2,10,100]
fit_func = lambda x,a,b,c,d: a * np.exp(b * x + c) + d
y = fit_func(x,*param1)
popt,_ = curve_fit(fit_func,x,y,maxfev=5000)

解决方法

这几乎可以肯定是由于对参数的初步猜测。

您不会将初始猜测传递给curve_fit,这意味着每个参数的缺省值均为1。不幸的是,这对您来说是一个可怕的猜测。感兴趣的函数是指数,其一个特性是导数也是指数。因此,所有导数(一阶,二阶等)不仅是错误的,而且具有错误的 sign 。这意味着优化器将很难取得进展。

您可以通过给优化器一点帮助来解决此问题。由于您知道所有数据都是负数,因此可以将-1作为对 first 参数(函数的比例或幅度)的初始猜测。仅此一项就足以使优化程序做出合理的猜测。

p0 = (-1,1,1)
popt,_ = curve_fit(x,y,p0=p0,maxfev=5000)
fig,ax = plt.subplots()
ax.plot(x,label="Data",color="k")
ax.plot(x,fit_func(x,*popt),color="r",linewidth=3.0,linestyle=":",label="Fitted")
fig.tight_layout()

您应该看到类似这样的内容:enter image description here