Skip to main content
 首页 » 编程设计

python之将边界应用于 Scipy 优化曲线拟合

2024年12月31日9del

我正在尝试将简单的正弦波拟合到数据并应用边界来帮助约束拟合。

我正在使用发布的第二个答案 here这是完美的工作,但是当我按照惯例应用边界时,例如:

def fit_sin(tt, yy): 
    import scipy.optimize 
    import numpy as np 
    ''' 
    Fit sin to the input time sequence, and return dict of fitting parameters: 
    "amp", "omega", "phase", "offset", "freq", "period" and "fitfunc" 
    ''' 
    tt = np.array(tt) 
    yy = np.array(yy) 
    ff = np.fft.fftfreq(len(tt), (tt[1]-tt[0]))   # assume uniform spacing 
    Fyy = abs(np.fft.fft(yy)) 
    guess_freq = abs(ff[np.argmax(Fyy[1:])+1])   # excluding the zero frequency "peak", which is related to offset 
    guess_amp = np.std(yy) * 2.**0.5 
    guess_offset = np.mean(yy) 
    guess = np.array([guess_amp, 2.*np.pi*guess_freq, 0., guess_offset]) 
 
    def sinfunc(t, A, w, p, c):  return A * np.sin(w*t + p) + c 
    boundary = ([-np.inf, -np.inf, -np.pi, -np.inf],[np.inf, np.inf, np.pi, np.inf]) 
    popt, pcov = scipy.optimize.curve_fit(sinfunc, tt, yy, p0=guess, bounds=boundary) 
    A, w, p, c = popt 
    f = w/(2.*np.pi) 
    fitfunc = lambda t: A * np.sin(w*t + p) + c 
    return {"amp": A, "omega": w, "phase": p, "offset": c, "freq": f, "period": 1./f, "fitfunc": fitfunc, "maxcov": np.max(pcov), "rawres": (guess,popt,pcov)} 

我收到以下错误:

RuntimeError: Optimal parameters not found: The maximum number of function evaluations is exceeded. 

如果我将边界设置为无穷大并将边界线更改为简单,

boundary = ([-np.inf, -np.inf, -np.inf, -np.inf],[np.inf, np.inf, np.inf, np.inf]) 

该功能有效。

要测试你可以做的功能:

import pylab as plt 
 
N, amp, omega, phase, offset, noise = 500, 1., 2., .5, 4., 3 
#N, amp, omega, phase, offset, noise = 50, 1., .4, .5, 4., .2 
#N, amp, omega, phase, offset, noise = 200, 1., 20, .5, 4., 1 
tt = numpy.linspace(0, 10, N) 
tt2 = numpy.linspace(0, 10, 10*N) 
yy = amp*numpy.sin(omega*tt + phase) + offset 
yynoise = yy + noise*(numpy.random.random(len(tt))-0.5) 
 
res = fit_sin(tt, yynoise) 
print( "Amplitude=%(amp)s, Angular freq.=%(omega)s, phase=%(phase)s, offset=%(offset)s, Max. Cov.=%(maxcov)s" % res ) 
 
plt.plot(tt, yy, "-k", label="y", linewidth=2) 
plt.plot(tt, yynoise, "ok", label="y with noise") 
plt.plot(tt2, res["fitfunc"](tt2), "r-", label="y fit curve", linewidth=2) 
plt.legend(loc="best") 
plt.show() 

特别是我只是试图将拟合的阶段 p 限制在 -np.pi 和 np.pi 之间,其他可以是无穷大。

我正在使用此函数的实际数据是干净的,拟合快速且非常准确,但有时当数据开始于或接近 +/- np.pi,它将适合 2*np.pi 阶段。

我也无法手动捕捉到它,因为它适用于数千个数据集,而且我正在查看它们之间的相对相位差异。

感谢任何帮助,谢谢。

请您参考如下方法:

我修复了它,对于给我带来麻烦的特定数据集,我的函数正在拟合负振幅,然后迫使我的相位值 np.pi 大于预期。

我会在这里留下这个答案,供任何在正弦波拟合方面遇到类似问题的人使用!