Foundations to Frontier
Tests
K. Time Series and Sensor Data › K2 Deep Learning for Time Series

RNN and LSTM forecasting

Recurrent networks read a series one step at a time and carry a hidden state forward, so they can learn nonlinear dynamics that linear ARIMA models cannot. This page builds an LSTM in NumPy, backpropagation through time included, checks its gradients, and forecasts the chaotic Mackey–Glass series. The LSTM is compared with persistence and a linear autoregression one step and ten steps ahead, with recursive and direct multi-step strategies.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

A network with a memory

A recurrent network reads a series like you read a sentence: one value at a time, keeping a summary of what it has seen so far. At each step it updates that summary and can make a prediction. An LSTM adds gates, little switches that decide what to remember, what to forget and what to output, which helps it hold on to information for many steps.

Deep forecasting lab
log₁₀ of ∂statek/∂state0 over 50 steps with random inputs. Light: a tanh RNN, a product of w·tanh′ terms; dark: the LSTM cell path, fk. After 20 steps: RNN 10^-2.1, LSTM 10^-0.4. Below w = 1 the RNN signal vanishes; well above 1 the tanh saturates and it still vanishes. A forget gate near 1 keeps the path open.
Why engineers care

LSTMs were the workhorse of sequence learning from about 2014 to 2018 and still power many industrial forecasting and anomaly-detection systems.

📝 Quick check (Level 0)
0/3 answered
  1. 1. A recurrent network reads a series…
  2. 2. An LSTM's gates decide…
  3. 3. Compared with a linear model, an LSTM can learn…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • RNN: h_t = tanh(W[x_t, h_(t−1)] + b). The same weights are used at every step, and a read-out maps h to the forecast.
  • LSTM: a cell state c carries memory. The input gate i, forget gate f and output gate o (sigmoids) and a candidate g (tanh) update it: c_t = f⊙c_(t−1) + i⊙g, h_t = o⊙tanh(c_t). A GRU merges these gates into two.
  • Training: cut the series into windows of length T, predict the next value, minimise squared error with backpropagation through time (BPTT) and Adam.
  • Multi-step forecasts: the recursive strategy feeds predictions back in; the direct strategy trains a separate model for each horizon; the multi-output strategy predicts the whole horizon at once (seq2seq, MQ-RNN).
  • Global models: one network trained on many related series (DeepAR) shares patterns across them.
  • Practicalities: scale inputs with training statistics only, clip gradients, and use early stopping on a later validation period.
📝 Quick check (Level 1)
0/3 answered
  1. 1. The LSTM cell state is updated as…
  2. 2. The recursive multi-step strategy…
  3. 3. DeepAR is an example of…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

An LSTM in NumPy

Exercise 1.

  • An LSTM cell with four gates, a linear read-out from the last hidden state, BPTT and Adam.
  • A gradient check against central finite differences on a random 5-unit network.
  • Training a 12-unit LSTM on windows of 20 values of an amplitude-modulated sine, and testing on later windows.

Practice.

  • Always compare with persistence, seasonal naive and a linear AR: deep models often lose on short, noisy series.
  • Split by time (train, validation, test in order) and standardise with training statistics only.
  • Initialise the forget-gate bias to 1 and clip gradients to stabilise training.
  • Prefer global models when you have many related series.
  • Tools: PyTorch nn.LSTM, Darts, PyTorch Forecasting, GluonTS (DeepAR), NeuralForecast.
import numpy as np

sig = lambda z: 1 / (1 + np.exp(-z))

def lstm_step(W, b, x, h, c):
    H = h.shape[1]
    z = np.c_[x, h] @ W.T + b
    i, f, o = sig(z[:, :H]), sig(z[:, H:2*H]), sig(z[:, 2*H:3*H])
    g = np.tanh(z[:, 3*H:])
    c = f * c + i * g
    return o * np.tanh(c), c
🐍 Exercise 1: building and checking an LSTM
Implement the LSTM forward pass and backpropagation through time, verify the gradients numerically, and train it to predict a modulated sine wave.
📝 Quick check (Level 2)
0/3 answered
  1. 1. A good forget-gate bias initialisation is…
  2. 2. Deep forecasters should be compared with…
  3. 3. A library that provides DeepAR:

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Why gates help. In a plain RNN the gradient from step t back to step t − k is a product of k Jacobians. It shrinks or explodes geometrically. In an LSTM the cell state passes through c_t = f⊙c_(t−1) + …, so its gradient is multiplied by the forget gate, which the network can keep near 1. A constant forget gate f keeps information for about −1/ln f steps: 99 steps for f = 0.99.

