xreg 参数 hts R 包 ARIMA

xreg parameter hts R package ARIMA

我正在尝试将外部回归器 xreg 添加到 hts 包中,但是我收到有关行数 (140) 的错误,尽管我的外部变量具有相同的数字。我检查了其他答案,但我的答案更简单:

这是可重现的例子

library(hts)
abc <- matrix(sample(1:100, 32*140, replace=TRUE), ncol=32)
colnames(abc) <- c(
  paste0("A0",1:5), 
  paste0("B0",1:9),"B10",
  paste0("C0",1:8),
  paste0("D0",1:5),
  paste0("E0",1:4)
)
abc <- ts(abc, start=2019, frequency=365.25/7)
x <- hts(abc, characters = c(1,2))

data <- window(x, start = 2019.000, end = 2021.166)
test <- window(x, start = 2021.185)

x2 <- runif(n = 140, min = 1, max = 10) #External regressor with the same size

fcastsxreg <- forecast( data, h = 2, method = "comb", algorithms = "lu",  fmethod = "arima", weights=, "wls", nonnegative=TRUE, xreg=x2)
accuracy(fcastsxreg, test, levels = 1)

错误消息是关于 abc 矩阵的 de 大小与 x2 向量之间的不匹配,尽管两者都有 140 行

Error in model.frame.default(formula = x ~ xregg, drop.unused.levels = TRUE) : 
  variable lengths differ (found for 'xregg')
In addition: Warning message:
In !is.na(x) & !is.na(rowSums(xregg)) :
  longer object length is not a multiple of shorter object length

谢谢

您的训练数据 data 具有层次结构中每个系列的 114 个观察值。您的回归器有 140 个观测值。因此,错误状态的长度有所不同。

您还需要为训练期提供 xreg 参数,为预测期提供 newxreg 参数。

另一个小问题是您的训练数据和测试数据之间存在一个观察结果,这可能是无意的。

这是对您的代码进行的修改。

library(hts)
abc <- matrix(sample(1:100, 32 * 140, replace = TRUE), ncol = 32)
colnames(abc) <- c(
  paste0("A0", 1:5),
  paste0("B0", 1:9), "B10",
  paste0("C0", 1:8),
  paste0("D0", 1:5),
  paste0("E0", 1:4)
)
abc <- ts(abc, start = 2019, frequency = 365.25/7)
x <- hts(abc, characters = c(1, 2))

data <- window(x, end = 2021.166)
test <- window(x, start = 2021.167)

# External regressor with the same size as training and test data combined
x2 <- ts(runif(n = 140, min = 1, max = 10), start = 2019, frequency = 365.25/7)

fcastsxreg <- forecast(data,
  fmethod = "arima", nonnegative = TRUE,
  xreg = window(x2, end = 2021.166), newxreg = window(x2, start = 2021.167)
)
accuracy(fcastsxreg, test, levels = 1)
#>              A          B          C          D           E
#> ME   -9.278558 11.0833938 -4.7985252  5.8634578  -6.5853672
#> RMSE 58.741525 84.4354712 92.0376431 66.1268442  55.6521141
#> MAE  48.428461 69.6798318 78.7112730 55.7808292  45.1403745
#> MAPE 21.854145 13.4673244 20.5752506 23.0548665  31.0934899
#> MPE  -9.642284 -0.5202464 -6.0976324 -5.0032980 -15.7431146
#> MASE  0.638436  0.5647993  0.7868589  0.7730021   0.5935744

reprex package (v2.0.1)

于 2022-01-26 创建