This R Markdown document contains the complete workflow to reproduce
the real-data meteorological forecasting application presented in
Section 5 of the manuscript “Bayesian Stacking of
Linear Distributional Meta-Models under Heteroscedastic Prediction
Errors: The bmetapred method”.
The analysis benchmarks bmetapred against
BayesVarSel, BAS, EBMAforecast,
and Standard Horseshoe regression on the University of Washington
Mesoscale Ensemble (srft) surface air temperature dataset
(\(p = 8\) physical numerical weather
prediction models) across four training sample size regimes: \(N_{\text{train}} \in \{50, 500, 2{,}000,
10{,}000\}\).
Note on Execution: Sections 2 and 3 (data loading, leak-free partitioning, common-anchor standardization,
fit_LOESSerror-scale calibration, summary diagnostics, and generation of Figure 6) execute in a few seconds and are enabled by default (eval = TRUE). The full MCMC benchmark loop across \(N_{\text{train}} \in \{50, 500, 2{,}000, 10{,}000\}\) in Section 4 is set toeval = FALSEby default so the document knits rapidly, while remaining ready for full execution.
cmdstanr InstallationThe proposed bmetapred package and all benchmark
dependencies are available directly on CRAN. For MCMC sampling, both
bmetapred and brms support either the standard
CRAN "rstan" backend or the "cmdstanr"
backend. For intensive computational tasks and large model spaces, we
highly recommend installing “cmdstanr”. The setup chunk below installs
any missing CRAN packages and optionally installs cmdstanr
if desired:
# 1. Install bmetapred and CRAN dependencies if missing
cran_packages <- c(
"bmetapred", "brms", "rstan", "loo", "BAS", "BayesVarSel", "EBMAforecast",
"scoringRules", "dplyr", "tidyr", "ggplot2", "patchwork",
"emmeans", "bayestestR", "flextable", "officer",
"future", "future.apply", "progressr",
"e1071", "nnet", "ranger", "rpart", "glmnet", "ensembleBMA"
)
missing_pkgs <- cran_packages[!sapply(cran_packages, requireNamespace, quietly = TRUE)]
if (length(missing_pkgs) > 0) {
install.packages(missing_pkgs)
}
# 2. (Optional) Silent installation of cmdstanr and CmdStan C++ backend
url_stan <- paste0("https:", "//", "stan-dev.r-universe.dev")
url_cran <- paste0("https:", "//", "cloud.r-project.org")
if (!requireNamespace("cmdstanr", quietly = TRUE)) {
install.packages("cmdstanr", repos = c(url_stan, url_cran))
}
if (requireNamespace("cmdstanr", quietly = TRUE) &&
is.null(tryCatch(cmdstanr::cmdstan_path(), error = function(e) NULL))) {
cmdstanr::check_cmdstan_toolchain(fix = TRUE, quiet = TRUE)
cmdstanr::install_cmdstan(
cores = 2,
quiet = TRUE,
cpp_options = list(CXXFLAGS = "-w")
)
}
# Data manipulation and visualization
library(dplyr)
library(tidyr)
library(ggplot2)
# Meteorological dataset and Bayesian ensemble benchmarks
library(ensembleBMA) # Provides the 'srft' UWME dataset
library(bmetapred) # Proposed framework (available on CRAN)
library(brms) # Distributional and Horseshoe regressions
library(cmdstanr) # cmdstanr backend (optional). Activate if necessary
library(loo) # PSIS-LOO and Bayesian Stacking
library(BAS) # Linear BMA (Zellner-Siow prior)
library(BayesVarSel) # Linear BMA (Robust g-prior)
library(EBMAforecast) # Parametric Ensemble BMA (EM algorithm)
library(scoringRules) # Continuous Ranked Probability Score (CRPS)
fit_LOESS Calibrationsrft DatasetWe load the 48-hour-ahead 2-meter surface air temperature forecasts
(in Kelvin) from the ensembleBMA package, retaining
complete cases for the verifying observation (\(Y\)) and the \(p
= 8\) physical ensemble members (CMCG,
ETA, GASP, GFS, JMA,
NGPS, TCWB, UKMO).
data(srft)
modelos_orig <- c("CMCG", "ETA", "GASP", "GFS", "JMA", "NGPS", "TCWB", "UKMO")
cols_necesarias <- c("observation", modelos_orig)
df_raw <- srft[complete.cases(srft[, cols_necesarias]), cols_necesarias]
nombres_M <- paste0("M", seq_along(modelos_orig))
names(df_raw) <- c("Y", nombres_M)
mapa_modelos <- setNames(modelos_orig, nombres_M)
cat(sprintf("Total complete forecast-observation pairs: N = %d\n", nrow(df_raw)))
## Total complete forecast-observation pairs: N = 36826
print(mapa_modelos)
## M1 M2 M3 M4 M5 M6 M7 M8
## "CMCG" "ETA" "GASP" "GFS" "JMA" "NGPS" "TCWB" "UKMO"
Following Section 5 of the manuscript, the dataset is randomly
partitioned into three disjoint subsets: 1. External
pre-training calibration subset (\(N_{\text{pre}} = 25{,}828\)): used
exclusively to compute the common standardization anchor (\(\mu_{Y,\text{pre}},
\sigma_{Y,\text{pre}}\)) and to train the fit_LOESS
error-scale estimator. 2. Training pool (\(N_{\text{pool}} = 10{,}000\)): from which
nested training subsets \(N_{\text{train}} \in
\{50, 500, 2{,}000, 10{,}000\}\) are drawn. 3.
Out-of-sample testing subset (\(N_{\text{test}} = 1{,}000\)): held fixed
across all regimes for evaluation.
To preserve the exact structure of the prediction residuals (\(y_i - \hat{y}_{ik}\)) while strictly preventing data leakage, both \(Y\) and all \(p = 8\) point predictions across all partitions are centered and scaled using \(\mu_{Y,\text{pre}}\) and \(\sigma_{Y,\text{pre}}\).
set.seed(2026)
N_total <- nrow(df_raw)
N_test <- 1000
N_pool_tr <- 10000
N_pretrain <- N_total - N_test - N_pool_tr
idx_perm <- sample(seq_len(N_total), size = N_total, replace = FALSE)
idx_pretrain <- idx_perm[1:N_pretrain]
idx_pool_tr <- idx_perm[(N_pretrain + 1):(N_pretrain + N_pool_tr)]
idx_test <- idx_perm[(N_pretrain + N_pool_tr + 1):N_total]
df_pretrain_raw <- df_raw[idx_pretrain, ]
df_pool_tr_raw <- df_raw[idx_pool_tr, ]
df_test_raw <- df_raw[idx_test, ]
# Common standardization anchor computed exclusively on the pre-training subset
mu_Y <- mean(df_pretrain_raw$Y)
sd_Y <- sd(df_pretrain_raw$Y)
escala_Y <- list(mu_Y = mu_Y, sd_Y = sd_Y)
estandarizar_con_ancla <- function(df, mu, s) {
as.data.frame(lapply(df, function(col) (col - mu) / s))
}
df_pretrain <- estandarizar_con_ancla(df_pretrain_raw, mu_Y, sd_Y)
df_pool_tr <- estandarizar_con_ancla(df_pool_tr_raw, mu_Y, sd_Y)
df_test <- estandarizar_con_ancla(df_test_raw, mu_Y, sd_Y)
# Fit the non-parametric LOESS error-scale model (span = 0.4) on pre-training data
loess_obj <- fit_LOESS(data = df_pretrain, y = "Y", predictors = nombres_M, span = 0.4)
# Project observation-specific error-scale proxies (s_ik) onto all partitions
df_pretrain <- predict(loess_obj, newdata = df_pretrain, prefix = "sd_")
df_pool_tr <- predict(loess_obj, newdata = df_pool_tr, prefix = "sd_")
df_test <- predict(loess_obj, newdata = df_test, prefix = "sd_")
nombres_sd <- paste0("sd_", nombres_M)
head(df_pool_tr[, c("Y", "M1", "sd_M1", "M2", "sd_M2")])
## Y M1 sd_M1 M2 sd_M2
## 1 -1.1428912 -0.2497092 0.6700777 -0.2555369 0.6746869
## 2 1.3328564 0.6187907 0.4824577 0.5433733 0.4961974
## 3 0.8566984 0.1734853 0.6005167 0.4840678 0.5109734
## 4 -0.4763042 -0.3508371 0.6748429 -0.4229978 0.6375739
## 5 -0.2858753 -0.2678779 0.6736034 -0.3904312 0.6523798
## 6 0.9519985 1.1162028 0.4604656 0.6734684 0.4666062
We inspect the minimum, maximum, and Coefficient of Variation (\(\text{CV}_{\text{SD}}\)) of the out-of-sample error-scale proxies \(s_{ik}\) across the \(N = 10{,}000\) training pool (reported in Section 5 as ranging between \(12.5\%\) for GFS and \(14.4\%\) for UKMO).
tabla_cv_sd <- do.call(rbind, lapply(seq_along(nombres_M), function(i) {
col_m <- nombres_M[i]
col_sd <- nombres_sd[i]
sds <- df_pool_tr[[col_sd]]
data.frame(
Model = col_m,
Physical_Name = unname(mapa_modelos[col_m]),
SD_Min = round(min(sds), 4),
SD_Max = round(max(sds), 4),
Ratio_Max_Min = round(max(sds) / min(sds), 2),
CV_SD_Perc = round((sd(sds) / mean(sds)) * 100, 1)
)
}))
rownames(tabla_cv_sd) <- NULL
print(tabla_cv_sd)
## Model Physical_Name SD_Min SD_Max Ratio_Max_Min CV_SD_Perc
## 1 M1 CMCG 0.4361 0.9319 2.14 13.4
## 2 M2 ETA 0.4416 0.8662 1.96 13.4
## 3 M3 GASP 0.4417 0.7726 1.75 13.3
## 4 M4 GFS 0.4539 0.7903 1.74 12.5
## 5 M5 JMA 0.4321 0.9232 2.14 13.9
## 6 M6 NGPS 0.4509 0.8681 1.92 13.3
## 7 M7 TCWB 0.4646 1.2701 2.73 14.1
## 8 M8 UKMO 0.4283 1.0701 2.50 14.4
The chunk below reproduces Figure 6 of the
manuscript (fig_loess_residuals_grid.png), displaying the
standardized prediction residuals (\(y_i -
\hat{y}_{ik}\)) against standardized point predictions (\(\hat{y}_{ik}\)) alongside the projected
nominal 95% error bands (\(\pm
1.96\,s_{ik}\)) across the eight NWP models.
lista_paneles <- lapply(seq_along(nombres_M), function(i) {
mod_id <- nombres_M[i]
sd_id <- paste0("sd_", mod_id)
nom_fis <- unname(mapa_modelos[mod_id])
pred <- df_pool_tr[[mod_id]]
y <- df_pool_tr$Y
sd_e <- df_pool_tr[[sd_id]]
res <- y - pred
ic_low_y <- pred - 1.96 * sd_e
ic_up_y <- pred + 1.96 * sd_e
ic_low_r <- -1.96 * sd_e
ic_up_r <- +1.96 * sd_e
cov_emp <- mean(y >= ic_low_y & y <= ic_up_y, na.rm = TRUE) * 100
etiqueta_panel <- sprintf("%s (%s) | 95%% Cov: %.1f%%", mod_id, nom_fis, cov_emp)
df_mod <- data.frame(
Modelo = mod_id,
Fisico = nom_fis,
panel_label = etiqueta_panel,
pred = pred,
residuo = res,
ic_low_r = ic_low_r,
ic_up_r = ic_up_r,
stringsAsFactors = FALSE
)
df_mod[order(df_mod$pred), ]
})
df_grid_all <- do.call(rbind, lista_paneles)
df_grid_all$panel_label <- factor(df_grid_all$panel_label, levels = unique(df_grid_all$panel_label))
tema_academico <- theme_bw(base_size = 13) +
theme(
strip.background = element_rect(fill = "grey94", color = "grey50", linewidth = 0.5),
strip.text = element_text(face = "bold", size = 11.5, color = "black"),
panel.grid.minor = element_blank(),
panel.grid.major = element_line(color = "grey90", linewidth = 0.3),
panel.border = element_rect(color = "grey40", linewidth = 0.5),
axis.title.x = element_text(face = "plain", size = 13.5, color = "black", margin = margin(t = 8)),
axis.title.y = element_text(face = "bold", size = 13.5, color = "black", margin = margin(r = 8)),
axis.text = element_text(size = 11, color = "black"),
plot.title = element_blank(),
plot.subtitle = element_blank(),
plot.margin = margin(t = 6, r = 8, b = 6, l = 6, unit = "pt")
)
fig_grid_residuos <- ggplot(df_grid_all, aes(x = pred, y = residuo)) +
geom_point(alpha = 0.15, size = 0.6, color = "steelblue4", shape = 16) +
geom_ribbon(aes(ymin = ic_low_r, ymax = ic_up_r), fill = "#D55E00", alpha = 0.18) +
geom_hline(yintercept = 0, linetype = "dashed", color = "black", linewidth = 0.55) +
geom_line(aes(y = ic_up_r), color = "#D55E00", linewidth = 0.80) +
geom_line(aes(y = ic_low_r), color = "#D55E00", linewidth = 0.80) +
facet_wrap(~ panel_label, ncol = 2, scales = "fixed") +
labs(
x = expression(paste("Standardized base model prediction (", hat(y)[italic(ik)], ")")),
y = expression(bold(paste("Standardized prediction residual (", bolditalic(y)[bolditalic(i)] - bold(hat(y))[bolditalic(ik)], ")")))
) +
tema_academico
print(fig_grid_residuos)
The functions below evaluate out-of-sample predictions on both the standardized scale and the original Kelvin scale, and wrap the five competing methodologies under identical prior and posterior sampling settings (\(S = 1500\) draws).
evaluate_predictions <- function(data, truth_col = "truth", estimate_col = "estimate",
lower_col = "lower_95", upper_col = "upper_95",
raw_samples_matrix = NULL) {
y_true <- data[[truth_col]]
y_pred <- data[[estimate_col]]
rmse <- sqrt(mean((y_true - y_pred)^2, na.rm = TRUE))
mae <- mean(abs(y_true - y_pred), na.rm = TRUE)
ss_res <- sum((y_true - y_pred)^2, na.rm = TRUE)
ss_tot <- sum((y_true - mean(y_true, na.rm = TRUE))^2, na.rm = TRUE)
r2 <- 1 - (ss_res / ss_tot)
coverage <- NA
avg_width <- NA
mis <- NA
if (!is.null(lower_col) && !is.null(upper_col)) {
y_lower <- data[[lower_col]]
y_upper <- data[[upper_col]]
within_interval <- (y_true >= y_lower) & (y_true <= y_upper)
coverage <- mean(within_interval, na.rm = TRUE) * 100
widths <- y_upper - y_lower
avg_width <- mean(widths, na.rm = TRUE)
alpha <- 0.05
penalty_low <- (2 / alpha) * (y_lower - y_true) * (y_true < y_lower)
penalty_high <- (2 / alpha) * (y_true - y_upper) * (y_true > y_upper)
interval_scores <- widths + penalty_low + penalty_high
mis <- mean(interval_scores, na.rm = TRUE)
}
mean_crps <- NA
samples_to_use <- if (!is.null(raw_samples_matrix)) raw_samples_matrix else attr(data, "raw_samples")
if (!is.null(samples_to_use) && requireNamespace("scoringRules", quietly = TRUE)) {
matriz_pacientes_filas <- t(samples_to_use)
vec_crps <- scoringRules::crps_sample(y = y_true, dat = matriz_pacientes_filas)
mean_crps <- mean(vec_crps, na.rm = TRUE)
}
data.frame(
Metric = c("RMSE", "MAE", "R2", "Coverage_Perc", "Avg_Width", "MIS", "CRPS"),
Value = c(rmse, mae, r2, coverage, avg_width, mis, mean_crps),
stringsAsFactors = FALSE
)
}
evaluar_doble_escala <- function(df_preds_std, raw_samples_std, metodo_nombre, estimator_nombre,
tiempo_fit_sec, escala_Y = NULL) {
met_std <- evaluate_predictions(
data = df_preds_std, truth_col = "truth", estimate_col = "estimate",
lower_col = "lower_95", upper_col = "upper_95", raw_samples_matrix = raw_samples_std
)
met_std$Estimator <- estimator_nombre
met_std$Metodo <- metodo_nombre
met_std$Scale <- "Standardized"
df_tiempo_std <- data.frame(
Metric = "Fit_Time_Secs", Value = tiempo_fit_sec,
Estimator = "Algorithm", Metodo = metodo_nombre, Scale = "Standardized",
stringsAsFactors = FALSE
)
res_total <- rbind(met_std, df_tiempo_std)
if (!is.null(escala_Y)) {
mu_Y <- escala_Y$mu_Y
sd_Y <- escala_Y$sd_Y
df_preds_orig <- df_preds_std
for (col in c("truth", "estimate", "lower_95", "upper_95")) {
df_preds_orig[[col]] <- df_preds_std[[col]] * sd_Y + mu_Y
}
raw_samples_orig <- raw_samples_std * sd_Y + mu_Y
met_orig <- evaluate_predictions(
data = df_preds_orig, truth_col = "truth", estimate_col = "estimate",
lower_col = "lower_95", upper_col = "upper_95", raw_samples_matrix = raw_samples_orig
)
met_orig$Estimator <- estimator_nombre
met_orig$Metodo <- metodo_nombre
met_orig$Scale <- "Original_Kelvin"
df_tiempo_orig <- df_tiempo_std
df_tiempo_orig$Scale <- "Original_Kelvin"
res_total <- rbind(res_total, met_orig, df_tiempo_orig)
}
return(res_total)
}
# 1. Proposed Method: bmetapred
run_real_bmetapred <- function(df_train, df_test, y = "Y", predictors, sd_cols,
method = "stacking", p_max_exhaust = 9, n_iter_mc3 = 1500,
min_K = 10, max_K = 50, pri_sd = 2.5,
parallel_workers = 4, cores_stan = 2, iter_stan = 1500,
backend = "cmdstanr", n_samples = 1500,
escala_Y = NULL, seed = 2026) {
set.seed(seed)
t_start_fit <- Sys.time()
modelo <- fit_bmetapred(
data_train = df_train,
y = y,
predictors = predictors,
sd_cols = sd_cols,
method = method,
p_max_exhaust = p_max_exhaust,
n_iter_mc3 = n_iter_mc3,
min_K = min_K,
max_K = max_K,
pri_sd = pri_sd,
parallel_workers = parallel_workers,
cores_stan = cores_stan,
iter_stan = iter_stan,
verbosity = 0,
backend = backend
)
t_end_fit <- Sys.time()
tiempo_fit_sec <- as.numeric(difftime(t_end_fit, t_start_fit, units = "secs"))
preds_ensemble <- predict(modelo, newdata = df_test, n_samples_totales = n_samples,
estimator = "ensemble", verbosity = 0)
raw_samples_ens <- attr(preds_ensemble, "raw_samples")
metricas_ens <- evaluar_doble_escala(
df_preds_std = preds_ensemble, raw_samples_std = raw_samples_ens,
metodo_nombre = "bmetapred", estimator_nombre = "Ensemble",
tiempo_fit_sec = tiempo_fit_sec, escala_Y = escala_Y
)
return(list(metricas = metricas_ens, preds_std = preds_ensemble))
}
# 2. Benchmark: BayesVarSel (with safeguard for large-N numerical singularities)
run_real_bvs_safe <- function(df_train, df_test, y = "Y", predictors,
n_samples = 1500, escala_Y = NULL, seed = 2026) {
set.seed(seed)
train_bvs <- df_train[, c(y, predictors)]
test_bvs <- df_test[, c(y, predictors)]
form_bvs <- as.formula(paste(y, "~ ."))
res <- tryCatch({
t_start_fit <- Sys.time()
invisible(capture.output(suppressMessages({
bvs_obj_1 <- BayesVarSel::Bvs(formula = form_bvs, data = train_bvs, parallel = FALSE, n.keep = 1000)
})))
probs_modelos <- bvs_obj_1$modelsprob$prob
if (is.null(probs_modelos)) probs_modelos <- bvs_obj_1$modelsprob[, ncol(bvs_obj_1$modelsprob)]
masa_acumulada <- cumsum(probs_modelos)
top_occam_95 <- which(masa_acumulada >= 0.95)[1]
if (is.na(top_occam_95)) top_occam_95 <- length(probs_modelos)
n_keep_final <- max(1, top_occam_95)
invisible(capture.output(suppressMessages({
bvs_obj_final <- BayesVarSel::Bvs(formula = form_bvs, data = train_bvs, parallel = FALSE, n.keep = n_keep_final)
})))
t_end_fit <- Sys.time()
tiempo_fit_sec <- as.numeric(difftime(t_end_fit, t_start_fit, units = "secs"))
invisible(capture.output({
preds_bvs_raw_bma <- predict(bvs_obj_final, newdata = test_bvs, n.sim = n_samples)
}))
df_preds_ens <- data.frame(
truth = test_bvs[[y]],
estimate = colMeans(preds_bvs_raw_bma),
lower_95 = apply(preds_bvs_raw_bma, 2, quantile, probs = 0.025),
upper_95 = apply(preds_bvs_raw_bma, 2, quantile, probs = 0.975)
)
attr(df_preds_ens, "raw_samples") <- preds_bvs_raw_bma
metricas_ens <- evaluar_doble_escala(
df_preds_std = df_preds_ens, raw_samples_std = preds_bvs_raw_bma,
metodo_nombre = "BayesVarSel", estimator_nombre = "Ensemble",
tiempo_fit_sec = tiempo_fit_sec, escala_Y = escala_Y
)
if (any(is.na(metricas_ens$Value[metricas_ens$Metric == "RMSE"]))) {
stop("Numerical singularity (NaN) in BayesVarSel marginal likelihood.")
}
list(metricas = metricas_ens, preds_std = df_preds_ens)
}, error = function(e) {
message(sprintf("BayesVarSel failed to converge at N_train = %d: %s", nrow(df_train), e$message))
return(NULL)
})
return(res)
}
# 3. Benchmark: BAS
run_real_bas <- function(df_train, df_test, y = "Y", predictors,
n_samples = 1500, escala_Y = NULL, seed = 2026) {
set.seed(seed)
train_bas <- df_train[, c(y, predictors)]
test_bas <- df_test[, c(y, predictors)]
form_bas <- as.formula(paste(y, "~ ."))
t_start_fit <- Sys.time()
invisible(capture.output(suppressMessages({
bas_obj <- BAS::bas.lm(
formula = form_bas, data = train_bas,
prior = "JZS", modelprior = BAS::uniform(), method = "BAS"
)
})))
t_end_fit <- Sys.time()
tiempo_fit_sec <- as.numeric(difftime(t_end_fit, t_start_fit, units = "secs"))
probs_ordenadas <- sort(bas_obj$postprobs, decreasing = TRUE)
masa_acumulada <- cumsum(probs_ordenadas)
top_occam_95 <- which(masa_acumulada >= 0.95)[1]
if (is.na(top_occam_95)) top_occam_95 <- length(probs_ordenadas)
n_keep_final <- max(1, top_occam_95)
invisible(capture.output(suppressMessages({
preds_bas_bma <- predict(bas_obj, newdata = test_bas, estimator = "BMA", top = n_keep_final, se.fit = TRUE)
})))
means_bma <- as.numeric(preds_bas_bma$fit)
sds_bma <- as.numeric(preds_bas_bma$se.pred)
if (any(is.na(sds_bma))) sds_bma[is.na(sds_bma)] <- mean(sds_bma, na.rm = TRUE)
preds_bas_raw_bma <- matrix(NA, nrow = n_samples, ncol = length(means_bma))
for (k_sim in 1:n_samples) {
preds_bas_raw_bma[k_sim, ] <- rnorm(length(means_bma), mean = means_bma, sd = sds_bma)
}
df_preds_ens <- data.frame(
truth = test_bas[[y]],
estimate = means_bma,
lower_95 = apply(preds_bas_raw_bma, 2, quantile, probs = 0.025),
upper_95 = apply(preds_bas_raw_bma, 2, quantile, probs = 0.975)
)
attr(df_preds_ens, "raw_samples") <- preds_bas_raw_bma
metricas_ens <- evaluar_doble_escala(
df_preds_std = df_preds_ens, raw_samples_std = preds_bas_raw_bma,
metodo_nombre = "BAS", estimator_nombre = "Ensemble",
tiempo_fit_sec = tiempo_fit_sec, escala_Y = escala_Y
)
return(list(metricas = metricas_ens, preds_std = df_preds_ens))
}
# 4. Benchmark: EBMAforecast
run_real_ebma <- function(df_train, df_test, y = "Y", predictors,
n_samples = 1500, escala_Y = NULL, seed = 2026) {
set.seed(seed)
observaciones <- as.numeric(df_train[[y]])
pronosticos_mat <- as.matrix(df_train[, predictors])
observaciones_test <- as.numeric(df_test[[y]])
pronosticos_mat_test <- as.matrix(df_test[, predictors])
datos_ebma <- EBMAforecast::makeForecastData(
.predCalibration = pronosticos_mat,
.outcomeCalibration = observaciones
)
t_start_fit <- Sys.time()
invisible(capture.output(suppressMessages({
modelo_ebma <- EBMAforecast::calibrateEnsemble(
datos_ebma, model = "normal", useModelParams = FALSE, method = "EM"
)
})))
t_end_fit <- Sys.time()
tiempo_fit_sec <- as.numeric(difftime(t_end_fit, t_start_fit, units = "secs"))
pesos_ebma <- as.numeric(modelo_ebma@modelWeights)
var_ebma <- as.numeric(modelo_ebma@variance)
sigma_ebma <- if (length(var_ebma) == 1) rep(sqrt(var_ebma), length(pesos_ebma)) else sqrt(var_ebma)
rm(datos_ebma, modelo_ebma); invisible(gc(full = TRUE))
idx_ord <- order(pesos_ebma, decreasing = TRUE)
pesos_ord <- pesos_ebma[idx_ord]
masa_acumulada <- cumsum(pesos_ord)
top_occam_95 <- which(masa_acumulada >= 0.95)[1]
if (is.na(top_occam_95)) top_occam_95 <- length(pesos_ord)
pesos_finales <- pesos_ebma
if (top_occam_95 < length(pesos_ord)) {
pesos_finales[idx_ord[(top_occam_95 + 1):length(pesos_ord)]] <- 0
}
pesos_finales <- pesos_finales / sum(pesos_finales)
n_obs <- nrow(pronosticos_mat_test)
sims_ebma <- matrix(NA, nrow = n_samples, ncol = n_obs)
modelo_elegido <- sample(seq_along(pesos_finales), size = n_samples, replace = TRUE, prob = pesos_finales)
for (i in 1:n_samples) {
k <- modelo_elegido[i]
sims_ebma[i, ] <- rnorm(n_obs, mean = pronosticos_mat_test[, k], sd = sigma_ebma[k])
}
df_preds_ebma <- data.frame(
truth = observaciones_test,
estimate = colMeans(sims_ebma),
lower_95 = apply(sims_ebma, 2, quantile, probs = 0.025),
upper_95 = apply(sims_ebma, 2, quantile, probs = 0.975)
)
attr(df_preds_ebma, "raw_samples") <- sims_ebma
metricas_ens <- evaluar_doble_escala(
df_preds_std = df_preds_ebma, raw_samples_std = sims_ebma,
metodo_nombre = "EBMAforecast", estimator_nombre = "Ensemble",
tiempo_fit_sec = tiempo_fit_sec, escala_Y = escala_Y
)
return(list(metricas = metricas_ens, preds_std = df_preds_ebma))
}
# 5. Benchmark: Standard Horseshoe Regression
run_real_horseshoe_clean <- function(df_train, df_test, y = "Y", predictors,
backend = "cmdstanr", n_samples = 1500,
escala_Y = NULL, seed = 2026) {
set.seed(seed)
form_std_horseshoe <- brms::bf(as.formula(paste(y, "~", paste(predictors, collapse = " + "))))
priors_hs_std <- c(
brms::set_prior("horseshoe(df = 1, par_ratio = 0.33, scale_slab = 2)", class = "b"),
brms::set_prior("normal(0, 3)", class = "Intercept"),
brms::set_prior("exponential(1)", class = "sigma")
)
t_start_std <- Sys.time()
invisible(capture.output(suppressMessages(suppressWarnings({
fit_hs_std <- brms::brm(
formula = form_std_horseshoe, data = df_train, prior = priors_hs_std,
family = gaussian(), chains = 4, iter = 2000, warmup = 1000,
cores = 4, backend = backend, refresh = 0, silent = 2,
control = list(adapt_delta = 0.95, max_treedepth = 12)
)
}))))
t_end_std <- Sys.time()
tiempo_fit_std <- as.numeric(difftime(t_end_std, t_start_std, units = "secs"))
preds_raw_std <- brms::posterior_predict(fit_hs_std, newdata = df_test, ndraws = n_samples)
df_preds_std <- data.frame(
truth = df_test[[y]],
estimate = colMeans(preds_raw_std),
lower_95 = apply(preds_raw_std, 2, quantile, probs = 0.025),
upper_95 = apply(preds_raw_std, 2, quantile, probs = 0.975)
)
attr(df_preds_std, "raw_samples") <- preds_raw_std
metricas_total <- evaluar_doble_escala(
df_preds_std = df_preds_std, raw_samples_std = preds_raw_std,
metodo_nombre = "Std. Horseshoe", estimator_nombre = "Ensemble",
tiempo_fit_sec = tiempo_fit_std, escala_Y = escala_Y
)
return(list(metricas = metricas_total, preds_std = df_preds_std))
}
The loop below runs all five methods across the nested training sample sizes while holding the \(N_{\text{test}} = 1{,}000\) testing partition fixed, reproducing Table 2 of the manuscript.
tamanos_train <- c(50, 500, 2000, 10000)
resultados_por_N <- list()
for (N_tr in tamanos_train) {
cat(sprintf("\n=== Running Real-Data Benchmark for N_train = %d (N_test = %d) ===\n", N_tr, nrow(df_test)))
df_train_sub <- df_pool_tr[1:N_tr, ]
res_bm <- run_real_bmetapred(df_train_sub, df_test, "Y", nombres_M, nombres_sd,
parallel_workers = 4, cores_stan = 2, backend = "cmdstanr",
escala_Y = escala_Y, seed = 2026)
cat(sprintf("\n=== bmetapred finished. Starting benchmark methods ===\n"))
res_bvs <- run_real_bvs_safe(df_train_sub, df_test, "Y", nombres_M, escala_Y = escala_Y, seed = 2026)
res_bas <- run_real_bas(df_train_sub, df_test, "Y", nombres_M, escala_Y = escala_Y, seed = 2026)
res_ebma <- run_real_ebma(df_train_sub, df_test, "Y", nombres_M, escala_Y = escala_Y, seed = 2026)
res_hs <- run_real_horseshoe_clean(df_train_sub, df_test, "Y", nombres_M, backend = "cmdstanr",
escala_Y = escala_Y, seed = 2026)
cat(sprintf("\n=== Benchmark methods finished. Saving metrics ===\n"))
lista_met <- list(res_bm$metricas, res_bas$metricas, res_ebma$metricas, res_hs$metricas)
if (!is.null(res_bvs)) lista_met <- append(lista_met, list(res_bvs$metricas), after = 1)
df_met_N <- do.call(rbind, lista_met)
df_met_N$N_train <- N_tr
resultados_por_N[[paste0("N_", N_tr)]] <- list(
metricas_raw = df_met_N,
objetos = list(bmetapred = res_bm, bvs = res_bvs, bas = res_bas, ebma = res_ebma, horseshoe = res_hs)
)
saveRDS(resultados_por_N, file = "resultados_srft_4_escenarios.rds")
}
# Format and print Table 2 results (Standardized and Kelvin scales)
formatear_tabla_escenario <- function(df_sub) {
df_preds <- df_sub[df_sub$Metric != "Fit_Time_Secs", c("N_train", "Metodo", "Metric", "Value")]
df_time <- df_sub[df_sub$Metric == "Fit_Time_Secs", c("N_train", "Metodo", "Value")]
names(df_time)[3] <- "Fit_Time_Secs"
ancha <- tidyr::pivot_wider(df_preds, names_from = Metric, values_from = Value) %>%
left_join(df_time, by = c("N_train", "Metodo")) %>%
as.data.frame()
cols_orden <- c("N_train", "Metodo", "MIS", "CRPS", "Coverage_Perc", "Avg_Width", "RMSE", "MAE", "R2", "Fit_Time_Secs")
ancha <- ancha[, intersect(cols_orden, names(ancha))]
ancha[, -(1:2)] <- round(ancha[, -(1:2)], 4)
return(ancha)
}
df_todos_escenarios <- do.call(rbind, lapply(resultados_por_N, `[[`, "metricas_raw"))
cat(sprintf("\n=== Analysis finished. Formating table ===\n"))
print(formatear_tabla_escenario(df_todos_escenarios[df_todos_escenarios$Scale == "Standardized", ]))