在Python上使用scipy.least_squares估计正弦波频率

时间:2018-11-21 07:01:18

标签: python scipy least-squares non-linear-regression

我正在尝试使用scipy.least_squares和Python来估计正弦波频率。我不明白为什么它不起作用。 我的代码是:

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

def generate_data(t, A0, A, omega, phase):
    y = A0 + A * np.sin(omega * t + phase)
    return y


#  Init params
A0 = 0
A = 7.744444
omega = 2*np.pi*1 #2*np.pi*0.2
phase = np.pi/2
t_min = 0
t_max = 100
#  Model of sine
t_model = np.linspace(t_min, t_max, 100)
y_model = generate_data(t_model, A0= A0, A=A, omega=omega, phase=phase)
plt.plot(t_model,y_model)

#  Target func
def fun(x, t, y):
    return (x[0]*np.sin(x[1] * t + x[2])) - y


x0 = np.ones(3)
res_lsq = least_squares(fun, x0, args=(t_model, y_model))

res_robust = least_squares(fun, x0, loss='soft_l1', f_scale=0.1, args=(t_model, y_model))
print('res_robust.x,',res_robust.x[1], 'expect:',omega)
print('res_lsq.x = ', res_lsq.x[1], 'expect:',omega)

0 个答案:

没有答案