使用带有大数据集的SciPy曲线拟合库的RuntimeError

问题描述 投票:1回答:1

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

RuntimeError:找不到最佳参数:函数调用次数已达到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`
python scipy curve-fitting
1个回答
2
投票

要处理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个点,并发现有一条适合它们的高斯曲线,它可能很适合其余的数据点。或者至少它将成为随后使用完整数据集细化参数的良好起点。
© www.soinside.com 2019 - 2024. All rights reserved.