时间序列交叉验证的实现

时间:2021-01-08 10:52:12

标签: r time-series cross-validation

我正在处理 M3 比赛月度数据的时间序列 551。

所以,我的数据是:

library(forecast)
library(Mcomp)
# Time Series
# Subset the M3 data to contain the relevant series 
ts.data<- subset(M3, 12)[[551]]
print(ts.data)

我想对样本内间隔的最后 18 个观察值实施时间序列交叉验证

有些人通常会将此称为“滚动原点的预测评估”或类似的东西。

我怎样才能做到这一点?什么是样本内间隔?我必须评估哪个时间序列?

我很困惑,欢迎任何帮助点亮它。

1 个答案:

答案 0 :(得分:1)

tsCV 包的 forecast 函数是一个很好的起点。

从其文档中,

<块引用>

tsCV(y, forecastfunction, h = 1, window = NULL, xreg = NULL, initial = 0, . ..)

让‘y’包含时间序列 y[1:T]。那么“预测函数”是 连续应用于时间序列 y[1:t],对于​​ t=1,...,T-h, 做出预测 f[t+h]。误差由 e[t+h] = y[t+h]-f[t+h]。

即首先 tsCV 将模型拟合到 y[1],然后预测 y[1 + h],接下来将模型拟合到 y[1:2] 并预测 y[2 + h] 等等步骤。

tsCV 函数返回预测误差。

将此应用于 ts.data 的训练数据

# function to fit a model and forecast
fmodel <- function(x, h){
  forecast(Arima(x, order=c(1,1,1), seasonal = c(0, 0, 2)), h=h)
}
 
# time-series CV
cv_errs <- tsCV(ts.data$x, fmodel, h = 1)

# RMSE of the time-series CV
sqrt(mean(cv_errs^2, na.rm=TRUE))
# [1] 778.7898

在你的情况下,你可能应该

  1. 为 ts.data$x 拟合模型,然后预测 ts.data$xx[1]
  2. 拟合模式 c(ts.data$x, ts.data$xx[1]) 和 forecast(ts.data$xx[2]),