Skip to content

Recurrent Neural Networks

Source: CS1674 Ch.15 (Part B). RNNs process sequences with shared weights across time, maintaining a hidden state (memory). Vanilla RNNs suffer vanishing/exploding gradients → LSTM / GRU fix this. Key CV application: image captioning.

1. Why Sequences?

In CV, data associated with time = video. More generally, RNNs handle sequential prediction:

TaskExample
Text classificationSentiment ("The food was really good" → positive)
Text generationLanguage modeling — sample next token
Image captioning"A cat sitting on a suitcase" (neuraltalk2)
Machine translationSequence-to-sequence (many→many)

Input–output scenarios

  • One-to-one: feedforward network.
  • One-to-many: sequence generation (captioning).
  • Many-to-one: sequence classification (sentiment).
  • Many-to-many: translation, captioning.

2. The Recurrent Unit (Vanilla RNN, Elman 1990)

Recurrence:

ht=fW(xt,ht1)

The hidden state ht is the "memory"/"context" carried across time.

2.1 Cell equations

ht=tanh(Wxxt+Whht1)yt=softmax(Wyht)et=logyt(yt)(cross-entropy with ground-truth token)

Weights Wx,Wh,Wy are shared across all time steps.

2.2 Forward pass

Unroll in time; at each step compute ht from xt and ht1, then yt. (tanh derivative: ddatanha=1tanh2a.)


3. Training: Backpropagation Through Time (BPTT)

  • Treat the unfolded network as one big feed-forward net taking the whole sequence.
  • Compute weight gradients at each copy, then sum (or average) and apply to the shared RNN weights.
  • Problem: long sequences → huge memory.

Truncated BPTT

  • Run forward over chunks of k steps; backprop within each chunk.
  • Carry hidden states forward in time, but only backpropagate for a smaller number of steps.

3.1 Backward pass (vanilla RNN)

eht=eytythteWx=eht(1tanh2())xteht1=Wh(1tanh2())eht

3.2 Vanishing / exploding gradients

eht1=Wh(1tanh2())eht

Computing the gradient for step tk involves many repeated multiplications by Wh and rescalings in [0,1]:

  • If the largest singular value of Wh < 1 → gradients vanish.
  • If > 1 → gradients explode.

This is why vanilla RNNs struggle with long-range dependencies.


4. LSTM — Long Short-Term Memory (Hochreiter & Schmidhuber 1997)

Adds a memory cell ct that is not subject to matrix multiplication or squishing at every step → avoids gradient decay.

Gates and equations

[gtitftot]=[tanhσσσ][WgWiWfWo][xtht1]ct=ftct1+itgtht=ottanh(ct)
  • gt = new candidate content, it = input gate, ft = forget gate, ot = output gate.
  • Key: the gradient path from ct to ct1 involves only addition and element-wise multiplication (no matrix multiply / activation), so error can flow many steps without vanishing.

5. GRU — Gated Recurrent Unit (Cho et al. 2014)

Simpler than LSTM: merges forget + output into an update gate, drops the separate cell state.

rt=σ(Wr[xt,ht1]+br)(reset)h~t=tanh(W[xt,rtht1])(candidate)zt=σ(Wz[xt,ht1]+bz)(update)ht=(1zt)ht1+zth~t

More efficient than LSTM, often comparable performance.


6. RNN Variants

  • Multi-layer RNNs: stack hidden layers; skip connections across layers/time allowed.
  • Bi-directional RNNs: process forward and backward (common in speech recognition) → each state sees past and future context.

7. Application: Image Captioning (Show and Tell, Vinyals et al. CVPR 2015)

  • Encoder: CNN extracts image features I.
  • Decoder: RNN/LSTM generates words one at a time, conditioned on I and previous words.
  • Training: maximize likelihood of reference caption Y=(Y1,,YN):
L(I,Y)=i=1NlogPW(YiY1,,Yi1,I)
  • Test time: avoid always picking the max-likelihood word (greedy can be poor). Use beam search with beam width k: keep the k top-scoring candidate sentences by sum of per-word log-likelihoods; expand successors and keep best k each step.

Pipeline: one-hot word → word embedding → LSTM → softmax over vocabulary → (next word).


8. Summary

  • RNNs share weights over time and keep a hidden state; trained by BPTT (truncated in practice).
  • Vanilla RNNs vanish/explode because gradients multiply by Wh repeatedly.
  • LSTM (cell + gates) and GRU (update/reset gates) enable long-range memory.
  • Use bi-directional and multi-layer RNNs; apply to captioning via encoder–decoder + beam search.

9. Seq2seq with Additive Attention (Recap)

For machine translation (Bahdanau), the decoder hidden state st1 produces a query; alignment scores with encoder states hi:

et,i=vtanh(Wa[st1;hi]),at,i=eet,ijeet,j,ct=iat,ihi

The context ct replaces the fixed bottleneck vector → each output word attends to relevant source words (fixes the information bottleneck).


10. Beam Search & Teacher Forcing

  • Beam search: keep the top-k partial sequences by cumulative log-likelihood ilogP(yiy<i,I); expand and prune each step. Better than greedy (k=1).
  • Length normalization: divide score by (T)α to avoid favoring short sequences.
  • Teacher forcing: during training, feed the ground-truth previous word (not the model's own prediction) — stabilizes training but can cause exposure bias; mitigated by scheduled sampling.

11. Representations: Character vs. Word

  • Word-level: embeddings per word (large vocab, needs unknown-word handling).
  • Character-level: smaller vocab, handles misspellings/NEs, longer sequences (harder for RNNs).
  • Subword (BPE): the common compromise (used in Transformers).

12. Beyond Captioning

  • Video: extend RNN over frames; combine with CNN features per frame.
  • Handwriting / speech recognition: bi-directional RNNs over time steps.
  • Video captioning / VQA: encode frames + language, decode answer/caption.

13. LSTM/GRU Gradient Flow

The cell-state path in LSTM, ct=ftct1+itgt, gives a constant (additive, gated) path for gradients → they flow across many timesteps without vanishing. GRU's zt gate plays a similar role with fewer parameters. This is why they train on long sequences where vanilla RNNs fail.

RNNs = weight-shared, time-unrolled networks; LSTMs/GRUs fix the gradient problem; attention + beam search unlock strong sequence generation (and paved the way for Transformers in Ch.16).