5.1 · The family tree
5.2 · Convolutional Neural Networks (CNNs)
Definition. A CNN is a neural network that processes grid-shaped data (images, audio spectrograms) by sliding small filters across the input. Each filter detects a local pattern — an edge, a colour blob, a corner — and the network stacks these into increasingly abstract concepts (edges → eyes → faces).
Why it works. Two built-in priors: locality (a pixel relates most to its neighbours) and translation invariance (a cat is a cat wherever it appears in the frame).
A CNN, drawn
| Operation | Definition | Example |
|---|---|---|
| Convolution | Slides a small $k \times k$ filter across the input; output pixel = dot product of filter and patch. | A 3×3 edge filter highlights vertical lines. |
| ReLU | Non-linearity after each conv so the network can model curved features. | Negative activations zeroed out. |
| Pooling | Down-samples a region into a single value (max or avg). | Max-pool 2×2 turns 224 → 112; cuts compute by 4×. |
| Stride / padding | Stride = step size of the slide; padding = pixels added at borders. | Stride 2 halves resolution; "same" padding keeps it. |
| Skip connections | Add the input to the output of a block: $y = x + f(x)$. | ResNet — lets gradients flow through 100+ layers. |
Everyday example. A photo-app tags pictures as "beach", "dog", or "food". A CNN trained on ImageNet recognises objects with super-human accuracy on common categories.
Landmark architectures: LeNet (1998) → AlexNet (2012, the spark) → VGG → GoogLeNet → ResNet → EfficientNet → Vision Transformer (ViT, 2020 — applies the transformer to image patches).
5.3 · Recurrent Neural Networks (RNN / LSTM / GRU)
Definition. An RNN is a network that processes sequences one element at a time, carrying a hidden state $\mathbf{h}_t$ that summarises everything it has seen so far. At each step:
$\mathbf{h}_t = \tanh(\mathbf{W}_h \mathbf{h}_{t-1} + \mathbf{W}_x \mathbf{x}_t + \mathbf{b})$
An RNN unrolled in time
Everyday example. Predict the next word in a sentence; classify the sentiment of a tweet; translate "Hello" → "Bonjour". Anything where order matters.
| Variant | Definition | Why it exists |
|---|---|---|
| Vanilla RNN | The simple recurrence above. | Suffers from vanishing gradients — forgets things from > 20 steps ago. |
| LSTM | Adds three gates (input, forget, output) and a separate cell state that flows largely unchanged. | Preserves information across hundreds of steps. Powered Google Translate (2016) and Alexa. |
| GRU | A lighter LSTM with only update + reset gates. | Fewer parameters, similar quality. |
| Bidirectional | Two RNNs — one reading left→right, one right→left — concatenated. | Useful when you can see the whole sequence (e.g. tagging), not for live generation. |
5.4 · Autoencoders & VAEs
Definition. An autoencoder is a network with a deliberate bottleneck. It learns to compress an input down to a tiny latent vector $\mathbf{z}$ and then reconstruct the original from that vector. The reconstruction loss forces $\mathbf{z}$ to keep only what matters.
Everyday examples.
- Anomaly detection. Train on normal credit-card transactions; flag anything that reconstructs poorly.
- Denoising. Add noise to the input, ask the network to recover the clean version → image denoising.
- Representation learning. The bottleneck $\mathbf{z}$ is the linear ancestor of every "embedding" you use today.
VAE (Variational Autoencoder) — the bottleneck is forced to be a probability distribution (mean + variance). You can then sample new points and decode them — generating novel images, molecules, etc.
5.5 · GANs — the adversarial duet
Definition. A GAN (Generative Adversarial Network) pits two networks against each other in a minimax game:
- Generator $G$: takes random noise $z$ and produces a fake sample $G(z)$.
- Discriminator $D$: looks at a sample and tries to tell real from fake.
$G$ improves by fooling $D$; $D$ improves by catching $G$. At equilibrium, $G$ produces samples indistinguishable from real ones.
Example. StyleGAN-generated faces of people who never existed; deepfake images. GANs dominated photoreal generation 2017–2022 but training is famously unstable, which is one reason diffusion took over.
5.6 · Diffusion models
Definition. A diffusion model learns to reverse a noising process. Imagine taking a clean image and gradually adding Gaussian noise until it's pure static. The model is trained to do the opposite — starting from noise, predict slightly cleaner versions step by step until a sharp image emerges.
Example. Stable Diffusion, DALL·E 3, Midjourney, Sora, Veo — virtually every modern image / video generator. Conditioning on a text prompt steers the denoising toward "an astronaut riding a horse on Mars".
Diffusion has three structural advantages:
- Stable training (no adversarial game).
- Controllable via classifier-free guidance and additional conditions (text, depth, sketches, poses).
- Composable — works for images, audio, video, 3D, even action sequences in robotics.
5.7 · The Transformer
The Transformer replaced recurrence with self-attention: every token can directly attend to every other token, in parallel.
The core operation, scaled dot-product attention:
$\mathrm{Attn}(\mathbf{Q}, \mathbf{K}, \mathbf{V}) = \mathrm{softmax}\!\left(\dfrac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d_k}}\right)\mathbf{V}$
Each token computes how much to "pay attention" to every other token via $\mathbf{Q}\mathbf{K}^\top$, then mixes their values $\mathbf{V}$. We unpack this in detail in Chapter 6.
5.8 · One table to compare them all
| Architecture | Inductive bias | Strong at | Weak at |
|---|---|---|---|
| MLP | None | Tabular features | Sequences, images |
| CNN | Local + translation invariant | Images, audio spectrograms | Long-range deps |
| RNN / LSTM | Recurrence | Streaming sequences | Parallelization |
| Autoencoder / VAE | Bottleneck | Compression, anomaly detection | High fidelity gen |
| GAN | Adversarial | Photoreal generation | Stability, diversity |
| Diffusion | Iterative denoising | Controlled gen, multi-modal | Slow sampling |
| Transformer | Pairwise attention | Almost everything | $O(n^2)$ in sequence length |
5.9 · Evaluation metrics — by architecture / task
Deep models inherit the classification & regression metrics from Ch 3 — but each modality has its own gold-standard metrics. Use the right column to know which numbers to report.
| Task | Metric | Definition |
|---|---|---|
| Image classification | Top-1 / Top-5 accuracy | Did the true class appear in the top 1 / 5 predictions? Standard on ImageNet. |
| Object detection | IoU (Intersection over Union) | Area of overlap between predicted & ground-truth box, divided by their union. |
| Object detection | [email protected] / [email protected]:.95 | Mean Average Precision averaged across IoU thresholds. COCO benchmark. |
| Semantic segmentation | Pixel accuracy, mIoU, Dice | Pixel-wise correctness; mean IoU across classes; Dice = $2|A \cap B|/(|A|+|B|)$. |
| Instance segmentation | AP_mask, AR_mask | Mask-level versions of AP and Average Recall. |
| Pose estimation | PCK, OKS | Percent of Correct Keypoints; Object Keypoint Similarity. |
IoU — Intersection over Union, drawn
| Task | Metric | Definition |
|---|---|---|
| Sequence labelling (NER, POS) | Token / Entity F1 | Per-token or per-entity precision & recall; CONLL-style evaluation. |
| Sequence forecasting | MAPE / sMAPE / RMSE | Same as regression metrics, applied per time step. |
| Language modelling | Perplexity = $\exp(\text{cross-entropy})$ | Average uncertainty per token; lower is better. |
| Sequence classification | Accuracy / F1 / ROC-AUC | Standard classification metrics on the final-state head. |
| Task | Metric | Definition |
|---|---|---|
| Machine translation | BLEU | Modified n-gram precision vs reference(s), with brevity penalty. |
| Translation (newer) | chrF / chrF++ | Character-n-gram F-score; tolerant of morphology. |
| Translation (learned) | COMET / BLEURT | Learned regressors that predict human quality scores; SOTA for MT eval. |
| Summarisation | ROUGE-1 / ROUGE-2 / ROUGE-L | Recall of unigrams, bigrams, longest-common-subsequence. |
| Question answering | Exact Match, F1, SQuAD | EM = exact string match; F1 = token overlap with answer. |
| Semantic similarity | BERTScore | Cosine similarity of contextual embeddings between candidate & reference. |
| Modality | Metric | Definition |
|---|---|---|
| Image generation | FID (Fréchet Inception Distance) | Distance between feature distributions of real vs generated images. Lower = better, more realistic. |
| Image generation | Inception Score (IS) | Combines image classifier confidence (sharpness) and label diversity. Higher = better. |
| Text → image | CLIP Score | Cosine similarity between CLIP embedding of prompt and generated image. |
| Image quality | PSNR, SSIM, LPIPS | Peak-signal-to-noise; structural similarity; learned perceptual distance. |
| Video generation | FVD (Fréchet Video Distance) | FID extended over temporal features. |
| Diversity | Precision & Recall for generative models | Estimate how much of the real manifold the model covers (recall) vs how realistic its samples are (precision). |
| Human side-by-side | Pairwise preference / Elo | % of times judges prefer model A over B; Elo aggregates many pairwise comparisons. |
| Aspect | Metric | Definition |
|---|---|---|
| Language modelling | Perplexity | $\exp(\text{cross-entropy})$ on held-out tokens. |
| Multi-task benchmark | MMLU, BBH, GSM8K, MATH, HumanEval, ARC, HellaSwag | Standardised academic suites covering reasoning, code, knowledge. |
| Reasoning | Pass@k | Probability that at least one of k samples is correct (code & math). |
| Instruction following | IFEval, MT-Bench | Verifiable instructions; GPT-4 judge on multi-turn. |
| Open-ended generation | LLM-as-Judge, Pairwise Elo | A strong LLM scores against a rubric; LMSys arena uses pairwise Elo. |
| Safety | Jailbreak success rate, Toxicity, PII leak rate | Red-team and safety-specific metrics (see Ch 19). |
| RAG-style | Context recall, faithfulness | Did retrieved context support the answer? See Ch 9. |
| Task | Metric | Definition |
|---|---|---|
| Speech recognition (ASR) | WER (Word Error Rate) | $(S + D + I) / N$ — substitutions + deletions + insertions over reference words. |
| Speech recognition | CER (Character Error Rate) | Character-level version of WER; better for ideographic scripts. |
| Text-to-speech (TTS) | MOS (Mean Opinion Score) | 1–5 human rating of naturalness; the gold standard. |
| TTS automated | MCD, F0-RMSE | Mel-cepstral distortion; pitch error vs reference. |
| Speaker recognition | EER (Equal Error Rate) | Threshold where false accept rate = false reject rate. |
| Audio source separation | SI-SDR, PESQ, STOI | Signal-distortion ratio; perceptual quality; intelligibility. |