Recurrent networks and LSTMs
Networks with memory for sequences: recurrence, backpropagation through time, vanishing gradients and gates.
Animated explanation
The idea
Sentences, sensor streams and stock prices are sequences: order matters and lengths vary. A recurrent neural network reads them one element at a time, carrying a hidden state , a running summary of everything seen so far. At each step it combines the previous state with the new input using the same weights, so it handles any length.
Training unrolls the loop into a deep network, one layer per time step, and backpropagates through it (BPTT). That depth is the problem: gradients are multiplied by the recurrent weights at every step and tend to vanish or explode, so plain RNNs forget after a few dozen steps. LSTMs and GRUs add gates and an additive memory cell that lets information and gradients survive long gaps. Today, attention-based transformers have taken over most language tasks, but the ideas of state and gating remain central.
Shapes of sequence problems
- Many-to-one: read a sequence, output one label (sentiment, anomaly detection).
- One-to-many: generate a sequence (captioning).
- Many-to-many, aligned: a label per step (tagging, frame classification).
- Sequence-to-sequence: an encoder RNN summarises, a decoder RNN generates (translation), the setting where attention was invented.
Training tips
Clip the gradient norm (e.g. at 1–5) to stop explosions; use LSTM/GRU cells; truncate BPTT to a window for very long streams; initialise the forget-gate bias to around 1 so the cell remembers by default; use teacher forcing for generation.
The algorithm, step by step
- 1Initialise .
- 2For : (or the LSTM update).
- 3Compute outputs from the relevant states (last state, or every state).
- 4Backpropagate through the unrolled steps (BPTT), clip the gradient norm, update the shared weights.
The maths
RNN cell
LSTM gates
LSTM state
Gradient clipping
Strengths and weaknesses
Strengths
- Handles variable-length sequences with shared weights
- Natural for streaming (constant memory per step)
- LSTMs capture long-range dependencies far better than plain RNNs
Weaknesses
- Sequential computation: slow to train on long sequences
- Vanishing/exploding gradients in plain RNNs
- Largely superseded by transformers for language
Reach for it when…
Check your understanding
Lambdian Lab
RNN and LSTM forward passes
Implement the forward computations (no training).
- rnn_forward(X, Wh, Wx, b, h0): X has shape (T, d); return all hidden states, shape (T, h).
- lstm_step(x, h, c, W, b): one LSTM step where W has shape (4h, h + d) stacking the [input, forget, output, candidate] blocks applied to concat([h, x]); return (h_new, c_new).
- running_sum_weights(): choose (Wh, Wx, b) for a 1-unit RNN with identity activation so that h_T equals the sum of a 1-D sequence.
- gradient_factor(w, steps): , the scalar BPTT factor.