R/features.R

Defines functions .metrics .fit_lstm .predict_lstm .predict_scaled .n_params .n_step_inputs .seq_inputs .prepare .unscale01 .scale01 .minmax

# Sequence inputs, LSTM fitting and prediction helpers.
#
# For a target y[t] and lag order L the LSTM reads a sequence of L time
# steps, oldest first: y[t-L], ..., y[t-1]. At each step the input vector is
# the (min-max scaled) value and its IFCM membership and non-membership
# degrees in every cluster, i.e. 1 + 2 * Class inputs per step. Only past
# values enter the inputs, and the IFCM centres and the scaling constants
# are estimated from the fitting part of the series, so no information from
# the period being predicted leaks into the model.


.minmax <- function(x) {
  lo <- min(x)
  hi <- max(x)
  if (hi - lo < .Machine$double.eps) hi <- lo + 1
  list(lo = lo, hi = hi)
}

.scale01 <- function(x, s) (x - s$lo) / (s$hi - s$lo)

.unscale01 <- function(z, s) z * (s$hi - s$lo) + s$lo


# Everything estimated from the fitting window y_fit: IFCM centres and scaling
.prepare <- function(y_fit, Class, m, alpha, max_iter, tol) {
  cl <- .ifcm(y_fit, Class = Class, m = m, alpha = alpha,
              max_iter = max_iter, tol = tol)
  list(
    centers = cl$centers,
    m = m,
    alpha = alpha,
    scaling = .minmax(y_fit),
    ifcm = cl
  )
}


# List of L matrices (one per time step, oldest first) for the targets y[idx]
.seq_inputs <- function(y, idx, L, prep) {
  K <- length(prep$centers)
  lapply(L:1, function(k) {
    v <- y[idx - k]
    d <- .if_degrees(v, prep$centers, prep$m, prep$alpha)
    X <- cbind(.scale01(v, prep$scaling), d$mu, d$nu)
    colnames(X) <- c("Value", paste0("Mu_C", seq_len(K)), paste0("Nu_C", seq_len(K)))
    X
  })
}

.n_step_inputs <- function(K) 1L + 2L * K

# Number of trainable parameters of an LSTM with d inputs and H units
.n_params <- function(d, H) (d + H) * 4L * H + 4L * H + H + 1L


# Average scaled prediction of a list of networks (parameter sets)
.predict_scaled <- function(nets, X) {
  P <- vapply(nets, function(par) .lstm_predict(par, X), numeric(nrow(X[[1]])))
  if (is.matrix(P)) rowMeans(P) else mean(P)
}


# Predict the targets y[idx] (idx increasing and contiguous for "recursive").
#   "one-step"  : every prediction uses the observed past values
#   "recursive" : predictions inside idx replace the observations as lags
.predict_lstm <- function(nets, y, idx, L, prep, type = "one-step") {
  if (type == "one-step") {
    X <- .seq_inputs(y, idx, L, prep)
    return(.unscale01(.predict_scaled(nets, X), prep$scaling))
  }
  yy <- y
  out <- numeric(length(idx))
  for (i in seq_along(idx)) {
    t <- idx[i]
    X <- .seq_inputs(yy, t, L, prep)
    p <- .unscale01(.predict_scaled(nets, X), prep$scaling)
    yy[t] <- p
    out[i] <- p
  }
  out
}


# Train `Repeats` networks on the targets y[idx]; if eval_idx is given, also
# return the (averaged) predictions of y[eval_idx] after each epoch in
# eval_epochs, as a matrix with one column per epoch value.
.fit_lstm <- function(y, idx, L, prep, Units, Epochs, ctrl,
                      eval_idx = NULL, eval_epochs = integer(0),
                      Forecast_Type = "one-step") {
  X <- .seq_inputs(y, idx, L, prep)
  z <- .scale01(y[idx], prep$scaling)
  nets <- vector("list", ctrl$Repeats)
  losses <- vector("list", ctrl$Repeats)
  P <- NULL
  if (!is.null(eval_idx)) P <- matrix(0, length(eval_idx), length(eval_epochs))

  for (r in seq_len(ctrl$Repeats)) {
    cb <- if (is.null(eval_idx)) NULL else function(par) {
      .predict_lstm(list(par), y, eval_idx, L, prep, Forecast_Type)
    }
    fit <- .lstm_train(X, z, H = Units, epochs = Epochs, lr = ctrl$Learn_Rate,
                       batch = ctrl$Batch_Size, eval_epochs = eval_epochs,
                       callback = cb)
    nets[[r]] <- fit$par
    losses[[r]] <- fit$loss
    if (!is.null(eval_idx)) {
      P <- P + do.call(cbind, fit$evals[as.character(eval_epochs)])
    }
  }
  if (!is.null(P)) P <- P / ctrl$Repeats
  list(nets = nets, loss = losses, eval = P)
}


.metrics <- function(actual, pred) {
  e <- actual - pred
  c(
    RMSE = sqrt(mean(e^2)),
    MAE = mean(abs(e)),
    MAPE = if (any(actual == 0)) NA_real_ else mean(abs(e / actual)) * 100
  )
}

Try the IFLSTM package in your browser

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

IFLSTM documentation built on Nov. 25, 2026, 5:07 p.m.