Backpropagation through time. The forward pass stores each step’s inputs, gates and cell states. The backward pass runs in reverse: it accumulates dW from each step’s gate gradients and passes dh and dc back to the previous step. In Exercise 1 the analytic gradient matched finite differences to below 10⁻⁶, and a 12-unit LSTM predicted the modulated sine with test RMSE below a tenth of its sd.

Multi-step error accumulation. The recursive strategy feeds each prediction into the next input. Errors compound, especially for a model that is wrong in a systematic, nonlinear way. A linear model of a nonlinear chaotic system has such errors. The direct strategy avoids feedback but needs a model per horizon and ignores the dependence between horizons.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Plain RNN gradients over many steps tend to…
  2. 2. A forget gate of 0.99 keeps information for about…
  3. 3. Recursive multi-step forecasts suffer from…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

On a chaotic nonlinear series, how much does an LSTM gain over a linear autoregression one step and ten steps ahead, and does a direct 10-step model beat recursive forecasting?

History.

  • J. Elman (1990) introduced simple recurrent networks.
  • S. Hochreiter and J. Schmidhuber (1997) introduced the LSTM; F. Gers et al. (2000) added the forget gate.
  • K. Cho et al. (2014) proposed the GRU.
  • D. Salinas et al. (2020) developed DeepAR, a probabilistic global RNN forecaster used at Amazon, and S. Smyl’s ES-RNN won the M4 competition in 2018.

Exercise 2.

  • 1200 samples (every 3 time units) of the Mackey–Glass delay equation with τ = 17, standardised, plus noise with sd 0.02.
  • The first 800 points train and the rest test, using windows of 16 values.
  • Models: persistence, a linear AR(16) by least squares, and a 16-unit LSTM (60 epochs, Adam). Both models are applied recursively for 10 steps, and a second LSTM is trained directly on the 10-step target.

Seed 0, test RMSE:

model 1 step 10 steps
persistence 0.44 1.8
linear AR(16) 0.13 0.67
LSTM (recursive for 10 steps) 0.041 0.057
LSTM trained for 10 steps directly — 0.049
  • The LSTM was three times better than the linear AR one step ahead, close to the noise level of 0.02, which no model can beat.
  • The linear model’s errors compounded to 0.67 over 10 recursive steps, while the LSTM’s grew only to 0.057, more than ten times better. Persistence was worse than the series sd at 10 steps (1.8), because the series swings to the other side within 30 time units.
  • Direct and recursive LSTMs were similar: 0.049 against 0.057 here; in seeds 1 and 2, 0.049 against 0.073 and 0.059 against 0.056.
  • Seeds 1 and 2: LSTM one-step 0.048 and 0.037; linear AR 0.14 and 0.13 one step and 0.67 at 10 steps in both.
🐍 Exercise 2 (research): on a chaotic nonlinear series, how much does an LSTM gain over a linear autoregression one step and ten steps ahead, and does a direct 10-step model beat recursive forecasting?
Forecast the Mackey–Glass series with persistence, a linear AR(16) and a NumPy LSTM, one step ahead and ten steps ahead with recursive and direct strategies.

Recurrent forecasters in practice

  • Industry: DeepAR and MQ-RNN at Amazon, LSTMs for load forecasting and predictive maintenance, and LSTM autoencoders for anomaly detection.
  • Competitions: in M4 a hybrid of exponential smoothing and an LSTM won. In M5 gradient-boosted trees led, and pure RNNs were not dominant.
  • Successors: temporal convolutional networks and transformers parallelise over time; state-space layers (S4, Mamba) and xLSTM revisit recurrence at scale.
  • Caution: with short or noisy series, deep models often lose to ETS and ARIMA; always benchmark.

References

  1. S. Hochreiter and J. Schmidhuber (1997). “Long short-term memory.” Neural Computation.
  2. F. A. Gers, J. Schmidhuber and F. Cummins (2000). “Learning to forget: continual prediction with LSTM.” Neural Computation.
  3. D. Salinas, V. Flunkert, J. Gasthaus and T. Januschowski (2020). “DeepAR: probabilistic forecasting with autoregressive recurrent networks.” International Journal of Forecasting.
  4. S. Smyl (2020). “A hybrid method of exponential smoothing and recurrent neural networks for time series forecasting.” International Journal of Forecasting.
  5. H. Hewamalage, C. Bergmeir and K. Bandara (2021). “Recurrent neural networks for time series forecasting: current status and future directions.” International Journal of Forecasting.