使用具有大数据集的 SciPy 曲线拟合库时出现运行时错误

2024-03-21

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

运行时错误:未找到最佳参数:函数调用次数已达到 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 块 https://docs.python.org/3/tutorial/errors.html#handling-exceptions:

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 个,并发现有一条与它们拟合良好的高斯曲线,那么它可能会与其余数据点拟合得很好。或者至少它将为后续使用完整数据集细化参数奠定良好的起点。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用具有大数据集的 SciPy 曲线拟合库时出现运行时错误 的相关文章

随机推荐