Search

Search papers and lessons

Recurrent Neural Network

Level 3 · 9 min read

A recurrent neural network reads a sequence one step at a time and carries a hidden state forward, so each output can depend on everything it has seen so far.

On this page

  • Colour = topic mix
  • Calculus
  • Linear algebra
  • Neural network basics
  • Probability
  • Architectures
  • Losses & regularization
  • Sign in to see your progress

TL;DR

A recurrent neural network processes a sequence one element at a time. At each step it combines the current input with a hidden state carried over from the previous step, produces a new hidden state, and optionally emits an output. Because the same weights are reused at every step, the network can handle sequences of any length, and its output at step t can depend on everything that came before.

The hidden state is a running summary of the past. Its weights are shared across time, which is what makes the model compact, and also what makes training on long sequences hard.

Where you'll see it: in character-level and word-level language models, in speech recognition front ends, in time-series forecasting, and as the encoder and decoder inside early machine translation systems.

Intuition

Reading a sentence with a notepad

Imagine reading a sentence one word at a time while keeping a notepad. Each new word you read, you combine with what is already written on the notepad, then rewrite the notepad. The notepad never gets bigger; you only ever update the same page. By the last word, the page should hold enough of the sentence to finish it sensibly.

That is a recurrent network. The notepad is the hidden state, the rewriting rule is the network's weights, and the same rule is applied to every word. A feedforward network, by contrast, takes a fixed-size input all at once. If you want it to handle a sentence, you must choose a maximum length in advance and pad the rest, and it has no built-in notion that word 3 came before word 4.

Why does the shared rule matter? Think about how many words a sentence can have. A separate weight matrix for each position would need a new set of parameters for every possible length, and it would learn nothing about the fact that "dog" means the same thing whether it appears first or fifth. Reusing one rule at every step means the network learns a single way of updating memory, and it applies that way to a sentence of 5 words or 500.

flowchart LR
  h0[h0] --> C1((cell))
  x1[x1] --> C1
  C1 --> h1[h1]
  h1 --> C2((cell))
  x2[x2] --> C2
  C2 --> h2[h2]
  h2 --> C3((cell))
  x3[x3] --> C3
  C3 --> h3[h3]

The diagram is the same cell drawn three times, one per time step. Every cell has the same weights; only the inputs and the hidden state change.

The math

One step

Let xt∈Rd\mathbf{x}_t \in \mathbb{R}^{d} be the input at time tt and ht−1∈Rm\mathbf{h}_{t-1} \in \mathbb{R}^{m} be the hidden state from the previous step. The vanilla recurrent update is

ht=ϕ(Whx xt+Whh ht−1+bh),\mathbf{h}_t = \phi\left(W_{hx}\,\mathbf{x}_t + W_{hh}\,\mathbf{h}_{t-1} + \mathbf{b}_h\right),

where WhxW_{hx} is an m×dm \times d matrix mapping the input into the hidden space, WhhW_{hh} is an m×mm \times m matrix mapping the old state into the new one, bh\mathbf{b}_h is a bias vector, and ϕ\phi is an activation function applied elementwise. The most common choice is the hyperbolic tangent, which squashes every value into the range from −1-1 to 11. If the task needs an output at each step, a second linear map reads the state:

yt=Wyh ht+by,\mathbf{y}_t = W_{yh}\,\mathbf{h}_t + \mathbf{b}_y,

and for classification the output is passed through a Softmax to give a probability distribution over labels.

The first state h0\mathbf{h}_0 is usually a vector of zeros, or it is learned like any other parameter.

Unrolling and sharing

Applying the update repeatedly gives one long chain. For a sequence of length TT, the final state is a function of every input:

hT=ϕ(Whx xT+Whh ϕ(Whx xT−1+Whh ϕ(⋯ ))).\mathbf{h}_T = \phi\left(W_{hx}\,\mathbf{x}_T + W_{hh}\,\phi\left(W_{hx}\,\mathbf{x}_{T-1} + W_{hh}\,\phi\left(\cdots\right)\right)\right).

