SciPy Minimumsq适合正弦波失败 [英] SciPy leastsq fit to a sine wave failing

查看:120
本文介绍了SciPy Minimumsq适合正弦波失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚我在这里不明白什么。

I am trying to figure out what it is I don't understand here.

我正在关注 http://www.scipy.org/Cookbook/FittingData 并尝试拟合正弦波。真正的问题是卫星磁力计数据,该数据在旋转的航天器上产生了很好的正弦波。我创建了一个数据集,然后尝试使其适合以恢复输入。

I am following http://www.scipy.org/Cookbook/FittingData and trying to fit a sine wave. The real problem is satellite magnetometer data which makes a nice sine wave on a spinning spacecraft. I created a dataset then am trying to fit it to recover the inputs.

这是我的代码:

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)

是哪个情节:

Which makes this plot:

恢复的拟合参数 [44.2434221897 8.094832581 -61.6204033699] 与我刚开始的内容没有任何相似之处。

The recovered fit parameters of [44.2434221897 8.094832581 -61.6204033699] have no resemblance to what I started with.

有人对我不明白或做错的事情有想法吗?

Any thoughts on what I am not understanding or doing wrong?

scipy.__version__
'0.10.1'






编辑:
建议修复一个参数。在上面的示例中,将幅度固定为 np.histogram(yReal)[1] [-1] 仍然会产生不可接受的输出。适合度: [175.0 8.31681375217 6.0] 我应该尝试其他适合度的方法吗?


Fixing one parameter was suggested. In the example above fixing the amplitude to np.histogram(yReal)[1][-1] still produces unacceptable output. Fits: [175.0 8.31681375217 6.0] Should I try a different fitting method? Suggestions on which?

推荐答案

以下代码实现了Zhenya的一些想法。
它使用

Here is some code implementing some of Zhenya's ideas. It uses

yhat = fftpack.rfft(yReal)
idx = (yhat**2).argmax()
freqs = fftpack.rfftfreq(N, d = (xReal[1]-xReal[0])/(2*pi))
frequency = freqs[idx]

猜测数据的主要频率,并且

to guess the main frequency of the data, and

amplitude = yReal.max()

来猜测振幅。

import numpy as np
import scipy.optimize as optimize
import scipy.fftpack as fftpack
import matplotlib.pyplot as plt
pi = np.pi
plt.figure(figsize = (15, 5))

# generate a perfect data set (my real data have tiny error)
def mysine(x, a1, a2, a3):
    return a1 * np.sin(a2 * x + a3)

N = 5000
xmax = 10
xReal = np.linspace(0, xmax, N)
a1 = 200.
a2 = 2*pi/10.5  # omega, 10.5 is the period
a3 = np.deg2rad(10.) # 10 degree phase offset
print(a1, a2, a3)
yReal = mysine(xReal, a1, a2, a3) + 0.2*np.random.normal(size=len(xReal))

yhat = fftpack.rfft(yReal)
idx = (yhat**2).argmax()
freqs = fftpack.rfftfreq(N, d = (xReal[1]-xReal[0])/(2*pi))
frequency = freqs[idx]

amplitude = yReal.max()
guess = [amplitude, frequency, 0.]
print(guess)
(amplitude, frequency, phase), pcov = optimize.curve_fit(
    mysine, xReal, yReal, guess)

period = 2*pi/frequency
print(amplitude, frequency, phase)

xx = xReal
yy = mysine(xx, amplitude, frequency, phase)
# plot the real data
plt.plot(xReal, yReal, 'r', label = 'Real Values')
plt.plot(xx, yy , label = 'fit')
plt.legend(shadow = True, fancybox = True)
plt.show()

收益

(200.0, 0.5983986006837702, 0.17453292519943295)   # (a1, a2, a3)
[199.61981404516041, 0.61575216010359946, 0.0]     # guess
(200.06145097308041, 0.59841420869261097, 0.17487141943703263) # fitted parameters

请注意,使用fft,频率的猜测已经非常接近最终拟合参数。

Notice that by using fft, the guess for the frequency is already pretty close to final fitted parameter.

似乎您不需要修复任何参数。
通过使频率猜测接近于实际值, optimize.curve_fit 能够收敛到一个合理的答案。

It seems you do not need to fix any of the parameters. By making the frequency guess closer to the actual value, optimize.curve_fit is able to converge to a reasonable answer.

这篇关于SciPy Minimumsq适合正弦波失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