试图为多个嘈杂的正弦波寻找最佳拟合线

时间:2015-06-11 14:00:43

标签: python regression best-fit-curve

我试图为多个嘈杂的正弦波创建平均迹线/最佳拟合线。这是我为创建正弦波而生成的代码:

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



x = np.arange(0,10,.05)
noise = np.random.normal(0,.05,200)
wave = np.sin(x)
y = noise + wave

noise2 = np.random.normal(0,.05,200)
y2 = noise2 + wave

noise3 = np.random.normal(0,.05,200)
y3 = noise3 + wave


plt.plot(x, y)
plt.plot(x, y2)
plt.plot(x, y3)
plt.xlabel('x-axis')
plt.ylabel('y-axis')

plt.show()

我在网上搜索这个网站时遇到的问题是,大多数人都在为一组数据点而不是多行创建最佳拟合线。

任何建议都将不胜感激,谢谢!

这是我迄今为止所尝试过的:

guess_mean = np.mean(y)
guess_std = 3.0*np.std(y)/(2**.5)
guess_phase = 0

first_guess= guess_std*np.sin(x+guess_phase) + guess_mean

plt.plot(first_guess, label='first guess')

但这不起作用,我认为是因为这段时间已经过去了。

1 个答案:

答案 0 :(得分:0)

有几种方法可以做到这一点。以下是我认为最简单的实现方法。

首先,让我们定义一个带有元组(a, b, c)的函数,并找到 a * sin(b * x + c)与{{1}的拟合之和}}

y, y1, y2

有了这个,我们可以致电this question

def f(params):
    y_hat = params[0] * np.sin(params[1] * x + params[2])
    return np.linalg.norm(y_hat - y) + np.linalg.norm(y_hat - y2) + np.linalg.norm(y_hat - y3)

要进行健全性检查,请尝试解决方案(import scipy.optimize as optimize >> optimize.minimize(f, [1,1,1]) status: 0 success: True njev: 28 nfev: 140 hess_inv: array([[ 2.58018841e-03, -7.55654731e-05, 5.12200054e-04], [ -7.55654731e-05, 2.40734497e-04, -1.23067851e-03], [ 5.12200054e-04, -1.23067851e-03, 8.57449579e-03]]) fun: 2.1219465700417786 x: array([ 0.99811506, -1.00102866, 3.14393633]) message: 'Optimization terminated successfully.' jac: array([ -1.46031380e-06, -7.89761543e-06, -1.75833702e-06]) ):

[ 0.99811506, -1.00102866,  3.14393633]

enter image description here

Vs以上。嘈杂的数据:

enter image description here