【发布时间】:2020-10-23 07:58:26
【问题描述】:
我正在尝试使用 hts 包中的 combinef 函数来协调自定义预测。 我想比较重组的自动化方法和重组的自定义预测 (https://otexts.com/fpp2/reconciliation.html)
combinef (forecast.gts) 的自动计算部分非常用户友好。 如果需要自下而上的预测,那么您可以设置 method = "comb"。 如果需要对账,则可以通过将参数 weights 设置为 weights = c("wls", "ols", "nseries") 在加权最后一个正方形、普通最后一个正方形和结构缩放之间进行选择。
对于 combinef(),默认的 weights 参数是普通的最后一个正方形,因此这种方法可以很容易地实现。 在另一个线程中已经解释了如何应用自下而上的方法 (How to get top down forecasts using `hts::combinef()`?)。
我现在对使用“wls”以及“nseries”也很感兴趣。 有没有简单的方法来实现这个?
编辑 我深入研究了 forecast.gts() 和 combinef() 函数的原始代码。我最终得到了这个自定义代码:
library(hts)
library(rlist)
#forecast grouped time series by custom function
ally_df <- aggts(htseg1) %>% as.data.frame
forecast_list <- apply(ally_df, 2, function(x){x %>% auto.arima %>% forecast(h = 12)})
ally_fitted <- lapply(forecast_list, function(x){x$fitted %>% as.data.frame}) %>% list.cbind
colnames(ally_fitted) <- colnames(ally)
ally_forecast <- lapply(forecast_list, function(x){x$mean %>% as.data.frame}) %>% list.cbind
colnames(ally_forecast) <- colnames(ally)
#create weights for reconciliation
recomb_approaches <- c("wls", "ols", "nseries", "bu")
recomb_approach <- recomb_approaches[1]
if(recomb_approach == "bu"){
weights <- c(rep(0, ncol(ally_df)-ncol(htseg1$bts)), rep(1, ncol(htseg1$bts)))
}else if(recomb_approach == "ols"){
weights <- NULL
}else if(recomb_approach == "wls"){
tmp.resid <- ally_df - ally_fitted
weights <- 1/colMeans(tmp.resid^2, na.rm = TRUE)
}else if(recomb_approach == "nseries"){
# A function to calculate No. of groups at each level
Mlevel <- function(xgroup) {
m <- apply(xgroup, 1, function(x) length(unique(x)))
return(m)
}
# A function to get the inverse of row sums of S matrix
InvS4g <- function(xgroup) {
mlevel <- Mlevel(xgroup)
len <- length(mlevel)
repcount <- mlevel[len]/mlevel
inv.s <- 1/unlist(mapply(rep, repcount, mlevel, SIMPLIFY = FALSE))
return(inv.s)
}
weights <- InvS4g(htseg1$groups)
}
ally_forecast_recombined_df <- combinef(ally_forecast
, nodes = get_nodes(htseg1)
, weights = weights
, algorithms = "lu"
, keep = "bottom"
, parallel = TRUE
, num.cores = cores
)
这能解决问题吗?
【问题讨论】:
标签: r time-series hierarchy forecast