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 be the input at time and be the hidden state from the previous step. The vanilla recurrent update is
where is an matrix mapping the input into the hidden space, is an matrix mapping the old state into the new one, is a bias vector, and is an activation function applied elementwise. The most common choice is the hyperbolic tangent, which squashes every value into the range from to . If the task needs an output at each step, a second linear map reads the state:
and for classification the output is passed through a Softmax to give a probability distribution over labels.
The first state 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 , the final state is a function of every input:
The matrices , and 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 steps and treat the copies as one deep feedforward network with shared weights. The loss is a sum over the outputs, for example . The gradient with respect to collects a contribution from every time step, and each contribution is found with the Chain Rule. For the contribution from step back to step , the chain of derivatives includes a product of Jacobians:
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
Take a single hidden unit with scalar weights , , bias , and tanh activation. Start from and feed the inputs , , .
- Step 1: .
- Step 2: .
- Step 3: .
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 been 1.5, the state would have decayed much more slowly (here , even larger than , before tanh saturation caps it), which previews the training problem.
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 for (a, b, end).
- Softmax: the exponentials are , and .
- The sum is .
- Probabilities: , , .
- If the true next character is "b", the loss is 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.
| Situation | What goes wrong | Better choice |
|---|---|---|
| Long sequences (hundreds of steps) | Gradients vanish, so early inputs stop influencing training | An [[long-short-term-memory |
| Gradients explode during training | Updates become huge and training diverges | Gradient Norm Clipping |
| Whole sequence available at inference | Processing is sequential, so it cannot be parallelised across time | A Transformer, which processes all positions in parallel (a [[bidirectional-rnn |
| Need to relate distant tokens directly | The signal must cross many steps to connect them | [[attention-mechanism |
| Very small data, short sequences | Fine, but the model can still overfit | Smaller 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 and the derivative of the activation is below 1, the product shrinks exponentially with the distance , 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 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 . 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 , , bias 0, and tanh activation. Starting from with inputs then , what is to three decimal places?Show answer
Step 1 gives . Step 2 gives .
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
- Elman (1990), Finding Structure in Time: doi.org/10.1207/s15516709cog1402_1
- Pascanu, Mikolov, Bengio (2013), On the difficulty of training recurrent neural networks: arxiv.org/abs/1211.5063
- Recurrent neural network (Wikipedia): en.wikipedia.org/wiki/Recurrent_neural_network
- Goodfellow, Bengio, Courville, Deep Learning, Chapter 10: deeplearningbook.org