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

问题描述 投票:0回答:2

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

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

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

为了说明问题,这里是上面链接中的缩写代码。您会看到该模型拟合 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()

python statsmodels autoregressive-models
2个回答
4
投票

自从我提出这个问题以来的 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()


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.