我有一些想要使用2、3或4度的傅立叶级数拟合的数据。
虽然这个问题的答案在堆栈溢出得到接近我想要使用SciPy的做,他们已经预先定义的系数作为头= 0.045始终。我希望我的拟合找到具有95%置信区间的可能系数(a0,w1,w2,w3等),就像傅立叶级数的MATLAB曲线拟合等效一样。我看到的另一个选项是使用来自sympy的fourier_series,但是此函数仅适用于适合已定义函数的符号参数,而不适用于原始数据。
1)有没有一种方法可以使sympy fourier_series接收原始数据,而不是使用该库的函数或其他替代方法?
2)或给定数据曲线拟合,因为存在多个未知数(系数)
sympy
如果愿意,可以使用我为此目的编写的程序包,与数据拟合代码保持非常接近的状态symfit
。它基本上是scipy
使用sympy
接口包装的。使用symfit
,您可以执行以下操作:
from symfit import parameters, variables, sin, cos, Fit
import numpy as np
import matplotlib.pyplot as plt
def fourier_series(x, f, n=0):
"""
Returns a symbolic fourier series of order `n`.
:param n: Order of the fourier series.
:param x: Independent variable
:param f: Frequency of the fourier series
"""
# Make the parameter objects for all the terms
a0, *cos_a = parameters(','.join(['a{}'.format(i) for i in range(0, n + 1)]))
sin_b = parameters(','.join(['b{}'.format(i) for i in range(1, n + 1)]))
# Construct the series
series = a0 + sum(ai * cos(i * f * x) + bi * sin(i * f * x)
for i, (ai, bi) in enumerate(zip(cos_a, sin_b), start=1))
return series
x, y = variables('x, y')
w, = parameters('w')
model_dict = {y: fourier_series(x, f=w, n=3)}
print(model_dict)
这将打印出我们想要的符号模型:
{y: a0 + a1*cos(w*x) + a2*cos(2*w*x) + a3*cos(3*w*x) + b1*sin(w*x) + b2*sin(2*w*x) + b3*sin(3*w*x)}
接下来,我将其设置为简单的步进函数,以向您展示其工作原理:
# Make step function data
xdata = np.linspace(-np.pi, np.pi)
ydata = np.zeros_like(xdata)
ydata[xdata > 0] = 1
# Define a Fit object for this model and data
fit = Fit(model_dict, x=xdata, y=ydata)
fit_result = fit.execute()
print(fit_result)
# Plot the result
plt.plot(xdata, ydata)
plt.plot(xdata, fit.model(x=xdata, **fit_result.params).y, color='green', ls=':')
这将打印:
Parameter Value Standard Deviation
a0 5.000000e-01 2.075395e-02
a1 -4.903805e-12 3.277426e-02
a2 5.325068e-12 3.197889e-02
a3 -4.857033e-12 3.080979e-02
b1 6.267589e-01 2.546980e-02
b2 1.986491e-02 2.637273e-02
b3 1.846406e-01 2.725019e-02
w 8.671471e-01 3.132108e-02
Fitting status message: Optimization terminated successfully.
Number of iterations: 44
Regression Coefficient: 0.9401712713086535
并产生以下图:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句