我正在使用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)
此代码生成您在此图片中看到的拟合:
如何扩展sin函数以便预测系列的未来点?也就是说,如何将正弦曲线跨越到“已知”数据点覆盖的区域之外?
答案 0 :(得分:1)
您需要区分数据时间轴(输入)和拟合时间轴(输出)。一旦你这样做,方法就相当清楚了。下面我称他们为tdata
和tfit
:
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()