curve_fit 在自变量中使用 endpoint=False 时失败

curve_fit fails when using endpoint=False in independent variable

我正在使用 中描述的技术拟合一些数据(我已在此处对其进行硬编码),它似乎工作正常。但是,我意识到我的扩展数据并不完全是我想要的,所以我使用 'endpoint=False' 以便我的扩展数据以 0.5 的步长从 17 增加到 27.5。这样做时,scipy 警告我:

minpack.py:794: OptimizeWarning: Covariance of the parameters could not be estimated category=OptimizeWarning) 

也许这是按预期工作的,我遗漏了 curve_fit 的某些部分,或者傅立叶函数的工作原理,但我真的很想能够用正确的方式来适应它(尽管只是稍微不同的)x 值。我的 y 值确实有一个偏移量,当它成功运行时,它会被移除,这对我来说很好。

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

ydata = [48.97266579, 54.97148132, 65.33787537, 69.55269623, 56.5559082,  41.52973366,
 28.06554699, 19.01652718, 16.74026489, 19.38094521, 25.63856506, 24.39780998,
 18.99308014, 30.67970657, 31.52746582, 45.38796043, 45.3911972,  42.38343811,
 41.90969849, 38.00998878, 49.11366463, 70.14483643]
xdata = np.linspace(17, 28, 22, endpoint=False) #, endpoint=False

def make_fourier(na, nb):
    def fourier(x, *a):
        ret = 0.0
        for deg in range(0, na):
            ret += a[deg] * np.cos((deg+1) * 2 * np.pi * x)
        for deg in range(na, na+nb):
            ret += a[deg] * np.sin((deg+1) * 2 * np.pi * x)
        return ret
    return fourier

def obtain_fourier_coef(ydata, harms):
    popt, pcov = curve_fit(make_fourier(harms, harms), xdata, ydata, [0.0]*harms*2)
    plt.plot(xdata, (make_fourier(harms,harms))(xdata, *popt))
    plt.show()

plt.plot(xdata, ydata)
obtain_fourier_coef(ydata, 10)

端点=False: curve fit results plot

没有端点=False: curve fit results plot

问题是由

的组合引起的

[...] xdata increased from 17 to 27.5 in steps of 0.5.

np.cos((deg+1) * 2 * np.pi * x)

如果 x 包含步长为 0.5 的值,则传递给三角函数的值是 pi 的倍数。这使得 sin 总是 return 0 而 cos return 总是 +1 或 -1。由于这种退化,无法拟合生成的函数。