scipy Python中的正弦曲线拟合

iecba09b  于 2023-01-26  发布在  Python
关注(0)|答案(1)|浏览(192)

我想在这组数据中拟合正弦曲线的一个凸起

xData = np.array([1.7, 8.8, 15, 25, 35, 45, 54.8, 60, 64.7, 70])
yData = np.array([30, 20, 13.2, 6.2, 3.9, 5.2, 10, 14.8, 20, 27.5])

我已经成功地用scipy.optimiz.curve_fit函数拟合了一条抛物线,但是我不知道如何用正弦曲线拟合数据。
以下是我目前所做的:

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import scipy.interpolate as inp

xData = np.array([1.7, 8.8, 15, 25, 35, 45, 54.8, 60, 64.7, 70])
yData = np.array([30, 20, 13.2, 6.2, 3.9, 5.2, 10, 14.8, 20, 27.5])

def model_parabola(x, a, b, c):
    return a * (x - b) ** 2 + c

def model_sine(x, amp, omega, phase, c, z):
    return amp * np.sin(omega * (x - z) + phase) + c


poptsin, pcovsine = curve_fit(model_sine, xData, yData, p0=[np.std(yData) *2 **0.5, 2 * np.pi, 0, np.mean(yData), 0])
popt, pcov = curve_fit(model_parabola, xData, yData, p0=[2, 3, 4])

# for parabola
aopt, bopt, copt = popt
xmodel = np.linspace(min(xData), max(xData), 100)
ymodel = model_parabola(xmodel, aopt, bopt, copt)

print(poptsin)
# for sine curve
ampopt, omegaopt, phaseopt, ccopt, zopt = poptsin
xSinModel = np.linspace(min(xData), max(xData), 100)
ySinModel = model_sine(xSinModel, ampopt, omegaopt, phaseopt, ccopt, zopt)

y_fit = model_sine(xSinModel, *poptsin)

plt.scatter(xData, yData)
plt.plot(xmodel, ymodel, 'r-')
plt.plot(xSinModel, ySinModel, 'g-')

plt.show()

这就是结果

rsaldnfx

rsaldnfx1#

尝试以下方法:

def model_sine(x, amp, omega, phase, offset):
    return amp * np.sin(omega * x + phase) + offset

poptsin, pcovsine = curve_fit(model_sine, xData, yData, 
                  p0=[np.max(yData) - np.min(yData), np.pi/70, 3, np.max(yData)],
                  maxfev=5000)

您不需要同时使用phasez;一个就够了。
我需要增加允许的函数求值次数(maxfev);如果数据被完全归一化,则这可能是不必要的,尽管它仍然足够接近1阶。

相关问题