RuntimeError using SciPy 具有大数据集的曲线拟合库

RuntimeError using SciPy curve fitting library with a large data set

如何使用拟合高斯曲线的 SciPy 曲线拟合函数来关闭此错误?换句话说,如果它不适合模型峰值,那么它就不是峰值,所以我不想 return 任何东西。另外,有更快的方法吗? curve_fit 对于我查看大量数据的应用程序来说可能太慢了。

RuntimeError: Optimal parameters not found: Number of calls to function has reached maxfev = 800.

from scipy.optimize import curve_fit
from scipy import asarray as ar,exp
import matplotlib.pyplot as plt
from numpy import sqrt, pi, exp, loadtxt


data = loadtxt('data/model1d_gauss.dat')
x = data[:, 0]
y = data[:, 1]

n = len(x)                          #the number of data
mean = sum(x*y)/n                   #note this correction
sigma = sum(y*(x-mean)**2)/n        #note this correction

def gaus(x,a,x0,sigma):
    return a*exp(-(x-x0)**2/(2*sigma**2))

def gaussian(x, amp, cen, wid):
    "1-d gaussian: gaussian(x, amp, cen, wid)"
    return (amp/(sqrt(2*pi)*wid)) * exp(-(x-cen)**2 /(2*wid**2))

popt,pcov = curve_fit(gaus,x,y,p0=[1,mean,sigma])

#popt,pcov = curve_fit(gaussian,x,y,p0=[5,1,1])

plt.plot(x,y,'bo:',label='data')
plt.plot(x,gaus(x,*popt),'ro:',label='fit')
plt.legend()
plt.show()`enter code here`

要处理 RuntimeError,请使用 try-except block:

try:
    popt,pcov = curve_fit(gaus,x,y,p0=[1,mean,sigma])
except RuntimeError:
    print("No fit found")   # whatever you want to do here

一些减少运行时间的方法:

  • 减少函数调用的最大值maxfev,这样例程会更快失败:例如,curve_fit(gaus, x, y, p0=[1,0,1], maxfev=400)
  • 对您的数据点进行采样。如果你有 10000 个点,随机选择其中的 1000 个,发现有一条高斯曲线可以很好地拟合它们,它可能会很好地拟合其余的数据点。或者至少它将为随后使用完整数据集优化参数提供一个良好的起点。