Forecast: R6 Class for Forecast in Hidden Markov Models

ForecastR Documentation

R6 Class for Forecast in Hidden Markov Models

Description

Creates a forecast object from a fitted HMM model, projecting future state probabilities and unconditional observation densities for a user-defined horizon using a covariate data-frame if applicable. Forecasting occurs in the constructor; results are accessible via public methods.

Methods

Public methods


Forecast$new()

Construct a forecast object.

Usage
Forecast$new(
  hmm = NULL,
  n = NULL,
  forecast_data = NULL,
  preset_eval_range = NULL,
  starting_state_distribution = "last"
)
Arguments
hmm

A fitted HMM object.

n

Forecast horizon: a whole number greater than zero. Ignored if forecast_data is provided.

forecast_data

data.frame of future covariates / IDs. Must include all covariates in fitted hmm.

preset_eval_range

Named list: elements are numeric vectors (univariate) or matrices (multivariate, rows as dimension ex. mu1, mu2, columns as points). For any observation variable without an entry, a default grid of 100 equally spaced points is used, spanning the range of the training data for that variable with each endpoint expanded outward by 10% of its magnitude. A warning is issued whenever this default is applied, as the resulting grid may not suit the distribution's support.

starting_state_distribution

Distribution over states at the first forecast step. Either a numeric vector of length nstates() that is non-negative and sums to 1, or one of "last" (state probabilities at the final training row, propagated one step) or "stationary" (the model's stationary distribution).

Details

Algorithm overview

  1. Validate the arguments.

  2. Build or accept the future design matrix (forecast_data).

  3. Obtain time-varying transition matrices (tpm_forecast) and observation parameters (obs_par_forecast) via HMM$predict().

  4. Forward-propagate the hidden-state distribution (hidden_state_forecast).

  5. Marginalise over states to obtain unconditional pdfs on the evaluation grid (forecast_dists).

Returns

A Forecast object. Results are read back with the accessor methods below, each invoked with ():

hidden_state_forecast

Matrix of nstates rows by n forecast steps.

obs_par_forecast

Array of time-varying observation parameters.

tpm_forecast

Array of time-varying transition matrices.

forecast_dists

List of unconditional pdf matrices, one per observation variable.

eval_range

List of grids on which each pdf was evaluated.

forecast_data

The data.frame of future covariates used for prediction.

The evaluation grid can be changed after construction with update_eval_range(), which recomputes forecast_dists.

Examples
data(faithful)

# Create training and forecast data frames
training_fraction <- 0.8
n_training <- floor(nrow(faithful) * training_fraction)
training_df <- data.frame(
  ID = rep(1, n_training),
  waiting = faithful$waiting[1:n_training],
  eruptions = faithful$eruptions[1:n_training]
)
forecast_df <- data.frame(
  ID = rep(1, nrow(faithful) - n_training),
  waiting = faithful$waiting[(n_training + 1):nrow(faithful)],
  eruptions = faithful$eruptions[(n_training + 1):nrow(faithful)]
)
# Create 2-state model with non-linear effect of waiting on all transitions
hid_model <- MarkovChain$new(
  data = training_df,
  n_states = 2,
  formula = ~ s(waiting, k = 10, bs = "cs")
)

# Create observation model with normal distribution for duration
obs_model <- Observation$new(
  data = training_df,
  n_states = 2,
  dists = list(eruptions = "norm"),
  par = list(eruptions = list(
    mean = c(0, 0),
    sd = c(1, 1)
  ))
)
# Update model parameters to suggested
obs_model$update_par(par = obs_model$suggest_initial())
# Create HMM model
hmm <- HMM$new(
  hid = hid_model,
  obs = obs_model
)
hmm$fit(silent = TRUE)
# Create forecast object. Setting the evaluation grid explicitly is
# recommended; omitting it falls back to a default grid and warns.
forecast <- Forecast$new(
  hmm = hmm,
  forecast_data = forecast_df,
  preset_eval_range = list(eruptions = seq(1, 6, length.out = 100)),
  starting_state_distribution = "last"
)

# Unconditional predictive densities: grid points x forecast steps
dim(forecast$forecast_dists()$eruptions)

Forecast$obs_par_forecast()

Get predicted observation parameters.

Usage
Forecast$obs_par_forecast()

Forecast$tpm_forecast()

Get predicted transition matrices.

Usage
Forecast$tpm_forecast()

Forecast$eval_range()

Get the evaluation grid for each response variable.

Usage
Forecast$eval_range()

Forecast$forecast_data()

Get the forecast data used for predictions.

Usage
Forecast$forecast_data()

Forecast$update_eval_range()

Update the evaluation grid for forecast pdfs. This method reconfigures the evaluation range used to compute unconditional predictive pdfs. It validates the new eval_range, updates internal state, reinitializes forecast densities, and returns the object invisibly for chaining.

Usage
Forecast$update_eval_range(eval_range)
Arguments
eval_range

A named list specifying the new evaluation grid for each observation variable.

Returns

The Forecast object (invisibly), allowing method chaining.


Forecast$hidden_state_forecast()

Get the forward state probabilities.

Usage
Forecast$hidden_state_forecast()

Forecast$forecast_dists()

Get the unconditional predictive pdfs.

Usage
Forecast$forecast_dists()

Forecast$quantile()

Quantiles of forecast distribution

Usage
Forecast$quantile(var, probs)
Arguments
var

Name of observation variable, as character string

probs

Numeric vector of probabilities

Returns

Data frame with one column for each quantile probability and one row for each time step in the forecast


Forecast$mean()

Mean of forecast distribution

Usage
Forecast$mean(var)
Arguments
var

Name of observation variable, as character string

Returns

Numeric vector of means, with one element for each time step in the forecast


Forecast$plot()

Plot forecast

Usage
Forecast$plot(var, show_data = FALSE)
Arguments
var

Name of observation variable, as character string

show_data

Logical: should data be included in the plot?

Details

The plot shows the mean of the forecast distribution over time (red line), as well as bands of decreasing opacity for the 50 90

Returns

A ggplot object


Forecast$clone()

The objects of this class are cloneable with this method.

Usage
Forecast$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

See Also

HMM for the fitted model that is forecast from, and MarkovChain and Observation for the hidden state and observation components it is built from.

Examples


## ------------------------------------------------
## Method `Forecast$new()`
## ------------------------------------------------


data(faithful)

# Create training and forecast data frames
training_fraction <- 0.8
n_training <- floor(nrow(faithful) * training_fraction)
training_df <- data.frame(
  ID = rep(1, n_training),
  waiting = faithful$waiting[1:n_training],
  eruptions = faithful$eruptions[1:n_training]
)
forecast_df <- data.frame(
  ID = rep(1, nrow(faithful) - n_training),
  waiting = faithful$waiting[(n_training + 1):nrow(faithful)],
  eruptions = faithful$eruptions[(n_training + 1):nrow(faithful)]
)
# Create 2-state model with non-linear effect of waiting on all transitions
hid_model <- MarkovChain$new(
  data = training_df,
  n_states = 2,
  formula = ~ s(waiting, k = 10, bs = "cs")
)

# Create observation model with normal distribution for duration
obs_model <- Observation$new(
  data = training_df,
  n_states = 2,
  dists = list(eruptions = "norm"),
  par = list(eruptions = list(
    mean = c(0, 0),
    sd = c(1, 1)
  ))
)
# Update model parameters to suggested
obs_model$update_par(par = obs_model$suggest_initial())
# Create HMM model
hmm <- HMM$new(
  hid = hid_model,
  obs = obs_model
)
hmm$fit(silent = TRUE)
# Create forecast object. Setting the evaluation grid explicitly is
# recommended; omitting it falls back to a default grid and warns.
forecast <- Forecast$new(
  hmm = hmm,
  forecast_data = forecast_df,
  preset_eval_range = list(eruptions = seq(1, 6, length.out = 100)),
  starting_state_distribution = "last"
)

# Unconditional predictive densities: grid points x forecast steps
dim(forecast$forecast_dists()$eruptions)


hmmTMB documentation built on Nov. 10, 2026, 5:09 p.m.