给定正弦曲线fi的预测值

2023-02-06 13:31:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Python来拟合一个正弦函数的时间序列。我找到了一个很好的匹配,现在我想能够预测未来的价值。。我在这里迷路了。在

我得到的是:

timeSeries = [0.01146, 0.00724, 0.00460, 0.00192, 0.00145, 0.01559, 0.02585, 0.04118, 0.05073, 0.01966, 0.01486, 0.02784]

import numpy as np
from scipy.optimize import curve_fit

def createSinFromFit(x, freq, amplitude, phase, offset):
    return np.sin(x * freq + phase) * amplitude + offset

def sinRegr(series):
    t = np.linspace(0, 4*np.pi, len(series))
    guess_freq = 1
    guess_amplitude = 3*np.std(series)/(2**0.5)
    guess_phase = 0
    guess_offset = np.mean(series)
    p0=[guess_freq, guess_amplitude, guess_phase, guess_offset]
    fit = curve_fit(createSinFromFit, t, series, p0=p0)
    results = createSinFromFit(t,*fit[0])
    return results

plotThis = sinRegr(timeSeries)

此代码生成您在图中看到的配件:

![pic]http://i.stack.imgur.com/sNdIu.png

如何扩展sin函数,使之预测序列的未来点?i、 e.怎样才能让正弦图的跨度在右边,超出“已知”数据点覆盖的区域?在


Tags: 函数importnp序列fitoffsetseriestimeseriesfreqguess正弦phasep0amplitudecreatesinfromfit
1条回答
网友
1楼 · 发布于 2023-02-06 13:31:04

您需要区分数据时间线(输入)和拟合时间线(输出)。一旦你这样做,方法就相当清楚了。下面我把它们叫做tdatatfit

enter image description here

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

tdata = np.linspace(0, 10)
timeSeries = np.sin(tdata) + .4*np.random.random(tdata.shape)

def createSinFromFit(x, freq, amplitude, phase, offset):
    return np.sin(x * freq + phase) * amplitude + offset

def sinRegr(tdata, series):
    tfit = np.linspace(0, 6*np.pi, len(series))
    guess_freq = .2
    guess_amplitude = 3*np.std(series)/(2**0.5)
    guess_phase = 0
    guess_offset = np.mean(series)
    p0=[guess_freq, guess_amplitude, guess_phase, guess_offset]
    fit = curve_fit(createSinFromFit, tdata, series, p0=p0)   # use tdata to create the fit
    results = createSinFromFit(tfit,*fit[0])                  # use tfit to generate a new curve 
    return tfit, results

tfit, plotThis = sinRegr(tdata, timeSeries)

plt.plot(tfit, plotThis)
plt.plot(tdata, timeSeries, "ro")
plt.show()

相关问题 更多 >