我正在使用this question中描述的技术来拟合一些数据(我在这里对其进行了硬编码),看起来效果不错。然而,我意识到我的扩展数据并不是我想要的那样,所以我使用了'endpoint=False',这样我的扩展数据就从17增加到了27.5,步长为0.5。在这样做的时候,西皮警告我:
minpack.py:794: OptimizeWarning: Covariance of the parameters could not be estimated category=OptimizeWarning)
也许这是预期的工作,我遗漏了一些曲线拟合的部分,或者傅里叶函数的工作原理,但是我真的希望能够用正确的(尽管只是稍微不同的)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
无端点=假: curve fit results plot
这个问题是由
以及
np.cos((deg+1) * 2 * np.pi * x)
如果
x
包含步长为0.5的值,则传递给三角函数的值是pi
的倍数。这使得sin
总是返回0,cos
返回+1或-1。由于这种简并性,结果函数无法拟合相关问题 更多 >
编程相关推荐