Statsmodels ARMA 训练数据与预测测试数据

Statsmodels ARMA training data vs test data for prediction

我正在尝试测试 ARMA 模型,并完成此处提供的示例:

http://www.statsmodels.org/dev/examples/notebooks/generated/tsa_arma_0.html

我不知道是否有一种直接的方法可以在训练数据集上训练模型,然后在测试数据集上对其进行测试。在我看来,您必须在整个数据集上拟合模型。然后您可以进行样本内预测,它使用与您用于训练模型的数据集相同的数据集。或者您可以进行样本外预测,但这必须从训练数据集的末尾开始。相反,我想做的是在训练数据集上拟合模型,然后 运行 模型在一个完全不同的数据集上,该数据集不是训练数据集的一部分,并获得一系列 1 步预测。

为了说明这个问题,这里是上面 link 中的缩写代码。您会看到该模型正在拟合 1700-2008 年的数据,然后预测 1990-2012 年。我遇到的问题是 1990-2008 年已经是用于拟合模型的数据的一部分,所以我认为我正在对相同的数据进行预测和训练。我希望能够获得一系列没有前瞻性偏差的单步预测。

import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm

dta = sm.datasets.sunspots.load_pandas().data
dta.index = pandas.Index(sm.tsa.datetools.dates_from_range('1700', '2008'))
dta = dta.drop('YEAR',1)

arma_mod30 = sm.tsa.ARMA(dta, (3, 0)).fit(disp=False)
predict_sunspots = arma_mod30.predict('1990', '2012', dynamic=True)

fig, ax = plt.subplots(figsize=(12, 8))
ax = dta.ix['1950':].plot(ax=ax)
fig = arma_mod30.plot_predict('1990', '2012', dynamic=True, ax=ax, plot_insample=False)

plt.show()

您可以将数据分成两个数据集。比如训练数据是原始数据到去年1月1日的切片,测试数据是去年1月到年底的切片。然后,根据拟合模型预测测试集的长度。

在我问这个问题后的 16 个月里,我在 statsmodels 中学到了更多关于 ARIMA 建模的知识,我认为 ARMA 或 ARIMA 模型不支持我正在寻找的行为,但它在 SARIMAX 模型中受支持。请参阅以下代码,基于 statsmodels.org 中的示例。绿线表示从 1700-1990 训练的 ARIMA(10,0,0) 模型(或 AR(10))模型,然后从 1990-2012 动态预测。

https://www.statsmodels.org/dev/examples/notebooks/generated/statespace_sarimax_stata.html

import pandas
import matplotlib.pyplot as plt
import statsmodels.api as sm

dta = sm.datasets.sunspots.load_pandas().data
dta.index = pandas.Index(sm.tsa.datetools.dates_from_range('1700', '2008'))
dta = dta.drop('YEAR', 1)

arma_mod30 = sm.tsa.ARMA(dta, (3, 0)).fit(disp=False)
predict_sunspots = arma_mod30.predict('1990', '2012', dynamic=True)

fig, ax = plt.subplots(figsize=(12, 8))
ax = dta.ix['1950':].plot(ax=ax)
fig = arma_mod30.plot_predict('1990', '2012', dynamic=True, ax=ax, plot_insample=False)

# Fit the model
mod = sm.tsa.statespace.SARIMAX(dta.loc[:'1990'], order=(10, 0, 0))
fit_res = mod.fit(disp=False)

# Create new model, but instead of fit, copy the params from the first model
mod = sm.tsa.statespace.SARIMAX(dta, order=(10, 0, 0))
res = mod.filter(fit_res.params)

# Dynamic predictions
predict_dy = res.get_prediction(dynamic='1990', end='2012')
predict_dy = predict_dy.predicted_mean
predict_dy['1990':].plot(ax=ax)

plt.show()