R/tune_hmix.R

Defines functions tune_hmix

Documented in tune_hmix

#' Select model complexity with rolling-origin CRPS
#'
#' Compare candidate cluster and state counts on chronological validation
#' origins. Reserve a separate final holdout before calling this function.
#' @param ts Numeric training and validation series, excluding the final holdout.
#' @param horizon Forecast horizon.
#' @param candidates Data frame with integer columns `centers` and `n_hidden`.
#' @param n_tests Number of validation origins.
#' @param warmup Fraction of the series before the earliest validation origin.
#' @param seed Random seed.
#' @param transform Transformation passed to [hmix()].
#' @param stride Window stride passed to [hmix()].
#' @param n_samples Number of forecast paths.
#' @param max_iterations Maximum HMM training iterations.
#' @param tolerance HMM convergence tolerance.
#' @param training_window Maximum observations used per fit, or NULL.
#' @param kmeans_starts Number of k-means initializations.
#' @param workers Number of parallel candidate workers: 1 (default) or 2.
#' @param engine HMM training implementation, compiled or reference.
#' @return A list with `best` (one candidate row) and `results` (all scores,
#'   elapsed seconds and error messages). Failed candidates are not selected.
#' @export
tune_hmix <- function(ts, horizon,
                      candidates = expand.grid(centers = c(2L, 4L, 6L), n_hidden = c(2L, 3L)),
                      n_tests = 3L, warmup = 0.6, seed = 42L,
                      transform = "auto", stride = 1L, n_samples = 1000L,
                      max_iterations = 1000L, tolerance = 1e-9, training_window = NULL,
                      kmeans_starts = 10L, workers = 1L, engine = c("compiled", "reference")) {
  engine <- match.arg(engine)
  if (!is.data.frame(candidates) || !all(c("centers", "n_hidden") %in% names(candidates)) || nrow(candidates) == 0L)
    stop("candidates must be a nonempty data frame with centers and n_hidden columns")
  if (length(n_tests) != 1L || !is.numeric(n_tests) || !is.finite(n_tests) || n_tests < 1 || n_tests != floor(n_tests)) stop("n_tests must be a positive integer")
  if (length(workers) != 1L || !is.numeric(workers) || !is.finite(workers) || workers < 1 || workers != floor(workers)) stop("workers must be a positive integer")
  if (workers > 2L) stop("workers must be 1 or 2")
  # Resolve arguments before serializing the closure to PSOCK workers; an
  # unevaluated promise may otherwise refer to a name in the caller's session.
  force(ts); force(horizon); force(warmup); force(seed); force(transform)
  force(stride); force(n_samples); force(max_iterations); force(tolerance)
  force(training_window); force(kmeans_starts)
  results <- candidates[, c("centers", "n_hidden"), drop = FALSE]
  results$mean_crps <- NA_real_
  results$elapsed_seconds <- NA_real_
  results$error <- NA_character_
  evaluated <- parallel_map(seq_len(nrow(results)), function(i) {
    started <- proc.time()[["elapsed"]]
    fit <- tryCatch(hmix_impl(ts, horizon, results$centers[i], results$n_hidden[i], seed, n_tests, warmup,
                              transform, stride, n_samples, max_iterations, tolerance, training_window,
                              kmeans_starts, 1L, engine, FALSE), error = identity)
    elapsed <- proc.time()[["elapsed"]] - started
    if (inherits(fit, "error")) list(score = NA_real_, elapsed = elapsed, error = conditionMessage(fit))
    else if (all(is.finite(fit$error_sets$crps_set))) list(score = mean(fit$error_sets$crps_set), elapsed = elapsed, error = NA_character_)
    else list(score = NA_real_, elapsed = elapsed, error = "non-finite validation scores")
  }, workers)
  for (i in seq_len(nrow(results))) {
    results$mean_crps[i] <- evaluated[[i]]$score
    results$elapsed_seconds[i] <- evaluated[[i]]$elapsed
    results$error[i] <- evaluated[[i]]$error
  }
  if (all(is.na(results$mean_crps))) stop("all candidates failed: ", paste(unique(results$error), collapse = "; "))
  best <- which.min(replace(results$mean_crps, is.na(results$mean_crps), Inf))
  list(best = results[best, c("centers", "n_hidden"), drop = FALSE], results = results)
}

Try the hmix package in your browser

Any scripts or data that you put into this service are public.

hmix documentation built on Dec. 2, 2026, 1:09 a.m.