Recurrent Neural Networks (RNNs)
“The canonical sequence-modeling workhorse before LSTMs and GRUs showed up.”
1. Intuition in Plain Words
Imagine you’re reading a sentence one word at a time and jotting down a running summary of what you’ve seen so far.
At every new word you:
- Look at the word.
- Read your current summary.
- Write an updated summary.
- Possibly emit an output (e.g., the next-word probability).
That running summary is the RNN’s hidden state. Because the same update rule is reused at every time-step, RNNs can, in theory, capture patterns of arbitrary length.
2. Minimal Math Formulation
For a sequence (x_1, x_2, \dots, x_T):
Hidden-state update
[
h_t = \phi\bigl(W_{xh},x_t + W_{hh},h_{t-1} + b_h\bigr)
]
Output layer (task-dependent)
[
y_t = g\bigl(W_{hy},h_t + b_y\bigr)
]
Where
• (x_t \in \mathbb{R}^{d_x}) … input vector at step t
• (h_t \in \mathbb{R}^{d_h}) … hidden state
• (y_t) … output (e.g. class probs, real value, etc.)
• (W_{xh}\in \mathbb{R}^{d_h\times d_x}), (W_{hh}\in\mathbb{R}^{d_h\times d_h}), (W_{hy}\in\mathbb{R}^{d_y\times d_h})
• (\phi(\cdot)) … usually tanh or ReLU
• (g(\cdot)) … softmax, identity, etc.
Same weights are reused for all time-steps ⇒ weight sharing across time.
2.1. Unfolding in Time
t=1 t=2 t=3
x1 ----> x2 ----> x3 ...
\ \ \
h0->h1-> h2 -> h3 ...
\
y2
Mathematically you can “unroll” the network into a deep feed-forward chain of length T; this viewpoint is key for training.
3. Training: Back-Propagation Through Time (BPTT)
- Forward pass through t=1…T to obtain all (h_t) and (y_t).
- Compute sequence loss, e.g.
• Classification: ( \mathcal{L}= -\sum_{t}\text{log} P_{\theta}( \hat{y}t | x{\le t}))
• Regression: ( \mathcal{L}= \sum_t ||y_t-\hat y_t||^{2})
- Backward pass: back-propagate gradients from t=T to 1 through the unrolled graph, accumulating gradients for the shared weight matrices.
- Update parameters with an optimizer (SGD, Adam, RMSprop).
- Clip gradients (often) to tame exploding gradients.
⚠️ Because the chain can be long, partial derivatives look like
[
\frac{\partial \mathcal{L}}{\partial W_{hh}} = \sum_{t}\Bigl( \prod_{k=t+1}^{T} W_{hh}^\top \operatorname{diag}(\phi'(a_k)) \Bigr)\dots
]
so eigenvalues of (W_{hh}) < 1 ⇒ gradients shrink (vanish); > 1 ⇒ explode.
4. Practical Tricks & Variants
• Truncated BPTT: back-prop only K steps backwards (e.g., K=20–30) to save memory and stabilize training.
• Gradient clipping: (g \leftarrow \frac{\tau}{|g|} g) with threshold τ.
• Regularization: dropout on inputs or recurrent connections (e.g., variational dropout).
• Initialization: orthogonal or scaled‐identity (W_{hh}) can help keep gradients’ magnitude.
• Bidirectional RNN: run a second RNN backwards and concatenate states ( [\overrightarrow{h_t};\overleftarrow{h_t}] ) for context from both directions.
• Gated variants: LSTM, GRU add gates to learn how much to forget/reset, effectively solving the vanishing‐gradient issue.
5. Simple Numpy-Style Pseudocode
def rnn_forward(X, params):
Wxh, Whh, Why, bh, by = params
h = np.zeros((batch, hidden))
outputs = []
for x_t in X: # iterate over time
h = np.tanh(x_t @ Wxh + h @ Whh + bh)
y = h @ Why + by
outputs.append(y)
return outputs
Back-prop would store all h_t, then loop backward to accumulate gradients.
6. When Are Vanilla RNNs Still Useful?
• Character-level language modeling on short contexts
• Tiny models on microcontrollers (LSTM/GRU bigger)
• As building blocks inside bigger architectures (e.g., Echo State Networks, Simple Recurrent Unit research)
But for most realistic long-range tasks, you’ll reach for LSTMs, GRUs, or Transformers.
7. Key Takeaways
- RNNs add recurrence: output depends on current input + previous hidden state.
- Weight sharing across time gives them a form of memory.
- Training uses back-prop through time, but gradients can vanish/explode.
- Gated RNNs (LSTM/GRU) and modern architectures mitigate those issues.
That’s the core of how vanilla RNNs tick!