R/lstm.R

Defines functions .lstm_predict .lstm_train .subset_steps .lstm_loss .lstm_backward .lstm_forward .lstm_init .orthogonal .glorot .sigmoid

# A single-layer LSTM regression network in plain R.
#
# Input: a list X of T matrices (n x d), one per time step, oldest first.
# Network: LSTM with H units (input, forget, output gates; tanh candidate),
# followed by a linear output on the last hidden state.
# Training: full back-propagation through time on mini-batches, mean squared
# error loss, Adam optimiser, gradient-norm clipping. Weights are initialised
# with Glorot-uniform input weights, orthogonal recurrent weights and a
# forget-gate bias of 1 (as in Keras).


.sigmoid <- function(x) 1 / (1 + exp(-x))

.glorot <- function(fan_in, fan_out) {
  lim <- sqrt(6 / (fan_in + fan_out))
  matrix(stats::runif(fan_in * fan_out, -lim, lim), fan_in, fan_out)
}

.orthogonal <- function(n, m) {
  a <- matrix(stats::rnorm(n * m), n, m)
  q <- qr.Q(qr(if (n >= m) a else t(a)))
  if (n >= m) q[, seq_len(m), drop = FALSE] else t(q)[seq_len(n), , drop = FALSE]
}

# Parameters: W ((d + H) x 4H; rows 1..d input, d+1..d+H recurrent),
# b (4H; gate order i, f, o, g), V (H x 1), c0 (scalar)
.lstm_init <- function(d, H) {
  W_in <- .glorot(d, 4L * H)
  W_rec <- do.call(cbind, lapply(1:4, function(k) .orthogonal(H, H)))
  b <- numeric(4L * H)
  b[(H + 1L):(2L * H)] <- 1                       # forget-gate bias
  list(W = rbind(W_in, W_rec), b = b, V = .glorot(H, 1L), c0 = 0)
}


# Forward pass; keep = TRUE stores what the backward pass needs
.lstm_forward <- function(par, X, keep = FALSE) {
  n <- nrow(X[[1]])
  H <- nrow(par$V)
  Tn <- length(X)
  h <- matrix(0, n, H)
  cc <- matrix(0, n, H)
  ii <- seq_len(H)
  ff <- H + ii
  oo <- 2L * H + ii
  gg <- 3L * H + ii
  cache <- if (keep) vector("list", Tn) else NULL

  for (t in seq_len(Tn)) {
    z <- cbind(X[[t]], h)
    a <- z %*% par$W
    a <- a + rep(par$b, each = n)
    i <- .sigmoid(a[, ii, drop = FALSE])
    f <- .sigmoid(a[, ff, drop = FALSE])
    o <- .sigmoid(a[, oo, drop = FALSE])
    g <- tanh(a[, gg, drop = FALSE])
    c_prev <- cc
    cc <- f * c_prev + i * g
    tc <- tanh(cc)
    h <- o * tc
    if (keep) cache[[t]] <- list(z = z, i = i, f = f, o = o, g = g,
                                 c_prev = c_prev, tc = tc)
  }
  yhat <- as.numeric(h %*% par$V) + par$c0
  list(yhat = yhat, h = h, cache = cache)
}


# Gradients of the mean squared error with respect to all parameters
.lstm_backward <- function(par, X, y, fw) {
  n <- length(y)
  H <- nrow(par$V)
  d <- ncol(X[[1]])
  Tn <- length(X)

  dy <- 2 * (fw$yhat - y) / n
  gV <- crossprod(fw$h, dy)
  gc0 <- sum(dy)
  dh <- dy %o% as.numeric(par$V)
  dh <- matrix(dh, n, H)
  dc <- matrix(0, n, H)
  gW <- matrix(0, nrow(par$W), ncol(par$W))
  gb <- numeric(length(par$b))
  rec <- d + seq_len(H)

  for (t in Tn:1) {
    k <- fw$cache[[t]]
    do <- dh * k$tc
    dc <- dc + dh * k$o * (1 - k$tc^2)
    dA <- cbind(
      dc * k$g * k$i * (1 - k$i),           # input gate
      dc * k$c_prev * k$f * (1 - k$f),      # forget gate
      do * k$o * (1 - k$o),                 # output gate
      dc * k$i * (1 - k$g^2)                # candidate
    )
    gW <- gW + crossprod(k$z, dA)
    gb <- gb + colSums(dA)
    dc <- dc * k$f
    if (t > 1L) dh <- dA %*% t(par$W[rec, , drop = FALSE])
  }
  list(W = gW, b = gb, V = gV, c0 = gc0)
}


.lstm_loss <- function(par, X, y) mean((.lstm_forward(par, X)$yhat - y)^2)

.subset_steps <- function(X, rows) lapply(X, function(m) m[rows, , drop = FALSE])


# Train one network
#   X list of T matrices (n x d), y numeric(n) (scaled target)
#   H units, epochs, lr Adam learning rate, batch mini-batch size
#   eval_epochs: epochs at which callback(par) is called (e.g. validation)
# Returns the parameters, the callback results and the training loss
# (mean squared error on the scaled target) of every epoch.
.lstm_train <- function(X, y, H, epochs, lr = 0.01, batch = 32L, clip = 5,
                        eval_epochs = integer(0), callback = NULL) {
  n <- length(y)
  d <- ncol(X[[1]])
  par <- .lstm_init(d, H)
  m <- lapply(par, function(p) p * 0)
  v <- m
  beta1 <- 0.9
  beta2 <- 0.999
  eps <- 1e-8
  step <- 0L
  batch <- min(as.integer(batch), n)
  evals <- list()
  loss <- numeric(epochs)

  for (ep in seq_len(epochs)) {
    perm <- sample.int(n)
    starts <- seq(1L, n, by = batch)
    sse <- 0
    for (s in starts) {
      rows <- perm[s:min(n, s + batch - 1L)]
      Xb <- .subset_steps(X, rows)
      fw <- .lstm_forward(par, Xb, keep = TRUE)
      sse <- sse + sum((fw$yhat - y[rows])^2)
      gr <- .lstm_backward(par, Xb, y[rows], fw)

      gnorm <- sqrt(sum(vapply(gr, function(g) sum(g^2), numeric(1))))
      if (is.finite(gnorm) && gnorm > clip) gr <- lapply(gr, function(g) g * clip / gnorm)

      step <- step + 1L
      for (nm in names(par)) {
        m[[nm]] <- beta1 * m[[nm]] + (1 - beta1) * gr[[nm]]
        v[[nm]] <- beta2 * v[[nm]] + (1 - beta2) * gr[[nm]]^2
        mh <- m[[nm]] / (1 - beta1^step)
        vh <- v[[nm]] / (1 - beta2^step)
        par[[nm]] <- par[[nm]] - lr * mh / (sqrt(vh) + eps)
      }
    }
    loss[ep] <- sse / n
    if (!is.finite(loss[ep])) stop("LSTM training diverged; try a smaller Learn_Rate")
    if (ep %in% eval_epochs && is.function(callback)) {
      evals[[as.character(ep)]] <- callback(par)
    }
  }
  list(par = par, evals = evals, loss = loss, H = H, d = d)
}

.lstm_predict <- function(par, X) .lstm_forward(par, X)$yhat

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.