gpt4 book ai didi

r - R : using tsCV() with tslm()-Models 中的时间序列交叉验证

转载 作者:行者123 更新时间:2023-12-01 22:08:12 29 4
gpt4 key购买 nike

我目前正在尝试使用时间序列交叉验证来评估 tslm 模型。我想使用固定模型(没有参数重新估计)查看去年评估期的 1 到 3 步超前水平预测。

我很难从 forecast-library 中获取 tsCVtslm 来很好地协同工作。我错过了什么?

library(forecast)
library(ggfortify)

AirPassengers_train <- head(AirPassengers, 100)
AirPassengers_test <- tail(AirPassengers, 44)

## Holdout Evaluation
n_train <- length(AirPassengers_train)
n_test <- length(AirPassengers_test)
pred_train <- ts(rnorm(n_train))
pred_test <- ts(rnorm(n_test))

fit <- tslm(AirPassengers_train ~ trend + pred_train)

forecast(fit, newdata = data.frame(pred_train = pred_test)) %>%
accuracy(AirPassengers_test)
#> ME RMSE MAE MPE MAPE MASE
#> Training set 1.135819e-15 30.03715 23.41818 -1.304311 10.89785 0.798141
#> Test set 3.681350e+01 76.39219 55.35298 6.513998 11.96379 1.886546
#> ACF1 Theil's U
#> Training set 0.6997632 NA
#> Test set 0.7287923 1.412804


## tsCV Evaluation
fc_reg <- function(x) forecast(x, newdata = data.frame(pred_train = pred_test),
h = h, model = fit)

tsCV(AirPassengers_test, fc_reg, h = 1)
#> Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
#> 1957 NA NA NA NA NA NA NA NA
#> 1958 NA NA NA NA NA NA NA NA NA NA NA NA
#> 1959 NA NA NA NA NA NA NA NA NA NA NA NA
#> 1960 NA NA NA NA NA NA NA NA NA NA NA NA


forecast(AirPassengers_test, newdata = data.frame(pred_train = pred_test),
h = 1, model = fit)
#> Error in forecast.ts(AirPassengers_test, newdata = data.frame(pred_train = pred_test),
#> : Unknown model class

我有一种感觉,https://gist.github.com/robjhyndman/d9eb5568a78dbc79f7acc49e22553e96是相关的。我如何将其应用于上述场景?

最佳答案

对于时间序列交叉验证,您应该为每个训练集拟合一个单独的模型,而不是传递现有模型。对于预测变量,函数需要能够在拟合每个模型时获取相关元素,并在生成预测时获取其他元素。

以下将起作用。

fc <- function(y, h, xreg)
{
if(NROW(xreg) < length(y) + h)
stop("Not enough xreg data for forecasting")
X <- xreg[seq_along(y),]
fit <- tslm(y ~ X)
X <- xreg[length(y)+seq(h),]
forecast(fit, newdata=X)
}

# Predictors of the same length as the data
# and with the same time series characteristics.
pred <- ts(rnorm(length(AirPassengers)), start=start(AirPassengers),
frequency=frequency(AirPassengers))

# Now pass the whole time series and the corresponding predictors
tsCV(AirPassengers, fc, xreg=pred)

如果您有多个预测变量,则 xreg 应该是一个矩阵。

关于r - R : using tsCV() with tslm()-Models 中的时间序列交叉验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50255912/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com