我在想我不明白的是什么。
我正在跟踪http://www.scipy.org/Cookbook/FittingData并尝试拟合正弦波。真正的问题是卫星磁强计数据在旋转的航天器上产生一个很好的正弦波。我创建了一个数据集,然后尝试对其进行调整以恢复输入。
这是我的代码:
import numpy as np
from scipy import optimize
from scipy.optimize import curve_fit, leastsq
import matplotlib.pyplot as plt
class Parameter:
def __init__(self, value):
self.value = value
def set(self, value):
self.value = value
def __call__(self):
return self.value
def fit(function, parameters, y, x = None):
def f(params):
i = 0
for p in parameters:
p.set(params[i])
i += 1
return y - function(x)
if x is None: x = np.arange(y.shape[0])
p = [param() for param in parameters]
return optimize.leastsq(f, p, full_output=True, ftol=1e-6, xtol=1e-6)
# generate a perfect data set (my real data have tiny error)
def mysine(x, a1, a2, a3):
return a1 * np.sin(a2 * x + a3)
xReal = np.arange(500)/10.
a1 = 200.
a2 = 2*np.pi/10.5 # omega, 10.5 is the period
a3 = np.deg2rad(10.) # 10 degree phase offset
yReal = mysine(xReal, a1, a2, a3)
# plot the real data
plt.figure(figsize=(15,5))
plt.plot(xReal, yReal, 'r', label='Real Values')
# giving initial parameters
amplitude = Parameter(175.)
frequency = Parameter(2*np.pi/8.)
phase = Parameter(0.0)
# define your function:
def f(x): return amplitude() * np.sin(frequency() * x + phase())
# fit! (given that data is an array with the data to fit)
out = fit(f, [amplitude, frequency, phase], yReal, xReal)
period = 2*np.pi/frequency()
print amplitude(), period, np.rad2deg(phase())
xx = np.linspace(0, np.max(xReal), 50)
plt.plot( xx, f(xx) , label='fit')
plt.legend(shadow=True, fancybox=True)
这使得这个情节:
恢复的[44.2434221897 8.094832581 -61.6204033699]
拟合参数与我开始使用的参数没有相似之处。
有没有想过我不理解或做错了什么?
scipy.__version__
'0.10.1'
编辑:
建议修正一个参数。在上面的例子中,将振幅固定到np.histogram(yReal)[1][-1]
仍然会产生不可接受的输出。拟合:[175.0 8.31681375217 6.0]
我应该尝试不同的拟合方法吗?建议是什么?
从我玩
leastsq
(没有菜谱上的花哨内容,只是直接打给leastsq
——顺便说一句,full_output=True
是你的朋友)可以看出,很难一次将振幅、频率和相位三者都匹配起来。另一方面,如果我固定振幅,并与频率和相位相匹配,它也会工作;如果我固定频率,并与振幅和相位相匹配,它也会工作。这里不止一条路。最简单的一个可能是什么——如果你确定你只有一个正弦波(这很容易用傅里叶变换检查),那么你就可以从信号的连续最大值之间的距离知道频率。然后拟合其余两个参数。
如果你得到的是几个谐波的混合物,那么,再一次,傅里叶变换会告诉你这一点。
下面是一些代码,实现了振亚的一些想法。 它使用
猜测数据的主频,以及
去猜振幅。
收益率
注意,通过使用fft,对频率的猜测已经非常接近最终的拟合参数。
似乎不需要修复任何参数。 通过使频率猜测更接近实际值,
optimize.curve_fit
能够收敛到一个合理的答案。相关问题 更多 >
编程相关推荐