The matrices WhxW_{hx}, WhhW_{hh} and WyhW_{yh} are the same at every position. The parameter count is fixed no matter how long the sequence is. That sharing is what lets a single set of weights generalise across positions.

Backpropagation through time

To train the network, unroll it over the TT steps and treat the copies as one deep feedforward network with shared weights. The loss is a sum over the outputs, for example L=∑tℓ(yt,y^t)L = \sum_t \ell(\mathbf{y}_t, \hat{\mathbf{y}}_t). The gradient with respect to WhhW_{hh} collects a contribution from every time step, and each contribution is found with the Chain Rule. For the contribution from step TT back to step kk, the chain of derivatives includes a product of Jacobians:

∂hT∂hk=∏t=k+1T∂ht∂ht−1,∂ht∂ht−1=diag ⁣(ϕ′(⋅))Whh.\frac{\partial \mathbf{h}_T}{\partial \mathbf{h}_k} = \prod_{t=k+1}^{T} \frac{\partial \mathbf{h}_t}{\partial \mathbf{h}_{t-1}}, \qquad \frac{\partial \mathbf{h}_t}{\partial \mathbf{h}_{t-1}} = \mathrm{diag}\!\left(\phi'(\cdot)\right) W_{hh}.

This product is the source of the main difficulty, and it is worked through in a worked example below. The method is called backpropagation through time, and it is ordinary Backpropagation applied to the unrolled graph.

Worked examples

Example
A one-unit recurrence by hand

Take a single hidden unit with scalar weights wx=1w_x = 1, wh=0.5w_h = 0.5, bias b=0b = 0, and tanh activation. Start from h0=0h_0 = 0 and feed the inputs x1=1x_1 = 1, x2=0x_2 = 0, x3=0x_3 = 0.

  1. Step 1: h1=tanh⁡(1⋅1+0.5⋅0)=tanh⁡(1)≈0.762h_1 = \tanh(1 \cdot 1 + 0.5 \cdot 0) = \tanh(1) \approx 0.762.
  2. Step 2: h2=tanh⁡(1⋅0+0.5⋅0.762)=tanh⁡(0.381)≈0.364h_2 = \tanh(1 \cdot 0 + 0.5 \cdot 0.762) = \tanh(0.381) \approx 0.364.
  3. Step 3: h3=tanh⁡(0+0.5⋅0.364)=tanh⁡(0.182)≈0.180h_3 = \tanh(0 + 0.5 \cdot 0.364) = \tanh(0.182) \approx 0.180.

The input was a single spike at time 1, but the state at time 3 is still nonzero: the memory of that spike decays by about half each step, filtered through tanh. This is the whole behaviour of the recurrence in miniature. Had whw_h been 1.5, the state would have decayed much more slowly (here h2=tanh⁡(1.143)≈0.815h_2 = \tanh(1.143) \approx 0.815, even larger than h1h_1, before tanh saturation caps it), which previews the training problem.

Example
Next-word prediction over a tiny vocabulary

Consider a character-level language model with a vocabulary of three symbols: a, b and end. The network reads the characters "a" then "b", and must predict the next one. Suppose a 2-number hidden state after reading "a" and "b" gives logits (0.2,1.1,−0.4)(0.2, 1.1, -0.4) for (a, b, end).

  1. Softmax: the exponentials are e0.2≈1.221e^{0.2} \approx 1.221, e1.1≈3.004e^{1.1} \approx 3.004 and e−0.4≈0.670e^{-0.4} \approx 0.670.
  2. The sum is 1.221+3.004+0.670=4.8951.221 + 3.004 + 0.670 = 4.895.
  3. Probabilities: p(a)≈0.249p(\text{a}) \approx 0.249, p(b)≈0.614p(\text{b}) \approx 0.614, p(end)≈0.137p(\text{end}) \approx 0.137.
  4. If the true next character is "b", the loss is −ln⁡(0.614)≈0.488-\ln(0.614) \approx 0.488 nats.

The prediction depends on the whole history, not only the last character: the hidden state was updated by both "a" and "b". Change the first character and the same final character gets a different distribution, which is the point of the recurrence.

Tradeoffs and failure modes

A recurrent network is a good choice when order matters and the sequence is processed in order, for example streaming audio or a generation step that must consume its own output. It is a poor choice when the whole input is available at once and the task needs to relate distant positions directly, since information must pass through every intermediate step.

SituationWhat goes wrongBetter choice
Long sequences (hundreds of steps)Gradients vanish, so early inputs stop influencing trainingAn [[long-short-term-memory
Gradients explode during trainingUpdates become huge and training divergesGradient Norm Clipping
Whole sequence available at inferenceProcessing is sequential, so it cannot be parallelised across timeA Transformer, which processes all positions in parallel (a [[bidirectional-rnn
Need to relate distant tokens directlyThe signal must cross many steps to connect them[[attention-mechanism
Very small data, short sequencesFine, but the model can still overfitSmaller hidden state and early stopping

The two central failure modes are the vanishing gradient problem and exploding gradients. Both come from the product of Jacobians in the training formula above. If the typical size of WhhW_{hh} and the derivative of the activation is below 1, the product shrinks exponentially with the distance T−kT - k, and the network cannot learn long-range dependencies. If it is above 1, the product grows exponentially and training is unstable. Careful initialisation and clipping help with the second; gating is the main fix for the first.

History

The idea of feeding a network's output back into itself is older than neural networks as a field. Hopfield networks in the early 1980s used feedback, and Jordan and Elman introduced simple recurrent architectures for sequence tasks around 1986 and 1990. Elman's 1990 paper "Finding Structure in Time" showed that a network with a context layer could discover word classes and structure from a stream of text, and the architecture is still often called the Elman network.

Training was the bottleneck. Backpropagation through time made gradient computation possible, but in the 1990s the vanishing gradient problem made long-range learning nearly impossible in practice. Hochreiter's 1991 analysis explained why, and the LSTM of 1997 was the main remedy. Pascanu, Mikolov and Bengio analysed exploding and vanishing gradients in detail in 2013 and popularised gradient clipping as the standard fix for the first.

Recurrent networks dominated sequence modelling for most of the 2010s, in speech recognition, translation and language modelling. Their sequential structure is also what made the Transformer attractive: replacing the recurrence with attention removed the need to process one step at a time.

Check yourself

QuestionRecall: what does the hidden state ht\mathbf{h}_t represent, and why is the same set of weights used at every step?Show answer

The hidden state is a fixed-size summary of everything the network has read up to step tt. The same weights are reused because the rule for updating memory should not depend on position; sharing them keeps the parameter count fixed and lets the network handle sequences of any length.

QuestionComputation: a scalar recurrence has wh=0.5w_h = 0.5, wx=1w_x = 1, bias 0, and tanh activation. Starting from h0=0h_0 = 0 with inputs x1=1x_1 = 1 then x2=0x_2 = 0, what is h2h_2 to three decimal places?Show answer

Step 1 gives h1=tanh⁡(1)≈0.762h_1 = \tanh(1) \approx 0.762. Step 2 gives h2=tanh⁡(0.5×0.762)=tanh⁡(0.381)≈0.364h_2 = \tanh(0.5 \times 0.762) = \tanh(0.381) \approx 0.364.

QuestionWhy: why do gradients vanish over long sequences in a vanilla RNN?Show answer

Backpropagation through time multiplies one Jacobian per step, and each Jacobian contains the recurrent weight matrix and the derivative of the activation. When these typically have magnitude below 1, the product shrinks exponentially with the number of steps between the early input and the later loss, so the early inputs receive almost no gradient signal.

QuestionApplied: you are building a model to detect a fault in a sensor stream that sends 10,000 readings per second, and the fault signature can appear up to 30 seconds before the alarm is needed. A vanilla RNN fails to learn it. What would you change, and why?Show answer

Thirty seconds at 10,000 readings per second is 300,000 steps, far beyond what a vanilla RNN can carry gradients across. Switch to an LSTM or GRU, which uses gates to keep the state stable over long spans, and consider clipping gradients for stability. Downsampling or extracting windowed features before the recurrence would also shorten the effective sequence considerably.

Sources