Computer Vision:
A First-Principles Mastery Guide
From Signals to Architectures:
A Complete Derivation-First Curriculum
IMAGE
Style after:
Goodfellow (Deep Learning) · Prince (Understanding
Deep Learning) · Géron (Hands-On ML)
et al.
Complete Curriculum All 7 Phases
March 17, 2026
Preface
This document is a
derivation-rst guide to Computer Vision. Unlike most text-
books that present results and ask you to accept them, this curriculum forces you
to derive every concept from scratch. By the end, you should be able to:
Derive the convolution operation from rst principles of signal processing.
Understand why translation equivariance is the fundamental inductive bias of
CNNs.
Build every major architecture (LeNet through ConvNeXt) from a single motivating failure.
Reason about Vision Transformers and understand when to use them over
CNNs.
Design and debug a complete computer vision pipeline end-to-end.
Learning Philosophy: Every concept follows the strict order:
Intuition
−→ Formalization −→ Mathematics −→ Implementation −→ Limitations −→ Conn
Exercises: Every module ends with deep questions. The answers follow immediately. Do not read the answers before attempting the questions.
1
Contents
Preface
1
I Phase 1: Foundations
9
1
Images as Signals
10
1.1
Intuition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10
1.1.1
Physical Analogy . . . . . . . . . . . . . . . . . . . . . . . . .
10
1.1.2
Signal-Processing Viewpoint . . . . . . . . . . . . . . . . . . .
10
1.1.3
Geometric Viewpoint . . . . . . . . . . . . . . . . . . . . . . .
11
1.2
Formal Denition . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11
1.3
Mathematical Derivation . . . . . . . . . . . . . . . . . . . . . . . . .
11
1.3.1
Image as a Vector Space Element
11
1.3.2
Sampling Theory and the Nyquist Criterion
1.3.3
Image Channels and Colour Spaces
1.3.4
1.4
2
. . . . . . . . . . . . . . . .
. . . . . . . . . .
12
. . . . . . . . . . . . . . .
12
Image Statistics . . . . . . . . . . . . . . . . . . . . . . . . . .
13
Geometric / Information-Theoretic Interpretation
. . . . . . . . . . .
13
1.4.1
Images Live on a Low-Dimensional Manifold . . . . . . . . . .
13
1.4.2
Information Content via Entropy
. . . . . . . . . . . . . . . .
13
1.5
Implementation from Scratch
. . . . . . . . . . . . . . . . . . . . . .
14
1.6
Failure Modes and Limitations . . . . . . . . . . . . . . . . . . . . . .
16
1.7
Connection to the Next Concept . . . . . . . . . . . . . . . . . . . . .
17
1.8
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
17
Linear Algebra of Images
22
2.1
Intuition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
22
2.1.1
Physical Analogy . . . . . . . . . . . . . . . . . . . . . . . . .
22
2.1.2
Why This Matters for Deep Learning . . . . . . . . . . . . . .
22
2.2
Formal Denitions
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
22
2.3
Mathematical Derivation . . . . . . . . . . . . . . . . . . . . . . . . .
22
2.3.1
23
Linear Transformations on Vectorised Images
2
. . . . . . . . .
Contents
3
2.3.2
Rank of an Image . . . . . . . . . . . . . . . . . . . . . . . . .
23
2.3.3
Covariance and PCA of an Image Dataset
. . . . . . . . . . .
23
2.3.4
Norms on Image Spaces
. . . . . . . . . . . . . . . . . . . . .
24
2.4
Geometric Interpretation . . . . . . . . . . . . . . . . . . . . . . . . .
24
2.5
Implementation from Scratch
. . . . . . . . . . . . . . . . . . . . . .
25
2.6
Failure Modes and Limitations . . . . . . . . . . . . . . . . . . . . . .
27
2.7
Connection to the Next Concept . . . . . . . . . . . . . . . . . . . . .
27
2.8
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
28
Convolution An Extremely Deep Dive
30
3.1
Intuition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
30
3.1.1
Physical Analogy: The Impulse Response . . . . . . . . . . . .
30
3.1.2
Signal-Processing Viewpoint . . . . . . . . . . . . . . . . . . .
30
3.1.3
Geometric Viewpoint: Sliding Dot Products
. . . . . . . . . .
31
3.2
Formal Denition . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
31
3.3
Mathematical Derivation . . . . . . . . . . . . . . . . . . . . . . . . .
32
3.4
4
3
3.3.1
Step 1: Deriving Convolution from Linearity and Shift-Invariance 32
3.3.2
Step 2: Extending to 2D . . . . . . . . . . . . . . . . . . . . .
33
3.3.3
Step 3: Convolution Theorem (Frequency Domain)
. . . . . .
33
3.3.4
Step 4: Properties of 2D Convolution . . . . . . . . . . . . . .
34
3.3.5
Step 5: Separability . . . . . . . . . . . . . . . . . . . . . . . .
34
3.3.6
Step 6: Padding and Stride
34
. . . . . . . . . . . . . . . . . . .
Geometric / Information-Theoretic Interpretation
. . . . . . . . . . .
35
3.4.1
Frequency-Selective Filtering . . . . . . . . . . . . . . . . . . .
35
3.4.2
Information Flow in a Convolutional Layer . . . . . . . . . . .
35
3.5
Implementation from Scratch
. . . . . . . . . . . . . . . . . . . . . .
36
3.6
Failure Modes and Limitations . . . . . . . . . . . . . . . . . . . . . .
39
3.7
Connection to the Next Concept . . . . . . . . . . . . . . . . . . . . .
40
3.8
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
40
Translation Equivariance
44
4.1
Intuition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
44
4.2
Formal Denition . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
44
4.3
Mathematical Derivation . . . . . . . . . . . . . . . . . . . . . . . . .
45
4.4
Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
45
4.5
Failure Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
47
4.6
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
47
Contents
5
6
4
Edge Detection and Filters
48
5.1
Intuition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
48
5.2
Formal Denition . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
48
5.3
Mathematical Derivation . . . . . . . . . . . . . . . . . . . . . . . . .
48
5.3.1
Derivative Filters . . . . . . . . . . . . . . . . . . . . . . . . .
48
5.3.2
Canny Edge Detector: A Complete Derivation . . . . . . . . .
49
5.4
Failure Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
51
5.5
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
51
Feature Extraction
53
6.1
Intuition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
53
6.2
HOG: Histogram of Oriented Gradients . . . . . . . . . . . . . . . . .
53
6.3
SIFT: Scale-Invariant Feature Transform
. . . . . . . . . . . . . . . .
54
6.4
Connection to CNNs
. . . . . . . . . . . . . . . . . . . . . . . . . . .
54
6.5
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
54
II Phase 2: Representation Learning
56
7
Why Handcrafted Features Fail
57
7.1
Intuition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
57
7.2
The Semantic Gap
57
7.3
Curse of Dimensionality for Hand-Crafted Features
. . . . . . . . . .
57
7.4
What Deep Learning Provides . . . . . . . . . . . . . . . . . . . . . .
58
7.5
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
58
8
9
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
Perceptron Limitations on Images
60
8.1
Intuition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
60
8.2
Parameter Count Analysis . . . . . . . . . . . . . . . . . . . . . . . .
60
8.3
Why FC Layers Fail on Images: Three Fundamental Problems . . . .
60
8.4
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
61
Spatial Structure and the CNN Idea
62
9.1
Spatial Hierarchy of Visual Concepts
. . . . . . . . . . . . . . . . . .
62
9.2
The CNN Hypothesis . . . . . . . . . . . . . . . . . . . . . . . . . . .
63
9.3
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
63
III Phase 3: CNN Core
65
10 Convolutional Layers Deep Dive
66
10.1 The Full Convolutional Layer
. . . . . . . . . . . . . . . . . . . . . .
66
Contents
5
10.1.1 Depthwise Separable Convolution . . . . . . . . . . . . . . . .
10.2 Backpropagation through Convolution
66
. . . . . . . . . . . . . . . . .
67
10.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
68
11 Receptive Fields
69
11.1 Denition and Growth Rate
. . . . . . . . . . . . . . . . . . . . . . .
69
11.2 Theoretical vs Eective Receptive Field . . . . . . . . . . . . . . . . .
69
11.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
70
12 Parameter Sharing
71
12.1 The Statistical Justication
. . . . . . . . . . . . . . . . . . . . . . .
71
. . . . . . . . . . . . . . . . . . . . . . . . . . .
71
12.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
72
12.2 Parameter Eciency
13 Pooling
73
13.1 Intuition and Purpose
13.2 Types of Pooling
. . . . . . . . . . . . . . . . . . . . . . . . . .
73
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
73
13.3 Backprop through Max Pooling
. . . . . . . . . . . . . . . . . . . . .
74
13.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
74
14 Activation Functions
76
14.1 Necessity of Non-Linearity . . . . . . . . . . . . . . . . . . . . . . . .
76
14.2 Key Activation Functions
. . . . . . . . . . . . . . . . . . . . . . . .
76
14.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
77
IV Phase 4: Architecture Evolution
79
15 LeNet-5 (1998)
80
15.1 Problem Before It . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
80
15.2 Core Insight . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
80
15.3 Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
80
15.4 Key Innovations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
81
15.5 Limitations
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
81
15.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
81
16 AlexNet (2012)
16.1 The Problem
83
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
83
16.2 Core Insight . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
83
16.3 Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
83
16.4 Key Innovations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
83
16.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
84
Contents
6
17 VGGNet (2014)
86
17.1 Core Insight . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
86
17.2 Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
86
17.3 Legacy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
86
17.4 Limitation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
87
17.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
87
18 GoogLeNet / Inception (2014)
88
18.1 Core Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
88
18.2 The Inception Module
. . . . . . . . . . . . . . . . . . . . . . . . . .
88
18.3 Key Insight: Multi-Scale Processing . . . . . . . . . . . . . . . . . . .
88
18.4 GoogLeNet Architecture
. . . . . . . . . . . . . . . . . . . . . . . . .
89
18.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
89
19 ResNet (2015)
90
19.1 The Degradation Problem
. . . . . . . . . . . . . . . . . . . . . . . .
90
19.2 Core Insight: Residual Learning . . . . . . . . . . . . . . . . . . . . .
90
19.3 Why Residual Connections Help Gradient Flow
. . . . . . . . . . . .
90
19.4 The Bottleneck Block . . . . . . . . . . . . . . . . . . . . . . . . . . .
91
19.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
91
20 DenseNet (2017)
93
20.1 Core Insight: Dense Connectivity
. . . . . . . . . . . . . . . . . . . .
93
. . . . . . . . . . . . . . . . . . . . . . . . . .
93
20.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
94
20.2 Growth Rate Analysis
21 EcientNet (2019)
95
21.1 The Scaling Problem
. . . . . . . . . . . . . . . . . . . . . . . . . . .
95
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
95
21.3 MBConv: The Building Block . . . . . . . . . . . . . . . . . . . . . .
95
21.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
96
21.2 Compound Scaling
22 ConvNeXt (2022)
22.1 The Question
97
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
22.2 Key Design Changes
97
. . . . . . . . . . . . . . . . . . . . . . . . . . .
97
22.3 The ConvNeXt Block . . . . . . . . . . . . . . . . . . . . . . . . . . .
97
22.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
98
Contents
7
V Phase 5: Modern Paradigms
99
23 Vision Transformers (ViT)
100
23.1 The Core Idea . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
23.2 Self-Attention in Images
. . . . . . . . . . . . . . . . . . . . . . . . . 100
23.3 The Full ViT Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
23.4 ViT Complexity Analysis . . . . . . . . . . . . . . . . . . . . . . . . . 101
23.5 CNN vs Transformer: The Core Trade-o . . . . . . . . . . . . . . . . 101
23.6 When to Use CNN vs Transformer
. . . . . . . . . . . . . . . . . . . 101
23.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
VI Phase 6: CV Tasks
103
24 Image Classication
104
24.1 Formulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
24.2 Cross-Entropy Loss Derivation . . . . . . . . . . . . . . . . . . . . . . 104
24.3 Label Smoothing
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
24.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
25 Object Detection
106
25.1 Problem Formulation . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
25.2 Key Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
25.3 Two-Stage vs One-Stage Detectors
25.4 Loss Function for Detection
. . . . . . . . . . . . . . . . . . . 106
. . . . . . . . . . . . . . . . . . . . . . . 107
25.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
26 Semantic Segmentation
109
26.1 Problem Formulation . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
26.2 Fully Convolutional Networks (FCN)
. . . . . . . . . . . . . . . . . . 109
26.3 U-Net Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
26.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
VII Phase 7: The Complete CV Pipeline
111
27 Data: Acquisition, Preprocessing, and Augmentation
112
27.1 The Data Flywheel . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
27.2 Preprocessing Pipeline
. . . . . . . . . . . . . . . . . . . . . . . . . . 112
27.3 Data Augmentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
27.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
Contents
8
28 Training: Optimisation and Regularisation
115
28.1 The Optimisation Problem . . . . . . . . . . . . . . . . . . . . . . . . 115
28.2 Stochastic Gradient Descent . . . . . . . . . . . . . . . . . . . . . . . 115
28.3 Learning Rate Schedules . . . . . . . . . . . . . . . . . . . . . . . . . 116
28.4 Batch Normalisation
. . . . . . . . . . . . . . . . . . . . . . . . . . . 116
28.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
29 Evaluation, Debugging, and Deployment
29.1 Evaluation Metrics
118
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
29.2 The Debugging Framework . . . . . . . . . . . . . . . . . . . . . . . . 119
29.3 Transfer Learning Decision Framework
29.4 Deployment Considerations
. . . . . . . . . . . . . . . . . 119
. . . . . . . . . . . . . . . . . . . . . . . 119
29.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
30 Architectural Decision Framework
30.1 The Full Decision Tree
30.2 Final Exercises
Closing Remarks
122
. . . . . . . . . . . . . . . . . . . . . . . . . . 122
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
125
Part I
Phase 1: Foundations
9
Chapter 1
Images as Signals
1.1 Intuition
1.1.1 Physical Analogy
Think of sunlight hitting a scene. Photons bounce o surfaces and enter your eye
(or a camera sensor). Each photon carries energy proportional to its frequency. The
sensor at each spatial location integrates incoming energy over a small time window,
producing a single scalar value: the intensity at that pixel.
Key Insight:
An image is nothing more than a
function that maps a 2D spatial location to
a measurement of physical energy. Before thinking about pixels or RGB,
think about continuous physical elds that are then sampled.
1.1.2 Signal-Processing Viewpoint
In signal processing, a signal is any quantity that varies with an independent variable. Audio is a 1D signal: amplitude varies with time. An image is a 2D signal:
intensity (or colour) varies with two spatial coordinates (x, y).
The key questions in signal processing are:
1. What frequencies are present in the signal? (spectral content)
2. How do we sample it without losing information? (Nyquist theory)
3. How do we lter it to extract what we care about?
All three questions will recur throughout this entire curriculum.
10
1.2.
Formal Denition
11
1.1.3 Geometric Viewpoint
An image of size H × W can be vectorised into a point in R
of images is a point
H×W
.
A dataset
cloud in a very high-dimensional space. The entire eld of
computer vision can be viewed as learning to navigate this spacending structure,
invariances, and meaningful directions.
1.2 Formal Denition
Denition: Continuous Image
A continuous grayscale image is a function
f : R2 → R,
(x, y) 7→ f (x, y)
where f (x, y) represents the light intensity at spatial location (x, y).
For a
colour image with C channels:
f : R2 → RC ,
(x, y) 7→ f1 (x, y), f2 (x, y), . . . , fC (x, y) .
Denition: Discrete Image
A discrete image is obtained by sampling f on a regular grid:
I[m, n] = f (m ∆x, n ∆y),
m ∈ {0, . . . , H − 1}, n ∈ {0, . . . , W − 1}
where ∆x, ∆y are the sampling intervals (pixel pitch).
1.3 Mathematical Derivation
1.3.1 Image as a Vector Space Element
Consider the space of all H ×W images. We can add two images pixel-wise, and scale
an image by a scalar. This makes the set of all images a vector space V ∼
= RHW .
The inner product between two images I1 , I2 is
⟨I1 , I2 ⟩ =
H−1
−1
XW
X
I1 [m, n] · I2 [m, n].
(1.1)
m=0 n=0
This inner product has a profound consequence: it measures similarity between
images. When ⟨I1 , I2 ⟩ = 0, the two images are orthogonal they share no common
1.3.
Mathematical Derivation
12
energy in any pixel.
1.3.2 Sampling Theory and the Nyquist Criterion
The continuous image f (x, y) must be sampled onto a discrete grid. The key result
from Fourier analysis is:
Theorem: Nyquist-Shannon Sampling Theorem
If the continuous image f (x, y) contains no frequency components above fmax
cycles per unit length, then the image is
samples taken at intervals
∆x ≤
completely described by discrete
1
.
2fmax
Sampling below this rate causes aliasing: high-frequency content masquerades as low-frequency artefacts.
Proof sketch.
Let fˆ(u, v) denote the 2D Fourier transform of f :
fˆ(u, v) =
Z ∞Z ∞
−∞
f (x, y) e−2πi(ux+vy) dx dy.
(1.2)
−∞
Sampling f at intervals ∆x in x and ∆y in y is equivalent in the frequency domain
to replication of fˆ at intervals 1/∆x and 1/∆y . If fˆ(u, v) = 0 for |u| >
1
and
2∆x
1
|v| > 2∆y
, the replicas do not overlap and f can be recovered exactly by low-pass
ltering. If this condition fails, replicas overlap, causing aliasing.
1.3.3 Image Channels and Colour Spaces
A colour image is a stack of C single-channel images. For RGB, C = 3:
R[m, n]
I[m, n] = G[m, n] ∈ R3 .
B[m, n]
(1.3)
H×W ×C
The full image is a rank-3 tensor I ∈ R
.
Why other colour spaces matter:
HSV: separates hue (colour identity) from saturation and value (brightness).
Useful when you want colour-invariant features.
Lab: a perceptually uniform space. Equal Euclidean distance in Lab corresponds to equal perceived colour dierence.
Important for any task where
similar colour should mean similar to a human.
1.4.
Geometric / Information-Theoretic Interpretation
13
YCbCr: separates luminance Y from chrominance. JPEG compression works
in this space because the human eye is more sensitive to luminance than colour.
1.3.4 Image Statistics
Pixel intensity distribution.
The histogram h[k] counts how many pixels have
intensity k :
h[k] =
X 1 I[m, n] = k ,
k ∈ {0, . . . , 255}.
(1.4)
m,n
Spatial autocorrelation.
Natural images are highly spatially correlated: nearby
pixels tend to have similar values. Formally, the autocorrelation function is
RII [∆m, ∆n] =
X
I[m, n] · I[m + ∆m, n + ∆n].
(1.5)
m,n
For natural images, RII is strongly peaked near (0, 0) and decays smoothlya fundamental statistical regularity that CNNs implicitly exploit.
1.4 Geometric / Information-Theoretic Interpretation
1.4.1 Images Live on a Low-Dimensional Manifold
Although an H × W image lives in R
HW
65536
(e.g., a 256 × 256 image in R
), natural
images occupy a tiny, curved subspace called the natural image manifold. Most
65536
points in R
look like pure noise. This manifold structure is the geometric reason
why deep learning works: neural networks learn to parameterise this manifold.
1.4.2 Information Content via Entropy
The Shannon entropy of an image quanties how much information it carries:
H=−
255
X
pk log2 pk
bits per pixel,
(1.6)
k=0
where pk = h[k]/(HW ) is the empirical probability of intensity k .
A uniform noise image has maximum entropy (H = 8 bits for an 8-bit image).
A black image has zero entropy. Real images typically have H ≈ 57 bits per pixel
before compression.
1.5.
Implementation from Scratch
1.5 Implementation from Scratch
1
2
import numpy as np
import matplotlib . pyplot as plt
3
4
5
6
7
8
9
10
11
12
13
14
# ------------------------------------------------------# 1. Load and interpret an image as a 2 D array ( signal )
# ------------------------------------------------------def load_image_as_signal ( path ) :
"""
Reads an image file and returns a numpy array .
Returns : I of shape (H , W) for grayscale or (H , W , C) for
colour .
"""
from PIL import Image
img = Image . open ( path )
return np . array ( img , dtype = np . float32 ) / 255.0
#
normalise to [0 ,1]
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# ------------------------------------------------------# 2. Compute the 2D Fourier Transform ( spectral content )
# ------------------------------------------------------def image_spectrum (I) :
"""
Computes the log - magnitude of the 2D DFT of a grayscale
image .
The DC component is shifted to the centre for visual
clarity .
"""
F = np . fft . fft2 ( I)
# 2 D DFT
F_shifted = np . fft . fftshift (F )
# shift DC to centre
magnitude = np . abs ( F_shifted )
log_magnitude = np . log1p ( magnitude )
# log scale for
visualisation
return log_magnitude
29
30
31
32
33
34
# ------------------------------------------------------# 3. Pixel histogram ( empirical intensity distribution )
# ------------------------------------------------------def pixel_histogram (I , num_bins =256) :
"""
14
1.5.
35
36
37
38
39
40
41
42
Implementation from Scratch
Computes histogram of pixel intensities .
Works on normalised [0 ,1] images .
"""
bins = np . linspace (0.0 , 1.0 , num_bins + 1)
hist , edges = np . histogram ( I. ravel () , bins = bins )
# Normalise to get probability mass function
pmf = hist / hist . sum ()
return pmf , edges
43
44
45
46
47
48
49
50
51
52
# ------------------------------------------------------# 4. Shannon entropy of the image
# ------------------------------------------------------def image_entropy (I , num_bins =256) :
pmf , _ = pixel_histogram (I , num_bins )
# Avoid log (0)
pmf = pmf [ pmf > 0]
entropy = - np . sum ( pmf * np . log2 ( pmf ))
return entropy
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# ------------------------------------------------------# 5. Spatial autocorrelation ( cropped to small window )
# ------------------------------------------------------def spatial_autocorrelation (I , max_lag =20) :
"""
Computes R [dm , dn ] for lags in [ - max_lag , max_lag ].
Uses FFT for efficiency : R = IFFT (| FFT (I ) |^2) .
"""
F = np . fft . fft2 ( I)
power_spectrum = np . abs (F ) ** 2
R_full = np . real ( np . fft . ifft2 ( power_spectrum ))
R_shifted = np . fft . fftshift ( R_full )
H , W = I. shape
cx , cy = H // 2 , W // 2
R_crop = R_shifted [ cx - max_lag : cx + max_lag +1 ,
cy - max_lag : cy + max_lag +1]
# Normalise by zero - lag value
R_crop /= R_crop [ max_lag , max_lag ]
return R_crop
73
74
75
# ------------------------------------------------------# 6. Demonstration
15
1.6.
76
77
78
79
80
81
82
83
Failure Modes and Limitations
16
# ------------------------------------------------------def rgb_to_grayscale ( I_rgb ) :
"""
Standard luminance - weighted conversion :
Y = 0.2989 R + 0.5870 G + 0.1140 B
"""
weights = np . array ([0.2989 , 0.5870 , 0.1140])
return I_rgb @ weights
# shape (H , W )
84
85
86
87
88
89
90
91
92
#
#
#
#
#
Example usage ( requires an image file ) :
I_rgb = load_image_as_signal (" sample . jpg ")
I_gray = rgb_to_grayscale ( I_rgb )
print (f " Image shape : { I_gray . shape }")
print (f " Value range : [{ I_gray . min () :.3 f }, { I_gray . max () :.3 f
}]")
# print (f " Entropy
: { image_entropy ( I_gray ) :.3 f } bits / pixel
")
# spectrum = image_spectrum ( I_gray )
# autocorr = spatial_autocorrelation ( I_gray )
Listing 1.1: Image as a Signal From Scratch in NumPy
1.6 Failure Modes and Limitations
1. Aliasing: If an image is captured with a sensor whose pixel pitch violates the
Nyquist criterion, high-frequency textures will produce Moiré patterns. This
is why smartphone cameras use optical low-pass lters in front of the sensor.
2. Photometric variation: The same scene under dierent lighting gives different pixel values. Raw pixel values are poor features for recognition because
they change with the light source, not just the object.
3. Geometric variation: A small rotation or translation changes most pixel
values, yet the scene is the same. This motivates the need for
invariant rep-
resentations.
4. High dimensionality: Even a modest 224 × 224 RGB image is a vector in
R150528 . Working directly in pixel space is computationally and statistically
hopeless for anything beyond trivial tasks.
1.7.
Connection to the Next Concept
17
1.7 Connection to the Next Concept
We now understand images as 2D signals sampled onto grids.
question is:
The natural next
what algebraic operations can we perform on these signals? The image
is a matrix (or tensor), and the operations we care about ltering, transforming,
projecting are fundamentally linear algebra operations. Chapter 2 makes this
precise.
1.8 Exercises
Exercise 1.1 Sampling and Aliasing
An image of a sinusoidal pattern with spatial frequency f0 = 80 cycles per
image-width is sampled onto a 100 × 100 pixel grid.
1. What does the Nyquist criterion say about the minimum sampling rate
required?
2. Will the 100 × 100 grid capture this pattern faithfully? If not, what will
you observe?
3. Write the mathematical expression for the aliased frequency that will
appear.
Answer: Answer 1.1
(a) The Nyquist criterion requires sampling at more than twice the highest
frequency:
fs > 2f0 = 160 samples per image-width.
A 100 × 100 grid gives only fs = 100 samples per image-width.
(b) Nothe grid violates Nyquist. The pattern cannot be faithfully captured.
The observer will see a lower-frequency interference pattern (Moiré eect).
(c) The aliased frequency is:
falias = |f0 − k · fs |
for the integer k such that |f0 − k · fs | ≤ fs /2.
= 100 and f0 = 80: k = 1 gives |80 − 100| = 20.
frequency is 20 cycles per image-width.
With fs
The observed
1.8.
Exercises
18
Exercise 1.2 Image as a Vector Space
Let I1 and I2 be two 4 × 4 grayscale images (represented as 4 × 4 matrices of
pixel values in [0, 1]).
1. Prove that the set of all 4×4 images under pixel-wise addition and scalar
multiplication forms a vector space.
2. Dene a valid inner product on this space and verify the three axioms
(symmetry, linearity, positive-deniteness).
3. What does ⟨I1 , I2 ⟩ = 0 mean visually/physically?
Answer: Answer 1.2
(a) The space R4×4 is isomorphic to R16 . For any two images I1 , I2 ∈ R4×4
and scalars α, β ∈ R:
Closure: (αI1 + βI2 )[m, n] = αI1 [m, n] + βI2 [m, n] ∈ R4×4 . ✓
Zero element: The all-zero image 0[m, n] = 0 satises I + 0 = I . ✓
All remaining vector space axioms follow from the eld axioms of R. ✓
(b) Dene ⟨I1 , I2 ⟩ =
P
m,n I1 [m, n]I2 [m, n].
Symmetry: ⟨I1 , I2 ⟩ =
P
m,n I1 [m, n]I2 [m, n] = ⟨I2 , I1 ⟩. ✓
Linearity: ⟨αI1 + βI3 , I2 ⟩ = α⟨I1 , I2 ⟩ + β⟨I3 , I2 ⟩ follows from distributivity of multiplication over addition. ✓
Positive-denite: ⟨I, I⟩ =
P
m,n I[m, n]
2
≥ 0, with equality i I = 0. ✓
(c) ⟨I1 , I2 ⟩ = 0 means the images are orthogonal : they have zero correlation.
Wherever one image is bright, the other tends to be dark (and vice versa),
perfectly cancelling out on average. They carry completely non-overlapping
informationthey are the image equivalent of two perpendicular axes.
1.8.
Exercises
19
Exercise 1.3 Shannon Entropy
1. A completely uniform image (all pixels the same value) has what entropy?
2. A pure noise image (each pixel independently uniformly distributed over
{0, . . . , 255}) has what entropy?
3. Natural images typically have entropy ≈ 6 bits/pixel while their theoretical maximum is 8 bits/pixel. What does this tell you about natural
image statistics?
4. Show that image compression is possible precisely because natural images have entropy below maximum.
Answer: Answer 1.3
(a) A uniform image has pk = 1 for one intensity k and pj = 0 for all others.
Thus H = −1 · log2 1 = 0 bits/pixel.
(b) For uniform distribution over 256 values, pk = 1/256 for all k :
255
X
1
1
H=−
log2
= log2 256 = 8 bits/pixel.
256
256
k=0
(c) Natural image entropy ≈ 6 bits/pixel means:
the pixel intensity distri-
bution is not uniform. Certain intensity values appear far more often than
others (bright sky pixels, shadow pixels), and more importantly, pixels are
not independent adjacent pixels are highly correlated. The true entropy of
a pixel given its neighbours is much lower than 6 bits.
(d) Shannon's source coding theorem states that the minimum average codeword length required to represent symbols losslessly is equal to the entropy.
If H < 8 bits/pixel, then we can encode the image using fewer than 8 bits per
pixel on average, achieving compression. JPEG, PNG, and WebP all exploit
exactly this statistical redundancy.
1.8.
Exercises
20
Exercise 1.4 Implementation Task
From scratch in NumPy (no PIL or cv2 for processing):
1. Create a synthetic 128 × 128 image of a 2D sinusoidal grating with
frequency f = 10 cycles/image.
2. Subsample it to 15 × 15 to simulate undersampling. What do you observe?
3. Compute and plot the 2D DFT magnitude spectrum of both the original and subsampled images.
frequency domain.
Describe what aliasing looks like in the
1.8.
Exercises
21
Answer: Answer 1.4
1
import numpy as np
2
3
4
5
6
7
8
# ( a) Create 128 x128 sinusoidal grating
N_orig = 128
x = np . linspace (0 , 1 , N_orig , endpoint = False )
xx , yy = np . meshgrid (x , x)
f = 10.0
# 10 cycles across the image
I_orig = 0.5 * (1 + np . sin (2 * np . pi * f * xx ))
horizontal grating
#
9
10
11
12
13
14
# ( b) Subsample to 15 x15 ( stride = 128//15
8)
stride = N_orig // 15
I_sub = I_orig [:: stride , :: stride ][:15 , :15]
# Observed : a much lower - frequency ( or zero - frequency )
pattern
# because f =10 > (15/2) =7.5
aliased !
15
16
17
18
19
# ( c) 2 D DFT magnitude spectra
def log_spectrum (I ):
F = np . fft . fftshift ( np . fft . fft2 ( I))
return np . log1p ( np . abs (F ))
20
21
22
spec_orig = log_spectrum ( I_orig )
spec_sub = log_spectrum ( I_sub )
15| = 5
# peak at u =+/ -10
# peak appears at |10 # -> aliased to f =5
cycles / image
23
24
25
26
27
28
print ( " Original image shape :" , I_orig . shape )
print ( " Subsampled image shape : " , I_sub . shape )
print ( " Aliased frequency
:" , abs (f - 15) , " cycles /
image ")
# Output : Aliased frequency : 5.0 cycles / image
Listing 1.2: Aliasing Demonstration
Explanation: In the spectrum of the original, we see two peaks at ±10 cycles
(horizontal frequency axis). After subsampling to 15 samples/image, the new
Nyquist limit is 7.5 cycles/image. The frequency 10 folds back to |10−15| = 5
cycles/image. In the subsampled spectrum, the peaks appear at ±5 that
is the aliased artefact.
Chapter 2
Linear Algebra of Images
2.1 Intuition
2.1.1 Physical Analogy
Consider a photographer adjusting contrast: every pixel value is multiplied by the
same scalar.
That is a
oset is a translation.
2D coordinates.
linear transformation.
Adding a uniform brightness
Rotating an image is a matrix
multiplication on the
Every classical image operation is, at its core, a linear algebra
operation.
2.1.2 Why This Matters for Deep Learning
The entire machinery of neural networks is linear algebra (matrix multiplications,
convolutions, dot products) punctuated by non-linearities.
To understand why
CNNs work, you must rst be uent in the linear algebra of image tensors.
2.2 Formal Denitions
Denition: Image Tensor
H×W
A single grayscale image is a matrix I ∈ R
.
A colour image is a rank-3 tensor I ∈ R
H×W ×C
.
N ×C×H×W
A mini-batch of N images is a rank-4 tensor B ∈ R
(PyTorch conN ×H×W ×C
vention) or R
(TensorFlow convention).
2.3 Mathematical Derivation
22
2.3.
Mathematical Derivation
23
2.3.1 Linear Transformations on Vectorised Images
Vectorise I into i
= vec(I) ∈ RHW .
Any linear operation on the image can be
written as:
o = A i,
′
′
A ∈ R(H W )×(HW ) .
(2.1)
′
′
The matrix A has (H W ) × (HW ) entries. For a 224 × 224 input image, HW
=
50176. The weight matrix A for a fully connected layer mapping to a 1000-dimensional
output has 50176 × 1000 ≈ 50 million parameters from the rst layer alone. This is
the parameter explosion that motivates weight sharing.
2.3.2 Rank of an Image
The
rank of the image matrix I measures how many independent textures it
contains. Via the SVD:
⊤
I = UΣV =
r
X
σk uk vk⊤ ,
(2.2)
k=1
where r = rank(I) ≤ min(H, W ), σ1 ≥ σ2 ≥ · · · ≥ σr > 0 are the singular values,
and uk , vk are the left/right singular vectors.
Key Insight: Low-Rank Approximation
Because natural images are spatially smooth and structured, their singular
values decay rapidly: most of the energy
2
k σk is concentrated in the rst
P
few singular values. This is why JPEG compression works it discards the
high-index singular-value components.
Keeping only the top k singular values gives the best rank-k approximation
in the Frobenius norm:
Ik =
k
X
σj uj vj⊤ .
j=1
2.3.3 Covariance and PCA of an Image Dataset
N
HW
N ×HW
Given N images vectorised as {in }n=1 ⊂ R
, the data matrix is X ∈ R
.
The sample covariance matrix is
Σ=
1
(X − X̄)⊤ (X − X̄) ∈ RHW ×HW .
N −1
The eigenvectors of Σ are the principal
(2.3)
components (PCs). When applied to
face images, the PCs are called Eigenfaces each PC is an image that captures
a mode of variation in the dataset.
2.4.
Geometric Interpretation
24
Why PCA tells us about visual structure.
The covariance structure of Σ
encodes which pairs of pixels tend to vary together. For a natural image dataset, Σ
has Toeplitz structure:
Σij depends mainly on the distance between pixel i and
pixel j , not their absolute positions. This translation invariance in the covariance
matrix is the statistical signal that motivates weight sharing in CNNs.
2.3.4 Norms on Image Spaces
Dierent norms capture dierent notions of image similarity:
∥I∥F =
sX
I[m, n]2
2
(Frobenius / L norm mean energy)
(2.4)
1
(L norm sparsity-promoting)
(2.5)
∞
(L
norm worst-case pixel)
(2.6)
(nuclear norm rank proxy)
(2.7)
m,n
∥I∥1 =
X
|I[m, n]|
m,n
∥I∥∞ = max |I[m, n]|
m,n
X
σk (I)
∥I∥∗ =
k
2
The Frobenius norm (L ) is by far the most common in deep learning (e.g., MSE
1
loss). The L norm appears in robust losses (MAE). The nuclear norm is used in
matrix completion problems.
2.4 Geometric Interpretation
Images as points on a manifold.
HW
The N × dataset forms a point cloud in R
.
The span of the top k PCs is the best-tting k -dimensional linear
subspace (a
hyperplane through the origin after mean-centering). Deep networks learn a nonlinear folded version of this structure.
Transformation geometry.
Geometric image transformations (rotation by
θ,
scale by s, translation by (tx , ty )) form a Lie group under composition. Specically:
Translations form a group (R2 , +).
Rotations form SO(2).
Combined, they form the Special Euclidean group SE(2).
Designing vision systems that are invariant or equivariant to elements of this
group is a central theme.
2.5.
Implementation from Scratch
2.5 Implementation from Scratch
1
import numpy as np
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# ------------------------------------------------------# 1. SVD - based image compression
# ------------------------------------------------------def svd_compress (I , k) :
"""
Compress image I using rank -k SVD approximation .
Returns the approximated image and compression ratio .
"""
U , S , Vt = np . linalg . svd (I , full_matrices = False )
# Keep only top -k components
U_k = U [: , :k ]
# (H , k)
S_k = np . diag (S [: k ])
# (k , k)
Vt_k = Vt [:k , :]
# (k , W)
I_approx = U_k @ S_k @ Vt_k
# (H , W )
# Compression ratio : original = H* W floats ,
# stored = H* k + k + k *W = k *( H+W +1) floats
original_size
= I. shape [0] * I . shape [1]
compressed_size = k * (I . shape [0] + I. shape [1] + 1)
ratio = original_size / compressed_size
return np . clip ( I_approx , 0, 1) , ratio
23
24
25
26
27
28
29
30
31
32
33
34
# ------------------------------------------------------# 2. Energy retained by top -k singular values
# ------------------------------------------------------def energy_retained (I , k) :
"""
Fraction of total Frobenius - norm energy in top - k SVs .
"""
_ , S , _ = np . linalg . svd (I , full_matrices = False )
total_energy = np . sum (S **2)
top_k_energy = np . sum (S [: k ]**2)
return top_k_energy / total_energy
35
36
37
38
39
# ------------------------------------------------------# 3. PCA on a small image dataset
# ------------------------------------------------------def image_pca ( images , k):
25
2.5.
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
Implementation from Scratch
26
"""
images : ndarray of shape (N , H , W)
N grayscale images
k: number of principal components to keep
Returns : mean_image , components (k , H* W) , projected (N , k)
"""
N , H , W = images . shape
X = images . reshape (N , H * W ). astype ( np . float32 )
# (N , HW
)
# Mean - centre
mean = X. mean ( axis =0 , keepdims = True )
# (1 ,
HW )
X_c = X - mean
# (N ,
HW )
# Covariance via thin SVD of X_c ( more stable than
# computing the full ( HW x HW ) covariance matrix )
# X_c = U * S * Vt = > cov = (1/( N -1) ) * Vt ^T * S ^2 * Vt
U , S , Vt = np . linalg . svd ( X_c , full_matrices = False )
components = Vt [: k]
# (k ,
HW )
projected = X_c @ components .T
# (N , k
)
return mean . reshape (H , W) , components . reshape (k , H , W) ,
projected
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# ------------------------------------------------------# 4. Covariance structure demo
# ------------------------------------------------------def covariance_distance_structure (H =16 , W =16) :
"""
Demonstrates that natural image covariance depends only
on distance between pixels ( Toeplitz structure ) .
We simulate this with a synthetic smooth covariance model .
"""
coords = np . array ([( m , n)
for m in range (H )
for n in range (W )], dtype = float )
# Squared - exponential covariance : cov (i ,j) = exp ( -|| xi - xj
||^2/(2* l ^2) )
length_scale = 3.0
diff = coords [: , None , :] - coords [ None , :, :]
# ( HW , HW
, 2)
2.6.
73
74
75
Failure Modes and Limitations
dist_sq = np . sum ( diff **2 , axis = -1)
HW )
cov = np . exp (- dist_sq / (2 * length_scale **2) )
HW )
return cov
27
# ( HW ,
# ( HW ,
76
77
78
79
80
81
82
83
# Demo
I_rand = np . random . rand (64 , 64)
for k in [1 , 5 , 20 , 50]:
approx , ratio = svd_compress ( I_rand , k)
e = energy_retained ( I_rand , k )
print (f "k ={ k :3 d }: compression ratio ={ ratio :.1 f}x , "
f" energy retained ={ e :.3 f }")
Listing 2.1: SVD Image Compression and PCA on Images
2.6 Failure Modes and Limitations
1. Curse of dimensionality: PCA on images requires storing a covariance ma2
10
trix of size (HW ) . For 224 × 224 images, this is ≈ 10
entries completely
intractable. In practice, PCA is only applied to small patches or feature vectors.
2. Linear representations are insucient: PCA nds the best linear subspace. Natural images live on a curved, non-linear manifold. Two images of
the same face under dierent lighting are not well-related by a linear transformation in pixel space.
3. Orthogonality assumption: SVD/PCA assumes components should be orthogonal. Real visual features (e.g., edges, textures, objects) are not necessarily orthogonal. ICA and sparse coding relax this.
2.7 Connection to the Next Concept
We have seen that any linear operation on a vectorised image is a matrix multiplication, and that the dominant operation in neural networks is of this form. However,
2
the naive matrix multiplication has O((HW ) ) parameters completely impractical. The solution is the convolution operation, which enforces locality and weight
sharing. This is the most important concept in all of computer vision. Chapter 3
derives it from rst principles.
2.8.
Exercises
28
2.8 Exercises
Exercise 2.1 SVD and Image Compression
Let I be a 200 × 200 grayscale image with singular values σ1
= 100, σ2 =
50, σ3 = 10, . . . (rapidly decaying).
1. What is the minimum rank-k approximation that retains at least 95%
of the Frobenius norm squared?
2. If the true rank is 200, what is the compression ratio when using rank-5?
3. Why does the Frobenius norm squared relate to visual quality (PSNR)?
Answer: Answer 2.1
P 2
PK 2
2
≥
0.95
.
We
need
σ
σ
k
k
k σk . With σ1 =
k=1
k
100, σ2 = 50, their squared sum is 10000+2500 = 12500. If total is, say, 13100
(≈ rapidly decaying tail), then k = 2 already gives 12500/13100 ≈ 95.4%. The
exact k depends on the full spectrum; the principle is to accumulate until the
(a) Total energy ∥I∥2F =
P
cumulative energy fraction crosses 0.95.
(b) For H = W = 200, rank-5 approximation stores 5 × (200 + 200 + 1) =
2005 values vs. 200 × 200 = 40000 original values. Compression ratio =
40000/2005 ≈ 19.95×.
2
(c) PSNR is dened as 10 log10 (peak /MSE) where MSE = ∥I − Î∥2F /(HW ).
qP
2
The Frobenius norm of the residual I−Ik equals
j>k σj , so minimising this
directly maximises PSNR. The Eckart-Young theorem guarantees the rank-k
SVD minimises the Frobenius-norm residual.
Exercise 2.2 Covariance and Weight Sharing
The covariance matrix Σ of a natural image dataset has
Toeplitz structure :
Σ(m1 ,n1 ),(m2 ,n2 ) ≈ g(m1 − m2 , n1 − n2 ) for some function g .
1. What does Toeplitz structure say about the relationship between pairs
of pixels?
2. How does this Toeplitz structure motivate convolutional (weight-shared)
architectures?
3. If Σ were not Toeplitz say, the top-left corner of images always had
dierent statistics from the bottom-right what would this imply for
architecture design?
2.8.
Exercises
29
Answer: Answer 2.2
(a) Toeplitz structure means the statistical relationship between two pixels
depends only on their
relative displacement, not their absolute positions. A
pixel at (10, 10) and its right neighbour at (10, 11) have the same correlation as
a pixel at (50, 50) and its neighbour at (50, 51). This is spatial stationarity
the statistics of the image are the same everywhere.
(b) If correlations are the same everywhere (stationary), then the optimal
linear lter for extracting any feature is the same at every location. There is
no reason to use dierent weights at dierent positions. This is exactly what
convolutions do: they apply the
same kernel everywhere. Weight sharing is
not a heuristic it is the statistically optimal thing to do when the data
distribution is spatially stationary.
(c) If statistics varied across positions (non-stationary), then dierent regions
of the image would require dierent lters. Architecturally, this would favour
locally connected (but not weight-shared) layers, sometimes called tiled convolutions. Some specialised architectures (e.g., for satellite imagery with xed
spatial semantics) do incorporate position-dependent processing.
Chapter 3
Convolution An Extremely Deep
Dive
3.1 Intuition
3.1.1 Physical Analogy: The Impulse Response
Imagine dropping a stone into a still pond. The stone is an impulse at position
(x0 , y0 ).
The resulting ripples describe the pond's impulse
response: how the
medium responds to a unit stimulus.
If you drop many stones at dierent positions simultaneously, the total water
height at any point is the sum of the ripples from each stone because water is
a linear medium. This superposition principle is exactly convolution: the output is
the sum of shifted, scaled impulse responses.
3.1.2 Signal-Processing Viewpoint
A linear, shift-invariant (LSI) system is one that:
Linear: If input x1 gives output y1 and x2 gives y2 , then αx1 + βx2 gives
αy1 + βy2 .
Shift-invariant: If x(t) gives y(t), then x(t − τ ) gives y(t − τ ).
30
3.2.
Formal Denition
31
Key Insight: The Fundamental Theorem of LSI Systems
Any LSI system is
completely characterised by its impulse response h. The
output for any input is the convolution of the input with h:
y = x ∗ h.
This is not an approximation it is exact, given linearity and shift-invariance.
3.1.3 Geometric Viewpoint: Sliding Dot Products
Convolution computes a dot product between the kernel and every local patch of the
image. Each output pixel is the inner product of the kernel with the image neighbourhood centred at that pixel.
High activation = high similarity between
the patch and the kernel.
This means: if the kernel is an edge detector, high activations occur wherever
the image looks like an edge. If the kernel is a template of a face, high activations
occur wherever the image looks like that face (though in practice we use learned,
hierarchical features, not raw face templates).
3.2 Formal Denition
Denition: Continuous 2D Convolution
2
For continuous functions f, g : R → R:
Z ∞Z ∞
(f ∗ g)(x, y) =
f (τ1 , τ2 ) g(x − τ1 , y − τ2 ) dτ1 dτ2 .
−∞
(3.1)
−∞
Denition: Discrete 2D Convolution
For discrete signals f [m, n] and kernel g[m, n]:
(f ∗ g)[m, n] =
∞
X
∞
X
k1 =−∞ k2 =−∞
f [k1 , k2 ] g[m − k1 , n − k2 ].
(3.2)
3.3.
Mathematical Derivation
32
Denition: Cross-Correlation (used in CNNs)
What deep learning frameworks call convolution
is technically
cross-
correlation:
(f ⋆ g)[m, n] =
XX
k1
f [m + k1 , n + k2 ] g[k1 , k2 ].
(3.3)
k2
The dierence from true convolution is that cross-correlation
does not ip the
kernel. Since kernels are learned, the ip is absorbed into the learned weights,
so the two are functionally equivalent for neural networks.
3.3 Mathematical Derivation
3.3.1 Step 1: Deriving Convolution from Linearity and ShiftInvariance
Let T be an LSI system. We want to nd the most general form of T .
Step 1a: Sifting property of the delta function.
be written as:
∞
X
x[n] =
Any discrete signal x[n] can
x[k] δ[n − k]
(3.4)
k=−∞
where δ[n] = 1 if n = 0 and 0 otherwise.
Step 1b: Apply linearity.
y[n] = T {x[n]} = T
By linearity of T :
(
X
)
x[k] δ[n − k]
k
=
X
x[k] T {δ[n − k]}.
(3.5)
k
Step 1c: Apply shift-invariance.
Let h[n] = T {δ[n]} be the impulse response.
By shift-invariance, T {δ[n − k]} = h[n − k]. Substituting:
y[n] =
X
x[k] h[n − k] = (x ∗ h)[n].
(3.6)
k
The derivation is complete. We have proven from rst principles that any LSI
system is a convolution. This is not a coincidence it is a mathematical inevitability.
3.3.
Mathematical Derivation
33
3.3.2 Step 2: Extending to 2D
The exact same derivation holds in 2D. Any 2D LSI system T satises:
y[m, n] =
XX
k1
x[k1 , k2 ] h[m − k1 , n − k2 ].
(3.7)
k2
3.3.3 Step 3: Convolution Theorem (Frequency Domain)
Theorem 3.1 (Convolution Theorem). Convolution in the spatial domain corre-
sponds to pointwise multiplication in the frequency domain:
F{f ∗ g}(u, v) = fˆ(u, v) · ĝ(u, v).
(3.8)
Proof.
Z Z
(f ∗ g)(x, y) e−2πi(ux+vy) dx dy
(3.9)
Z Z Z Z
=
f (τ1 , τ2 ) g(x − τ1 , y − τ2 ) dτ1 dτ2 e−2πi(ux+vy) dx dy
F{f ∗ g}(u, v) =
(3.10)
Z Z
Z Z
=
f (τ1 , τ2 )
g(x − τ1 , y − τ2 ) e−2πi(ux+vy) dx dy dτ1 dτ2 .
(3.11)
Substitute x
′
= x − τ1 , y ′ = y − τ2 in the inner integral:
Z Z
=
f (τ1 , τ2 ) e
−2πi(uτ1 +vτ2 )
Z Z
Practical consequence.
′
−2πi(ux′ +vy ′ )
g(x , y ) e
|
= fˆ(u, v) · ĝ(u, v).
′
{z
ĝ(u,v)
′
dx dy
′
dτ1 dτ2
(3.12)
}
□
(3.13)
Computing a convolution with a large kernel directly
2
) for a K × K kernel. Using the Convolution Theorem (FFT-based
convolution), it costs O(HW log(HW )), which is faster for large kernels. This is
is O(HW K
why modern implementations use FFT convolutions for large kernels.
3.3.
Mathematical Derivation
34
3.3.4 Step 4: Properties of 2D Convolution
f ∗g =g∗f
(3.14)
Associativity:
(f ∗ g) ∗ h = f ∗ (g ∗ h)
(3.15)
Distributivity:
f ∗ (g + h) = f ∗ g + f ∗ h
(3.16)
if y = f ∗ h, then y(· − τ ) = f (· − τ ) ∗ h
(3.17)
∂f
∂g
∂
(f ∗ g) =
∗g =f ∗
∂x
∂x
∂x
(3.18)
Commutativity:
Shift:
Derivative:
The derivative property is critical: applying an edge-detection kernel is the
same as dierentiating the image. This is not a coincidence derivative lters
are exactly the impulse responses of derivative operators.
3.3.5 Step 5: Separability
A 2D convolution kernel K is separable if it can be written as an outer product of
two 1D kernels:
K[k1 , k2 ] = v[k1 ] · u[k2 ],
i.e., K = vu
⊤
.
(3.19)
If K is separable, the 2D convolution factors into two 1D convolutions:
(I ∗ K)[m, n] = (I ∗rows u) ∗cols v.
Computational gain.
(3.20)
Direct 2D convolution with a K × K kernel:
operations. Separable 1D convolutions:
O(HW K 2 )
O(HW · 2K) operations. Speedup factor:
K/2.
Example: The Gaussian kernel is separable:
Gσ (x, y) =
1
1
1 −(x2 +y2 )/(2σ2 )
2
2
−x2 /(2σ 2 )
√
√
e
=
e
·
e−y /(2σ ) .
2
2πσ
2πσ
2πσ
|
{z
} |
{z
}
gσ (x)
(3.21)
gσ (y)
3.3.6 Step 6: Padding and Stride
Padding.
To control the spatial size of the output, we add zeros (or reections,
replications) around the border of the input.
With
same padding of ⌊K/2⌋
pixels on each side, the output has the same spatial size as the input.
3.4.
Geometric / Information-Theoretic Interpretation
Stride.
35
Instead of stepping the kernel by 1 pixel at a time, we can use stride s:
move the kernel s pixels between applications. The output size is
Hin + 2p − K
Hout =
+1
s
(3.22)
where p is the padding and K is the kernel size.
Dilation.
A dilated (à-trous) convolution inserts d − 1 zeros between kernel ele-
ments, eectively expanding the kernel to size K + (K − 1)(d − 1) = d(K − 1) + 1
without increasing the number of parameters. The output size formula generalises
to:
Hin + 2p − d(K − 1) − 1
Hout =
+ 1.
s
(3.23)
3.4 Geometric / Information-Theoretic Interpretation
3.4.1 Frequency-Selective Filtering
Since convolution is pointwise multiplication in the frequency domain, a convolution
kernel acts as a frequency lter:
Low-pass lter (e.g., Gaussian): |ĥ(u, v)| is large near (0, 0) and small at high
frequencies. Eect: blurring/smoothing. Removes noise (high-frequency).
High-pass lter (e.g., Laplacian): |ĥ(u, v)| is small near (0, 0) and large at
high frequencies. Eect: sharpening/edge enhancement.
Band-pass lter: emphasises a specic frequency band.
Gabor lters are
band-pass they are also the optimal linear lters for joint localisation
in space and frequency (they achieve the Heisenberg uncertainty principle
bound).
3.4.2 Information Flow in a Convolutional Layer
Each convolution kernel extracts one type of feature from the input. A layer with
Cout kernels produces Cout feature maps, each of which is a heat map answering:
how strongly does this feature appear at each location?
The information bottleneck viewpoint: the kernel lters out the frequencies it
is not sensitive to, retaining only the relevant frequency content. Stacking convolutional layers progressively builds up frequency-selective, spatially localised detectors
of increasing complexity.
3.5.
Implementation from Scratch
36
3.5 Implementation from Scratch
1
import numpy as np
2
3
4
5
6
7
8
9
10
11
12
13
14
# ------------------------------------------------------# 1. Naive 2D cross - correlation ( what CNNs actually do )
# ------------------------------------------------------def conv2d_naive (I , K , stride =1 , padding =0) :
"""
I: input image ( H_in , W_in )
K: kernel
( kH , kW )
stride , padding : integers
Returns : output feature map ( H_out , W_out )
"""
H_in , W_in = I . shape
kH , kW
= K. shape
15
16
17
18
# Pad the input
I_padded = np . pad (I , padding , mode = ' constant ' ,
constant_values =0)
H_p , W_p = I_padded . shape
19
20
21
H_out = ( H_in + 2* padding - kH ) // stride + 1
W_out = ( W_in + 2* padding - kW ) // stride + 1
22
23
O = np . zeros (( H_out , W_out ) , dtype = np . float32 )
24
25
26
27
28
29
30
31
32
for i in range ( H_out ):
for j in range ( W_out ):
# Extract patch
patch = I_padded [ i* stride : i* stride + kH ,
j* stride : j* stride + kW ]
# Dot product ( cross - correlation , no kernel flip )
O[i , j ] = np . sum ( patch * K)
return O
33
34
35
36
37
38
# ------------------------------------------------------# 2. Separable convolution ( much faster for separable kernels )
# ------------------------------------------------------def conv2d_separable (I , v , u , padding =0) :
"""
3.5.
39
40
41
42
43
44
45
46
47
48
49
50
Implementation from Scratch
Applies separable kernel K = v * u ^T in two passes .
v: column filter (kH ,)
u: row filter
(kW ,)
"""
# First pass : convolve along rows with u
u_kernel = u[ np . newaxis , :]
# (1 , kW )
temp = np . zeros_like (I )
kW = len (u )
I_p = np . pad (I , padding , mode = ' constant ')
for i in range (I . shape [0]) :
for j in range (I . shape [1]) :
temp [i , j ] = np . sum ( I_p [i+ padding , j :j+ kW ] * u)
51
52
53
54
55
56
57
58
59
# Second pass : convolve along columns with v
output = np . zeros_like (I)
kH = len (v )
temp_p = np . pad ( temp , padding , mode = ' constant ')
for i in range (I . shape [0]) :
for j in range (I . shape [1]) :
output [i , j] = np . sum ( temp_p [ i:i +kH , j+ padding ] *
v)
return output
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# ------------------------------------------------------# 3. FFT - based convolution ( efficient for large kernels )
# ------------------------------------------------------def conv2d_fft (I , K ):
"""
Convolution via the Convolution Theorem .
Pads K to the same size as I.
"""
H , W = I. shape
# Zero - pad kernel to image size
K_padded = np . zeros_like (I )
kH , kW = K . shape
K_padded [: kH , : kW ] = K
74
75
76
77
78
# FFT of both
FI = np . fft . fft2 ( I)
FK = np . fft . fft2 ( K_padded )
37
3.5.
79
80
Implementation from Scratch
# Pointwise multiply in frequency domain
FO = FI * FK
81
82
83
84
# Inverse FFT
O = np . real ( np . fft . ifft2 ( FO ) )
return O
85
86
87
88
89
90
91
92
93
94
95
96
# ------------------------------------------------------# 4. Classic kernels
# ------------------------------------------------------def gaussian_kernel ( sigma , size = None ) :
""" Isotropic Gaussian kernel . """
if size is None :
size = int (6* sigma + 1) | 1
# ensure odd
ax = np . arange ( -( size //2) , size //2 + 1)
g = np . exp (- ax **2 / (2* sigma **2) )
g /= g. sum ()
return np . outer (g , g)
# separable !
97
98
99
100
101
# Sobel kernels ( approximate image gradient )
SOBEL_X = np . array ([[ -1 , 0, 1] ,
[ -2 , 0, 2] ,
[ -1 , 0, 1]] , dtype = np . float32 )
102
103
104
105
SOBEL_Y = np . array ([[ -1 , -2, -1] ,
[ 0 , 0 , 0] ,
[ 1 , 2 , 1]] , dtype = np . float32 )
106
107
108
109
110
111
112
113
114
115
116
117
118
# Laplacian of Gaussian ( LoG )
blob detector
def laplacian_of_gaussian ( sigma , size = None ) :
""" LoG kernel : high response at blob boundaries . """
if size is None :
size = int (6* sigma + 1) | 1
ax = np . arange ( -( size //2) , size //2 + 1)
xx , yy = np . meshgrid (ax , ax )
r2 = xx **2 + yy **2
log = ( r2 - 2* sigma **2) / sigma **4 * np . exp ( - r2 /(2* sigma
**2) )
log -= log . mean ()
# zero - mean
return log
38
3.6.
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
Failure Modes and Limitations
39
# ------------------------------------------------------# 5. Demo : edge detection pipeline
# ------------------------------------------------------def detect_edges ( I_gray , sigma =1.0) :
"""
Classic edge detection :
1. Smooth with Gaussian
2. Apply Sobel in x and y
3. Compute gradient magnitude
"""
G
= gaussian_kernel ( sigma )
I_s = conv2d_naive ( I_gray , G , padding = len ( G) //2)
Gx = conv2d_naive ( I_s , SOBEL_X , padding =1)
Gy = conv2d_naive ( I_s , SOBEL_Y , padding =1)
magnitude = np . sqrt ( Gx **2 + Gy **2)
angle
= np . arctan2 ( Gy , Gx )
# gradient direction
return magnitude , angle
136
137
138
139
140
141
# Quick sanity check
I_test = np . random . rand (16 , 16) . astype ( np . float32 )
K_test = np . array ([[0 , -1 ,0] ,[ -1 ,4 , -1] ,[0 , -1 ,0]] , dtype = np .
float32 )
out_naive = conv2d_naive ( I_test , K_test , padding =1)
print (" Output shape : " , out_naive . shape )
# should be (16 , 16)
Listing 3.1: 2D Convolution from Scratch No High-Level Libraries
3.6 Failure Modes and Limitations
1. Boundary eects: Zero-padding introduces articial edges at the image
boundary. Reection or replication padding mitigate this.
2. Fixed receptive eld: A single convolution layer sees only a K × K region.
To capture long-range dependencies, you need either many stacked layers (and
a deep network) or a very large kernel (expensive). Transformers address this
limitation in Phase 5.
3. Anisotropy of the grid: The square pixel grid has preferred directions
(horizontal, vertical, diagonal at 45°). Circular or hexagonal grids would have
better rotational symmetry, but square grids dominate for practical reasons.
4. Aliasing in strided convolutions: When stride s > 1, the convolution
3.7.
Connection to the Next Concept
40
downsamples the output. If the feature map has high-frequency content above
the new Nyquist rate, aliasing occurs this is why blurring before striding
(anti-alias convolutions) matters.
5. Ineciency of naive implementation: The naive O(HW K 2 ) loop is extremely slow. In practice, convolution is recast as a matrix multiplication via
the im2col operation.
3.7 Connection to the Next Concept
We have derived convolution as the unique operation for LSI systems. The key property that makes convolutions special for images is that the
same kernel is applied
everywhere. This raises an important question: what exactly does same everywhere mean mathematically? It means the operation is translation equivariant
shifting the input shifts the output by the same amount. This property is not
just a consequence of convolution; it is its dening characteristic.
3.8 Exercises
Exercise 3.1 Deriving Convolution
Starting from the axioms of linearity and shift-invariance
only :
1. Write out the sifting property of the discrete delta function.
2. Use linearity to express the output y[n] as a sum over shifted impulse
responses.
3. Apply shift-invariance to show that this sum is a convolution.
4. Generalise the entire derivation to 2D without skipping any steps.
3.8.
Exercises
41
Answer: Answer 3.1
(a) Sifting property: x[n] =
P∞
k=−∞ x[k] δ[n − k].
(b) By linearity:
y[n] = T
(
X
)
x[k] δ[n − k]
k
=
X
x[k] T {δ[n − k]} .
k
(c) Dene h[n] ≜ T{δ[n]}. By shift-invariance, T{δ[n − k]} = h[n − k]. Therefore:
X
y[n] =
x[k] h[n − k] =: (x ∗ h)[n].
□
k
(d) In 2D, any signal x[m, n] =
P P
k1
k2 x[k1 , k2 ] δ[m−k1 , n−k2 ]. By linearity:
P
y[m, n] = k1 ,k2 x[k1 , k2 ] T {δ[m−k1 , n−k2 ]}. By 2D shift-invariance: T {δ[m−
P
k1 , n − k2 ]} = h[m − k1 , n − k2 ]. Therefore: y[m, n] = k1 ,k2 x[k1 , k2 ] h[m −
k1 , n − k2 ] = (x ∗ h)[m, n].
Exercise 3.2 Convolution Theorem Application
1. A Gaussian lter with σ = 2 is applied twice to an image. What single
lter achieves the same eect, and what is its σ ?
2. Prove this using the Convolution Theorem.
3. Why is this result practically useful for multi-scale image analysis?
Answer: Answer 3.2
(a) Applying Gaussian with σ1 then σ2 gives a Gaussian with σ =
For σ1 = σ2 = 2: σ =
√
√
8 = 2 2.
p
σ12 + σ22 .
(b) The Fourier transform of a Gaussian Gσ is another Gaussian: Ĝσ (u, v) =
2 2
2
2
e−2π σ (u +v ) . Applying Gσ1 then Gσ2 :
F{I ∗ Gσ1 ∗ Gσ2 } = Iˆ · Ĝσ1 · Ĝσ2
2 2 2
2
2 2 2
2
= Iˆ · e−2π σ1 (u +v ) · e−2π σ2 (u +v )
−2π 2 (σ12 +σ22 )(u2 +v 2 )
= Iˆ · e
(3.24)
(3.25)
= Iˆ · Ĝ√σ2 +σ2 . □
1
(3.26)
2
(c) This shows that the Gaussian scale-space is closed under composition :
blurring by σ1 then σ2 is the same as blurring by
p
σ12 + σ22 once. This means
you can build a scale-space pyramid incrementally by small Gaussian blurs,
which is the basis of SIFT and Laplacian-of-Gaussian blob detectors.
3.8.
Exercises
Exercise 3.3 Implementation
1. Implement the im2col operation that reshapes an image into a matrix
so that a single matrix multiply computes the full convolution.
2. Show that output = kernel_matrix @ im2col(image) is equivalent
to the naive convolution loop.
3. Measure the speedup on a 64 × 64 image with a 5 × 5 kernel (compare
loop vs matrix multiply).
42
3.8.
Exercises
Answer: Answer 3.3
1
2
import numpy as np
import time
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def im2col (I , kH , kW , stride =1 , padding =0) :
"""
Convert image patches to columns .
Returns matrix of shape ( kH *kW , H_out * W_out ).
Each column is one flattened receptive field .
"""
I_p = np . pad (I , padding , mode = ' constant ')
H_in , W_in = I_p . shape
H_out = ( H_in - kH ) // stride + 1
W_out = ( W_in - kW ) // stride + 1
cols = np . zeros (( kH *kW , H_out * W_out ) , dtype =I . dtype )
col = 0
for i in range ( H_out ):
for j in range ( W_out ):
patch = I_p [i* stride :i* stride + kH ,
j* stride :j* stride + kW ]
cols [: , col ] = patch . ravel ()
col += 1
return cols
23
24
25
26
27
28
29
30
31
32
33
34
35
def conv2d_im2col (I , K , stride =1 , padding =0) :
kH , kW = K . shape
H_in , W_in = I . shape
H_out = ( H_in + 2* padding - kH ) // stride + 1
W_out = ( W_in + 2* padding - kW ) // stride + 1
# im2col : ( kH *kW , H_out * W_out )
col = im2col (I , kH , kW , stride , padding )
# Reshape kernel to (1 , kH * kW )
k_flat = K. ravel () [ np . newaxis , :]
# (1 , kH * kW )
# Matrix multiply : (1 , kH * kW ) @ ( kH *kW , H_out * W_out ) =
(1 , H_out * W_out )
out = ( k_flat @ col ) . reshape ( H_out , W_out )
return out
36
37
38
39
# Timing comparison
I = np . random . rand (64 , 64) . astype ( np . float32 )
K = np . random . rand (5 , 5) . astype ( np . float32 )
40
41
42
43
t0 = time . time ()
for _ in range (10) :
out1 = conv2d_naive (I , K , padding =2)
43
Chapter 4
Translation Equivariance
4.1 Intuition
If you take a photo of a cat on the left side of the frame, and then retake it with
the cat on the right side, the cat is still a cat. A good detector should respond the
same way to the cat regardless of its position. This is translation equivariance
(for detectors) or translation invariance (for classiers).
Key Insight:
Equivariance means the representation moves with the input transformation.
Invariance means the representation does not change under the input transformation.
Convolution is equivariant to translations. Pooling adds invariance.
4.2 Formal Denition
Denition: Translation Operator
The translation operator Tτ shifts a signal by τ = (τ1 , τ2 ):
(Tτ f )(x, y) = f (x − τ1 , y − τ2 ).
44
4.3.
Mathematical Derivation
45
Denition: Equivariance
A function Φ is equivariant with respect to transformation g if:
Φ(g · x) = g · Φ(x) ∀ x, ∀ g ∈ G,
where G is the group of transformations.
Denition: Invariance
A function Φ is invariant with respect to transformation g if:
Φ(g · x) = Φ(x) ∀ x, ∀ g ∈ G.
4.3 Mathematical Derivation
Theorem 4.1 (Convolution is Translation-Equivariant). For any lter h and shift
τ:
(f ∗ h)(x − τ ) = ((Tτ f ) ∗ h)(x).
Equivalently: Tτ (f ∗ h) = (Tτ f ) ∗ h.
Proof.
Z
((Tτ f ) ∗ h)(x) =
(Tτ f )(ξ) h(x − ξ) dξ
(4.1)
f (ξ − τ ) h(x − ξ) dξ.
(4.2)
Z
=
Substitute ξ
Z
=
′
= ξ − τ:
f (ξ ′ ) h(x − τ − ξ ′ ) dξ ′ = (f ∗ h)(x − τ ) = Tτ (f ∗ h)(x). □
Group-theoretic interpretation.
(4.3)
2
The set of translations {Tτ : τ ∈ R } forms a
group under composition. Convolution commutes with every element of this
group. A function that commutes with a group action is said to be an equivariant
map. Convolution is the unique linear equivariant map for the translation group
this is essentially the content of the derivation in the previous chapter.
4.4 Implementation
4.4.
1
Implementation
46
import numpy as np
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def translate_image (I , dy , dx ):
"""
Shifts image I by (dy , dx ) pixels ( zero - padding borders ).
"""
H , W = I. shape
J = np . zeros_like (I )
# Source -> Destination mapping
src_r0 = max (0 , -dy ) ; src_r1 = min (H , H - dy )
dst_r0 = max (0 , dy ) ; dst_r1 = min (H , H+ dy )
src_c0 = max (0 , -dx ) ; src_c1 = min (W , W - dx )
dst_c0 = max (0 , dx ) ; dst_c1 = min (W , W+ dx )
J[ dst_r0 : dst_r1 , dst_c0 : dst_c1 ] = \
I[ src_r0 : src_r1 , src_c0 : src_c1 ]
return J
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
def verify_equivariance (I , K , dy =5 , dx =3) :
"""
Checks : conv (T( I) , K) == T ( conv (I , K ))
"""
p = K. shape [0] // 2
# Path 1: translate then convolve
I_shifted = translate_image (I , dy , dx )
out1 = conv2d_naive ( I_shifted , K , padding = p)
# Path 2: convolve then translate
out_full = conv2d_naive (I , K , padding =p)
out2 = translate_image ( out_full , dy , dx )
# Compare ( ignore border artefacts )
err = np . max ( np . abs ( out1 [ dy + p : -( dy +p) , dx +p : -( dx +p )]
- out2 [ dy + p : -( dy +p) , dx +p : -( dx +p) ]) )
print (f " Max equivariance error ( interior ): { err :.2 e}" )
return err < 1e -5
34
35
36
37
38
I = np . random . rand (32 , 32) . astype ( np . float32 )
K = np . array ([[0 , -1 ,0] ,[ -1 ,4 , -1] ,[0 , -1 ,0]] , dtype = np . float32 )
assert verify_equivariance (I , K , dy =4 , dx =6)
print (" Equivariance verified ! ")
Listing 4.1: Verifying Translation Equivariance Numerically
4.5.
Failure Modes
47
4.5 Failure Modes
1. Boundary: Equivariance breaks near image borders due to padding. The
system is only approximately equivariant on nite images.
2. Striding destroys equivariance to subpixel translations: With stride
s > 1, the system is only equivariant to translations that are multiples of s.
3. Not equivariant to rotation or scale:
equivariant to rotations.
Standard convolutions are not
Achieving rotational equivariance requires group-
equivariant CNNs (G-CNNs).
4.6 Exercises
Exercise 4.1 Equivariance vs Invariance
1
1. Is the global average pooling operation Φ(I) = HW
P
m,n I[m, n] invari-
ant or equivariant to translation? Prove your answer.
2. Is the max-pooling operation over a 2×2 region equivariant to translation
by 1 pixel? By 2 pixels?
3. Design a simple 2-layer architecture (convolution + global average pool)
and prove it is
invariant to any translation.
Answer: Answer 4.1
1
(a) Φ(Tτ I) = HW
P
m,n I[m−τ1 , n−τ2 ]. Assuming cyclic boundary conditions,
this is a reindexing of the same pixels the sum is the same. So Φ(Tτ I) =
Φ(I): invariant.
(b) Max pooling over 2 × 2 with stride 2 is not equivariant to translation by
1 pixel: shifting the input by 1 pixel changes which pixels fall into each pool
window, potentially changing the max. It
is equivariant to translation by 2
pixels (multiples of the stride), since the pool windows themselves shift by 1
pool step.
(c) Let F1 = f ∗ K (convolution, equivariant to translation) and Φ(F1 ) =
1
HW
P
m,n F1 [m, n] (global average pool, invariant to translation).
Φ(F1 (Tτ f )) = Φ(Tτ F1 (f )) = Φ(F1 (f )). The composition is invariant.
Then
Chapter 5
Edge Detection and Filters
5.1 Intuition
Edges are the most informative primitive in an image they mark boundaries
between objects, shadows, and texture regions. Psychophysical experiments show
that humans can recognise line-drawing versions of images almost as well as photographic ones.
The reason is that edges
carry the shape information while
uniform regions carry only material/lighting information.
5.2 Formal Denition
Denition: Image Gradient
The image gradient at pixel (m, n) is the 2D vector:
∇I[m, n] =
!
∂I/∂x
[m, n] ≈
∂I/∂y
!
I[m, n + 1] − I[m, n − 1]
/2.
I[m + 1, n] − I[m − 1, n]
The gradient magnitude ∥∇I∥ is large at edges. The gradient direction θ =
arctan(∂I/∂y, ∂I/∂x) gives the edge orientation.
5.3 Mathematical Derivation
5.3.1 Derivative Filters
The discrete derivative in x is approximated by the nite dierence:
∂I
[m, n] ≈ I[m, n + 1] − I[m, n − 1]
∂x
48
(5.1)
5.3.
Mathematical Derivation
49
which corresponds to convolution with the kernel [−1, 0, +1].
Why Sobel over nite dierence?
The simple [−1, 0, +1] lter is sensitive to
noise. The Sobel lter combines gradient estimation with local smoothing:
−1 0 1
1
Kx = −2 0 2 = 2 −1 0 1 .
1
−1 0 1
(5.2)
⊤
It is separable: rst smooth in y with [1, 2, 1] , then dierentiate in x with [−1, 0, 1].
5.3.2 Canny Edge Detector: A Complete Derivation
The Canny detector is the optimal edge detector under assumptions of a Gaussian
noise model. It has four steps:
1. Smooth: Is = I ∗ Gσ (suppress noise)
2. Gradient: Compute Gx = Is ∗ Kx , Gy = Is ∗ Ky ; then M =
p 2
Gx + G2y ,
θ = arctan(Gy /Gx ).
3. Non-maximum suppression (NMS): At each pixel, check if M [m, n] is a
local maximum along the gradient direction. If not, set it to zero. This thins
the edge response to a 1-pixel-wide ridge.
4. Hysteresis thresholding: Use two thresholds Tl < Th . Mark pixels with
M > Th as strong edges, Tl < M < Th as weak edges. Keep weak edges only
if connected to a strong edge (via 8-connectivity). This suppresses noise while
preserving continuity.
1
import numpy as np
2
3
4
5
6
7
def canny_edges (I , sigma =1.0 , T_low =0.1 , T_high =0.3) :
""" Full Canny edge detector . I: grayscale in [0 ,1]. """
# Step 1: Gaussian smoothing
G = gaussian_kernel ( sigma )
Is = conv2d_naive (I , G , padding = len (G ) //2)
8
9
10
11
12
13
# Step 2: Gradient
Gx = conv2d_naive (Is , SOBEL_X , padding =1)
Gy = conv2d_naive (Is , SOBEL_Y , padding =1)
M = np . sqrt ( Gx **2 + Gy **2)
M = M / (M. max () + 1e -8)
# normalise
5.3.
14
Mathematical Derivation
theta = np . arctan2 (Gy , Gx )
50
# in [ -pi , pi ]
15
16
17
18
19
20
# Step 3: Non - maximum suppression
H , W = M. shape
NMS = np . zeros_like (M)
# Quantise angle to 4 directions : 0, 45 , 90 , 135 degrees
angle_deg = np . degrees ( theta ) % 180
# map to [0 ,180)
21
22
23
24
25
26
27
28
29
30
31
32
33
34
for i in range (1 , H -1) :
for j in range (1 , W -1) :
a = angle_deg [i , j]
if (0 <= a < 22.5) or (157.5 <= a < 180) :
q , r = M[i , j +1] , M[i , j -1]
# 0 deg
elif 22.5 <= a < 67.5:
q , r = M[i +1 , j -1] , M[i -1 , j +1] # 45 deg
elif 67.5 <= a < 112.5:
q , r = M[i +1 , j], M[i -1 , j]
# 90 deg
else :
q , r = M[i -1 , j -1] , M[i +1 , j +1] # 135 deg
if M[i , j] >= q and M[i ,j] >= r:
NMS [i ,j] = M [i , j]
35
36
37
38
39
# Step
strong
weak
edges
4: Hysteresis thresholding
= NMS > T_high
= ( NMS > T_low ) & ~ strong
= np . copy ( strong ) . astype ( np . uint8 )
40
41
42
43
44
45
46
47
48
49
50
51
52
# 8 - connectivity : propagate strong edges to connected weak
ones
from collections import deque
queue = deque ( zip (* np . where ( strong )) )
visited = set ( map ( tuple , np . argwhere ( strong ) ))
while queue :
y , x = queue . popleft ()
for dy in ( -1 , 0, 1) :
for dx in ( -1 , 0, 1) :
ny , nx = y +dy , x+ dx
if (0 <= ny < H and 0 <= nx <W and
weak [ ny , nx ] and (ny , nx ) not in visited
):
edges [ny , nx ] = 1
5.4.
Failure Modes
visited . add (( ny , nx ))
queue . append (( ny , nx ))
53
54
55
51
return edges
Listing 5.1: Canny Edge Detector from Scratch
5.4 Failure Modes
1. Noise sensitivity: Without Gaussian pre-smoothing, derivative lters amplify noise (dierentiation is a high-pass operation).
2. Scale dependence: Choosing σ determines which scales of edges are detected. Small σ detects ne edges; large σ detects coarse structures. No single
σ works for all images.
3. Gaps at junctions: NMS can break edges at T-junctions or corners where
the gradient direction changes rapidly.
5.5 Exercises
Exercise 5.1 Gradient and Edge Detection
1. Show that applying the Sobel-x kernel is equivalent to rst smoothing
with a 1D Gaussian in y and then dierentiating in x.
2. Derive the Laplacian of Gaussian (LoG) lter and explain why it
detects edges at zero-crossings.
3. For the LoG, prove that the 2D LoG can be approximated by the Difference of Gaussians (DoG): LoG ≈ Gσ − Gkσ for k ≈ 1.6.
5.5.
Exercises
52
Answer: Answer 5.1
(a) Write Kx = [1, 2, 1]⊤ · [−1, 0, 1]. The [1, 2, 1]⊤ part is a binomial approximation to a 1D Gaussian in y (smoothing), and [−1, 0, 1] is the nite-dierence
⊤
derivative in x. Convolution is associative: I ∗Kx = (I ∗y [1, 2, 1] )∗x [−1, 0, 1].
∂2G
∂2G
(b) The LoG is ∇2 Gσ (x, y) = ∂x2σ + ∂y 2σ . Computing:
LoG(x, y) =
x2 + y 2 − 2σ 2 −(x2 +y2 )/(2σ2 )
e
.
σ4
2
Applying LoG to an image gives ∇ (I ∗ Gσ ) = I ∗ LoG (by the derivative
property of convolution). Edges in I produce extrema in I ∗Gσ , which produce
zero-crossings in ∇2 (I ∗ Gσ ).
(c) By Taylor expansion, for small ∆σ :
Gσ − Gσ+∆σ ≈ −
For discrete scale ratio k :
∆σ 2
∂Gσ
∆σ = −
· σ LoG(x, y; σ).
∂σ
σ
Gσ − Gkσ ≈ (k − 1)σ 2 LoG. Empirically, k ≈ 1.6
gives a good approximation (the ratio used in the SIFT algorithm).
Chapter 6
Feature Extraction
6.1 Intuition
Raw pixels are terrible features for recognition: a cat occupies only a small patch,
its pixels vary with lighting, pose, and scale. We need features that are:
Distinctive: dierent objects have dierent features
Invariant: same object under dierent conditions has similar features
Compact: low-dimensional representation
Classical methods designed these by hand.
data.
Deep learning
learns them from
Understanding the hand-crafted methods illuminates why learned features
are so powerful.
6.2 HOG: Histogram of Oriented Gradients
Denition: HOG
HOG divides the image into B×B cells, computes gradient orientations in each
cell, and builds a histogram of orientations weighted by gradient magnitude.
Neighbouring cells are grouped into
Mathematical formulation.
hc [k] =
X
blocks and L2-normalised.
In each cell c:
∥∇I[m, n]∥ · 1[θ[m, n] ∈ bin k] ,
k = 1, . . . , K.
(6.1)
(m,n)∈c
The K -bin histogram hc is invariant to local illumination changes (contrast normalisation in the block step) and captures the dominant gradient orientation in the
cell.
53
6.3.
SIFT: Scale-Invariant Feature Transform
54
6.3 SIFT: Scale-Invariant Feature Transform
SIFT achieves scale invariance by:
1. Building a Gaussian scale-space pyramid: L(x, y, σ) = Gσ ∗ I .
2. Detecting keypoints as extrema in the DoG pyramid (local extrema in both
scale and space).
3. Computing a descriptor: a 4 × 4 × 8 = 128-dimensional HOG-like descriptor
in the keypoint's local coordinate frame (rotated to the dominant gradient
orientation for rotation invariance).
6.4 Connection to CNNs
HOG, SIFT, and LBP all compute statistics of local gradient distributions.
rst convolutional layer of a CNN learns
optimal oriented gradient detectors.
The
Gabor-like lters which are exactly
The CNN then learns to combine these into
increasingly abstract features automatically. The hand-crafted pipeline is a special,
manually optimised case of what CNNs discover automatically.
6.5 Exercises
Exercise 6.1 HOG Descriptor
1. A 64 × 128 pedestrian image is divided into 8 × 8 cells with 9 orientation
bins and 2 × 2 blocks. How many dimensions does the HOG descriptor
have?
2. Why are blocks L2-normalised rather than cells? What problem does
block normalisation solve?
3. Implement a simplied HOG for a single 8 × 8 cell.
6.5.
Exercises
55
Answer: Answer 6.1
(a) Number of cells: (64/8) × (128/8) = 8 × 16 = 128 cells. Number of blocks
(8 − 1) × (16 − 1) = 7 × 15 = 105 blocks. Each block: 2 × 2
cells × 9 bins = 36 dimensions. Total: 105 × 36 = 3780 dimensions.
(stride=1 cell):
(b) If a cell is normalised independently, local brightness changes within the
cell are handled, but a large bright region neighbouring the cell could still
cause instability.
Block normalisation pools over a 2 × 2 neighbourhood of
cells, handling wider-range illumination variations and providing some spatial
context to the normalisation.
(c)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def hog_cell ( patch , n_bins =9) :
"""
patch : (8 , 8) grayscale image patch
Returns : ( n_bins ,) orientation histogram
"""
# Gradients via finite difference
Gx = np . diff ( patch , axis =1 , append = patch [: , -1:])
Gy = np . diff ( patch , axis =0 , append = patch [ -1: , :])
magnitude = np . sqrt ( Gx **2 + Gy **2)
angle = np . degrees ( np . arctan2 ( Gy , Gx ) ) % 180
#
unsigned [0 ,180)
hist = np . zeros ( n_bins )
bin_width = 180.0 / n_bins
for k in range ( n_bins ) :
bin_low = k * bin_width
bin_high = (k +1) * bin_width
mask = ( angle >= bin_low ) & ( angle < bin_high )
hist [ k] = magnitude [ mask ]. sum ()
return hist
Listing 6.1: HOG cell descriptor
Part II
Phase 2: Representation Learning
56
Chapter 7
Why Handcrafted Features Fail
7.1 Intuition
For 20+ years, computer vision relied on pipelines like:
SIFT/HOG
SVM/RF
Image −−−−−−→ Feature vector −
−−−−→ Prediction
These worked remarkably well for limited
domains.
They collapsed when the
world became richer.
7.2 The Semantic Gap
Key Insight:
The semantic gap is the dierence between what can be expressed in lowlevel pixel statistics and the high-level concepts needed for understanding. A
HOG descriptor of a dog image and a HOG descriptor of a wolf image may be
nearly identical both are four-legged, furry, horizontal shapes with similar
gradient distributions.
7.3 Curse of Dimensionality for Hand-Crafted Features
1. HOG gives a xed 3780-dimensional vector for a 64 × 128 patch. How do we
design features for a 1000 × 1000 image? We must choose a xed scale but
the relevant scale varies.
2. Features designed for one domain (faces) do not transfer to others (cars). For
57
7.4.
What Deep Learning Provides
58
each new task, features must be redesigned from scratch.
3. The combination of features required to describe complex patterns (a dog's
face is a conjunction of two eyes, a nose, and a muzzle in a specic spatial
layout) is exponentially hard to enumerate by hand.
7.4 What Deep Learning Provides
Rather than xing features, deep networks learn a hierarchy
of features from
data:
Layer 1: Gabor-like edge detectors (same as HOG, learned automatically)
Layer 2: Corners, curves, and textures
Layer 3: Object parts (wheels, eyes, windows)
Layer 4+: Full objects and scenes
Each level is a nonlinear combination of the level below. This compositional hi-
erarchy is exponentially more powerful than any xed hand-crafted representation.
7.5 Exercises
Exercise 7.1 The Representation Problem
1. Given a dataset with 1000 object categories, each with ∼ 100 images,
why is it dicult to design a single hand-crafted feature that works for
all categories?
2. What is feature engineering and why does it fail to scale?
3. Describe the manifold hypothesis and why deep networks are better
suited to capture it than SVMs with hand-crafted features.
7.5.
Exercises
59
Answer: Answer 7.1
(a) Object categories vary in texture (fur vs metal), shape (round vs elongated), colour (irrelevant for some, diagnostic for others), and parts structure.
A single feature vector must somehow capture all of this variation.
HOG
captures shape/gradient information but is colour-blind. Colour histograms
capture colour but are spatial-layout blind. No single xed feature captures
all relevant variations; one would need to engineer a dierent feature for each
category.
(b) Feature engineering is the process of manually designing input representations (SIFT, HOG, LBP, etc.) based on domain knowledge. It fails to scale
because (i) it requires expert knowledge for each domain, (ii) the engineered
features are heuristics with no guarantee of optimality, and (iii) with 1000+
categories, no team can manually design and tune features for each.
(c) The manifold hypothesis states that real data (images of objects) lies
on a low-dimensional nonlinear manifold embedded in high-dimensional pixel
space. SVMs with xed kernels can only model linear or xed-kernel (polynomial, RBF) decision boundaries in the feature space. If the hand-crafted
features do not already disentangle the manifold, the SVM cannot overcome
this. Deep networks learn to
unfold the manifold through hierarchical nonlin-
ear transformations, progressively mapping the manifold to a linearly separable space.
Chapter 8
Perceptron Limitations on Images
8.1 Intuition
The simplest neural network for image classication is a fully connected (FC) layer:
vectorise the image, multiply by a weight matrix, add a bias, apply a non-linearity.
This seems powerful and for tiny images it works. For real images, it catastrophically fails.
8.2 Parameter Count Analysis
For a single FC layer mapping a 224 × 224 × 3 image to 1000 classes:
Parameters = (224 × 224 × 3) × 1000 = 150,528 × 1000 ≈ 150 million.
And this is
(8.1)
one layer. Training 150M parameters from, say, 50,000 training images
guarantees extreme overtting.
8.3 Why FC Layers Fail on Images: Three Fundamental Problems
1. No spatial structure: The FC layer treats every pixel independently. It
has no notion that pixel (m, n) is spatially close to pixel (m, n + 1). Spatial
relationships (which are crucial for recognising shapes) must be re-learned from
scratch by the weights at enormous cost.
2. No translation invariance: A cat in the top-left corner activates completely
dierent weights than a cat in the bottom-right corner.
60
The two cats are
8.4.
Exercises
61
recognised by entirely dierent learned patterns. The model must see every
object at every position during training or it will fail.
3. No parameter sharing:
The detector for a horizontal edge at position
(10, 10) uses dierent parameters than the same detector at (100, 100). But
edges are the same everywhere. The redundancy is complete waste.
8.4 Exercises
Exercise 8.1 FC vs Convolutional
1. A 32 × 32 grayscale image enters a single FC layer with 512 outputs.
How many parameters does this require?
2. If we replace this with a single 3 × 3 convolutional layer (32 output
channels), how many parameters are needed?
3. What is the parameter reduction ratio? What property of images justies this reduction?
Answer: Answer 8.1
(a) FC: (32 × 32) × 512 + 512 = 1024 × 512 + 512 = 524,800 parameters.
(b) Conv: 32 × (3 × 3 × 1) + 32 = 32 × 9 + 32 = 320 parameters.
(c) Ratio:
524,800/320 = 1640× reduction.
Justied by:
(i)
local con-
nectivity (nearby pixels are more related than distant ones locality), (ii)
weight sharing (same feature appears at multiple positions spatial stationarity of natural images).
Chapter 9
Spatial Structure and the CNN Idea
9.1 Spatial Hierarchy of Visual Concepts
Natural images have a compositional spatial hierarchy:
Pixels → edges (local, 3 × 3)
Edges → curves, corners (larger local, 7 × 7)
Curves → parts: wheels, eyes (15 × 15)
Parts → objects: car, face (50 × 50)
Objects → scenes (224 × 224)
Each level needs to see a larger spatial region.
Rather than building a single
huge lter, we stack layers: each layer increases the receptive eld (the image
region inuencing one neuron) while operating on compact, local features.
62
9.2.
The CNN Hypothesis
9.2 The CNN Hypothesis
Key Insight:
The CNN is simply the implementation of three empirical facts about visual
data:
1. Visual features are spatially local.
2. Visual features repeat across space (translation stationarity).
3. Complex features are compositions of simpler ones (hierarchy).
These facts imply:
local connectivity + weight sharing + pooling +
stacking. This is the CNN.
9.3 Exercises
Exercise 9.1 Receptive Field Calculation
A network has three 3 × 3 convolutional layers (all stride 1, no padding):
1. What is the receptive eld of a neuron in layer 3 in terms of the input
image?
2. If you add a 2 × 2 max-pool with stride 2 after layer 1, what is the
receptive eld of a neuron at the same position in layer 3?
3. State the general formula for the receptive eld after L layers of K × K
convolutions with stride 1.
63
9.3.
Exercises
64
Answer: Answer 9.1
(a) Layer 1 sees 3 × 3.
Layer 2 sees
(3 − 1) + 3 = 5 × 5.
Layer 3 sees
(5 − 1) + 3 = 7 × 7.
(b) After layer 1, the spatial scale doubles due to the 2 × 2 pool with stride 2.
Layer 2 (at reduced scale) sees 3×3 at layer-2 resolution, which is 3×2 = 6×6
in input pixels.
Adding the layer-1 context: eective receptive eld grows.
Formally, after the pool, 1 layer-2 pixel corresponds to 2 input pixels, so a
3 × 3 kernel at layer 2 covers 3 × 2 = 6 input pixels on a side, and including
layer 1: 6 + (3 − 1) = 8? Actually: the pool with stride 2 means a neuron in
layer 2 has a receptive eld of 3 × 2 + 2 × (3 − 1)/2... let's compute carefully.
Pool: stride-2 means 1 pool-output pixel comes from a 2 × 2 input region,
oset by 2. A 3 × 3 layer-2 kernel over pooled features covers a 3 × 2 = 6
pixel range in layer-1 features, plus the 3 − 1 = 2 pixels of overlap: total
3 × 2 + (3 − 1) − (3 − 1) = . . . Simplest: RF after pool = (3 − 1) × 2 + 2 = 6. RF
after layer-2 (on top of pool): 6+(3−1) = 8. RF after layer-3: 8+(3−1) = 10.
(c) For L layers of K × K (stride 1):
RF(L) = (K − 1) · L + 1.
For K = 3: RF(L) = 2L + 1. For L = 3: RF = 7. ✓
Part III
Phase 3: CNN Core
65
Chapter 10
Convolutional Layers Deep Dive
10.1 The Full Convolutional Layer
Denition: Convolutional Layer
C ×H×W
C ×H ′ ×W ′
A convolutional layer maps input X ∈ R in
to output Y ∈ R out
:
Y[cout , m, n] = b[cout ]+
Cin K−1
X
X
X K−1
W[cout , cin , k1 , k2 ]·X [cin , ms+k1 , ns+k2 ]
cin =1 k1 =0 k2 =0
(10.1)
C ×Cin ×K×K
C
where W ∈ R out
are the learnable weights and b ∈ R out are biases.
Parameter count:
Parameters = C
out · Cin · K 2 + Cout .
(10.2)
FLOP count (multiply-accumulate operations):
FLOPs = C
out · H ′ · W ′ · Cin · K 2 .
(10.3)
10.1.1 Depthwise Separable Convolution
Standard convolution mixes channels and spatial ltering simultaneously.
Depth-
wise separable convolution factors this into:
1. Depthwise conv: Apply a separate K × K kernel per input channel (Cin
kernels total).
2. Pointwise conv: Apply a 1 × 1 convolution to mix channels.
66
10.2.
Backpropagation through Convolution
67
Parameter comparison:
Standard:
Cout · Cin · K 2
DW-Sep:
Cin · K 2 + Cout · Cin ≈ Cin K 2 + Cout
(10.4)
(10.5)
Reduction factor:
1
1
1
Cin (K 2 + Cout )
+
=
≈
Cout · Cin · K 2
Cout K 2
K2
for large C
out .
For K = 3: ≈ 9× fewer parameters. This is the key idea in MobileNet.
10.2 Backpropagation through Convolution
Let L be the scalar loss. Given the upstream gradient
∂L
∂L
∂L
, we need
and
.
∂Y
∂W
∂X
Gradient w.r.t. weights:
X
∂L
∂L
=
· X [ci , ms + k1 , ns + k2 ].
∂W[co , ci , k1 , k2 ]
∂Y[c
,
m,
n]
o
m,n
(10.6)
This is a cross-correlation between the input and the upstream gradient.
Gradient w.r.t. input (for backprop to previous layer):
XX
∂L
∂L
=
· W[co , ci , k1 , k2 ]
∂X [ci , p, q]
∂Y[co , m, n]
c k ,k
o
1
(10.7)
2
where the sum is over (m, n, k1 , k2 ) such that ms + k1 = p and ns + k2 = q . This is
a transposed convolution (full convolution) with the ipped kernel.
Key Insight:
Forward pass:
convolution.
Backward pass for weights:
cross-correlation.
Backward pass for inputs: transposed convolution (convolution with ipped
kernel).
All three operations are convolutions this is why GPUs are so
ecient at CNNs.
10.3.
Exercises
68
10.3 Exercises
Exercise 11.1 Backprop in Conv Layer
A single 3 × 3 conv layer maps 1 × 5 × 5 input to 1 × 3 × 3 output (no padding,
stride 1).
1. Write the forward pass explicitly as a sum (show all 9 output computations).
2. Given upstream gradient δY [m, n] (shape 3 × 3), derive the weight gradient
∂L
explicitly.
∂W [k1 ,k2 ]
3. Show that this gradient computation is a cross-correlation between the
input and δY .
Answer: Answer 11.1
(a) Y [m, n] =
P2
k1 =0
P2
k2 =0 W [k1 , k2 ] · X[m + k1 , n + k2 ], for m, n ∈ {0, 1, 2}.
9 output pixels, each a dot product between the 3 × 3 kernel and the corresponding 3 × 3 patch of the 5 × 5 input.
(b) By the chain rule:
2 X
2
X
X
∂L
∂L
∂Y [m, n]
=
·
=
δY [m, n] · X[m + k1 , n + k2 ].
∂W [k1 , k2 ] m=0 n=0 ∂Y [m, n] ∂W [k1 , k2 ]
m,n
(c) The expression
P
m,n δY [m, n] · X[m + k1 , n + k2 ] is exactly the cross-
correlation of X with δY evaluated at oset (k1 , k2 ):
(δY ⋆ X)[k1 , k2 ]. So the
weight gradient is obtained by cross-correlating the upstream gradient with
the input.
Chapter 11
Receptive Fields
11.1 Denition and Growth Rate
Denition: Receptive Field
The receptive eld of a neuron in layer ℓ is the region in the input image
whose values inuence that neuron's activation.
Theorem 11.1 (Receptive Field Growth). For L stacked layers each with kernel
size K and stride 1:
RF(L) = (K − 1)L + 1.
For stride s at each layer:
RF(L) = 1 + (K − 1)
L Y
ℓ−1
X
si .
ℓ=1 i=1
Why large receptive elds matter.
whole object.
Recognising an object requires seeing the
A car is ∼ 100 pixels wide.
To see 100 pixels with 3 × 3 kernels,
you need (100 − 1)/(3 − 1) = 50 layers. This is the motivation for pooling, dilated
convolutions, and skip connections.
11.2 Theoretical vs Eective Receptive Field
The theoretical receptive eld grows linearly with depth. The eective recep-
tive eld (ERF) the region that actually inuences the output most strongly √
is much smaller, and grows as O(
magnitudes.
L) due to the Gaussian distribution of gradient
This is a signicant practical concern: very deep networks may not
eectively see as much of the image as their theoretical RF suggests.
69
11.3.
Exercises
70
11.3 Exercises
Exercise 12.1 Receptive Field Expansion
1. A network alternates between 3 × 3 conv (stride 1) and 2 × 2 max pool
(stride 2) for 4 such pairs.
What is the receptive eld after the 4th
pooling layer?
2. If instead you use 3 × 3 dilated convolutions with dilation rates 1, 2, 4, 8
(4 layers), what is the receptive eld?
3. Which approach (pooling vs dilation) preserves spatial resolution, and
which one loses it? What are the trade-os?
Answer: Answer 12.1
(a) Pair 1: after conv, RF=3; after pool, RF=3 × 2 + (2 − 1) = 7... More
new = RFold + (K − 1) × prev strides .
precisely, use the recurrence: RF
Q
RF = 3; pool (stride 2): RF = 3 + (2 − 1) × 1 = 4...
PL
Actually the standard formula: RF accumulates as RFL = 1 +
ℓ=1 (Kℓ − 1) ·
Q
i<ℓ si .
Layer sequence: C(3,s=1), P(2,s=2), C(3,s=1), P(2,s=2), ... ×4: Strides:
[1, 2, 1, 2, 1, 2, 1, 2]. (K − 1) = [2, 1, 2, 1, 2, 1, 2, 1]. RF = 1 + 2 · 1 + 1 · 1 + 2 · 1 ·
2 + 1 · 2 + 2 · 4 + 1 · 4 + 2 · 8 + 1 · 8 = 1 + 2 + 1 + 4 + 2 + 8 + 4 + 16 + 8 = 46.
(b) Dilated 3 × 3 with dilation d has eective kernel size 2d + 1. After 4
dilated conv with d ∈ {1, 2, 4, 8} (all stride 1): RF = 1 + (3 − 1) + (3 − 1) ·
2 + (3 − 1) · 4 + (3 − 1) · 8 = 1 + 2 + 4 + 8 + 16 = 31.
(c) Pooling reduces spatial resolution (feature map shrinks by 2× per pool),
After pair 1: conv:
losing ne spatial detail but being computationally cheaper at subsequent
layers. Dilation preserves spatial resolution (useful for dense prediction tasks
like segmentation) but has higher memory cost since feature maps remain
large throughout.
Chapter 12
Parameter Sharing
12.1 The Statistical Justication
Parameter sharing is justied by spatial
stationarity: the distribution of local
image statistics is (approximately) the same everywhere. Formally, if the statistics
of p(I[m, n], I[m + ∆m, n + ∆n]) are independent of (m, n), then the optimal linear
feature extractor is the same at every location i.e., it should be a convolution.
12.2 Parameter Eciency
Layer type
in to Cout )
′
′
Conv (K × K , Cin → Cout , output H × W )
FC (H × W × C
DW-Separable
71
Parameters
FLOPs
HW Cin · Cout
K 2 Cin Cout
K 2 Cin + Cin Cout
K Cin Cout H ′ W ′
same
2
smaller
12.3.
Exercises
72
12.3 Exercises
Exercise 13.1 Parameter Sharing Analysis
A 112 × 112 × 64 feature map feeds into a 3 × 3 conv layer producing 112 ×
112 × 128.
1. How many parameters does this layer have?
2. How many FLOPs does the forward pass require?
3. If instead we used a locally connected (unshared) layer, how many parameters would it need?
4. What is the sharing factor?
Answer: Answer 13.1
(a) Params = K 2 ·Cin ·Cout +Cout = 9×64×128+128 = 73,728+128 = 73,856.
(b) FLOPs = K 2 · Cin · Cout · H ′ · W ′ = 9 × 64 × 128 × 112 × 112 ≈ 925 × 106
(925M).
(c) Locally connected (no sharing): each output pixel has its own 3 × 3 × 64
lter for each of 128 output channels. Params = H
′
· W ′ · K 2 · Cin · Cout =
112 × 112 × 9 × 64 × 128 ≈ 925 × 106 (925M parameters).
(d) Sharing factor = 925 × 106 /73,856 ≈ 12,500× fewer parameters with
weight sharing.
Chapter 13
Pooling
13.1 Intuition and Purpose
Pooling serves three purposes:
1. Spatial invariance: Small translations of the input don't change the pooled
output.
2. Dimensionality reduction: Reduces the size of feature maps, decreasing
computation in subsequent layers.
3. Increasing receptive eld: After pooling, subsequent convolutional kernels
see a larger region of the original input.
13.2 Types of Pooling
Max pooling:
y[m, n] =
max
x[i, j]
(i,j)∈R(m,n)
(13.1)
where R(m, n) is the pooling region. Preserves the strongest activation.
Average pooling:
y[m, n] =
1
|R|
X
x[i, j].
(13.2)
(i,j)∈R(m,n)
Smoother, less sensitive to noise.
Global average pooling (GAP):
y[c] =
1 X
x[c, m, n].
HW m,n
73
(13.3)
13.3.
Backprop through Max Pooling
74
Collapses a C × H × W feature map to a C -dimensional vector. Used in modern
architectures instead of FC layers (fewer parameters, regularisation benet).
13.3 Backprop through Max Pooling
Gradient passes only to the neuron that achieved the maximum (max-winner). All
other inputs in the pool receive zero gradient:
∂L
∂L
= ∂y[m,n]
∂x[i, j] 0
if x[i, j] = y[m, n] (was the max)
(13.4)
otherwise.
13.4 Exercises
Exercise 14.1 Pooling and Invariance
1. Prove that max pooling (with stride equal to pool size) is invariant to
translations within the pool region.
2. What happens to this invariance when stride < pool size (overlapping
pooling)?
3. The modern trend is to replace pooling with strided convolutions. What
is the argument for and against this?
13.4.
Exercises
Answer: Answer 14.1
(a) For a pool of size k with stride k (no overlap): the max over a k × k region
is unchanged if the maximum value shifts by less than k pixels within that
region.
Formally, if the input is shifted by (δm , δn ) with |δm |, |δn | < k , the
maximum value in a pool window is still selected (it may come from a slightly
dierent position, but the output value is the same if the same pixel remains
the maximum). This is exact invariance within the pooling window.
(b) Overlapping pooling (stride < pool size): adjacent pool windows share
elements. A shift by 1 pixel moves the input into a dierent overlapping window, potentially changing which pool window captures the max. Invariance
is weaker but output changes more gradually.
(c) Strided convolution (for dimension reduction): for: the network can learn
optimal downsampling (rather than xed max or average); richer representation.
Against: strided conv without prior smoothing causes aliasing (vio-
lates Nyquist). Additionally, max pooling provides stronger local translation
invariance than strided conv. Empirically, modern architectures (ResNet with
stride-2 conv, MobileNet) nd that learned downsampling performs as well as
pooling when the network is large enough.
75
Chapter 14
Activation Functions
14.1 Necessity of Non-Linearity
Without activation functions, stacking L linear layers is equivalent to a single linear
layer:
WL (WL−1 (· · · W1 x)) = (WL · · · W1 ) x.
|
{z
}
W
Non-linear activations allow the network to compute non-linear functions.
14.2 Key Activation Functions
Sigmoid:
σ(z) =
Problem:
1
,
1 + e−z
vanishing gradient.
For
σ ′ (z) = σ(z)(1 − σ(z)).
(14.1)
|z| > 4, σ ′ (z) < 0.02 gradients vanish
through many layers.
Tanh:
tanh(z) =
ez − e−z
,
ez + e−z
tanh′ (z) = 1 − tanh2 (z).
(14.2)
Zero-centred (better than sigmoid) but still suers from vanishing gradients.
ReLU (Rectied Linear Unit):
ReLU(z) = max(0, z),
d ReLU
= 1[z > 0].
dz
(14.3)
Key properties: (1) No vanishing gradient for positive inputs. (2) Sparse activations (0 for negative inputs) ecient. (3) Biological plausibility (roughly models
neuron ring threshold). Problem:
dying ReLU neurons that output 0 for all
76
14.3.
Exercises
77
training inputs receive no gradient and never recover.
Leaky ReLU / PReLU:
z
f (z) =
αz
z>0
,
α = 0.01 (Leaky ReLU) or learned (PReLU).
(14.4)
z≤0
GELU (Gaussian Error Linear Unit):
GELU(z) = z · Φ(z) ≈ 0.5z
1 + tanh
p
2/π(z + 0.044715z 3 ) ,
(14.5)
where Φ is the standard Gaussian CDF. GELU is smooth everywhere and is the
default in Transformers and ConvNeXt.
14.3 Exercises
Exercise 15.1 Activation Functions
1. Prove that a network with sigmoid activations and L layers has gradients
L
that shrink by a factor of at most (1/4) . Why does this cause training
failure?
2. Why does ReLU not have the vanishing gradient problem for positive
activations?
3. The dying ReLU problem: a ReLU neuron receives a large negative
gradient update. Explain the failure mechanism step by step.
14.3.
Exercises
78
Answer: Answer 15.1
(a) σ ′ (z) = σ(z)(1 − σ(z)) ≤ 1/4 (maximum at z = 0). By the chain rule
QL
∂L
′
′
ℓ=1 σ (zℓ ) · Wℓ · ∂zL+1 . The product
ℓ σ (zℓ ) ≤
(1/4)L decays exponentially. For L = 10: (1/4)10 ≈ 10−6 . Early layer gradi-
through L layers:
∂L
∂z1
=
Q
ents become negligible those layers stop learning.
′
(b) ReLU (z) = 1[z > 0], which equals exactly 1 for positive activations (no
shrinkage) and 0 for negative (which does not multiply into the gradient chain
since the neuron is o ). The gradient magnitude is preserved exactly through
active neurons.
(c) Dying ReLU mechanism: (1) due to a large learning rate or large gradient
update, a weight vector w becomes such that w
⊤
x < 0 for all training exam⊤
ples x. (2) In the forward pass, this neuron outputs ReLU(w x) = 0 for all
∂ ReLU
= 1[z > 0] = 0 since z < 0. So the
inputs. (3) In the backward pass,
∂z
gradient w.r.t. w is zero. (4) The weights never receive any gradient signal
and remain stuck in the dead state the neuron is permanently deactivated.
Part IV
Phase 4: Architecture Evolution
79
Chapter 15
LeNet-5 (1998)
15.1 Problem Before It
In the 1990s, digit recognition (postal codes, bank checks) required hand-crafted
feature pipelines with multiple stages, each tuned manually. Systems were brittle
and domain-specic.
15.2 Core Insight
Yann LeCun proposed training a convolutional network
end-to-end with backprop-
agation letting the network learn features directly from pixel data.
15.3 Architecture
6×5×5
pool
pool
16×5×5
FC
FC
FC
32×32 −−−−→ 28×28×6 −−→ 14×14×6 −−−−→ 10×10×16 −−→ 5×5×16 −→ 120 −→ 84 −→ 10
Layer
Output size
# Params
Activation
Input
32 × 32 × 1
28 × 28 × 6
14 × 14 × 6
10 × 10 × 16
5 × 5 × 16
0
156
Tanh
12
Tanh
2,416
Tanh
32
Tanh
Conv1 (5 × 5, 6 lters)
AvgPool1 (2 × 2)
Conv2 (5 × 5, 16 lters)
AvgPool2 (2 × 2)
FC1
120
48,120
Tanh
FC2
84
10,164
Tanh
Output
10
850
Softmax
80
15.4.
Key Innovations
81
15.4 Key Innovations
1. End-to-end training: features and classier optimised jointly.
2. Local receptive elds + weight sharing: the rst practical demonstration
at scale.
3. Spatial subsampling (pooling): reduces spatial resolution progressively.
15.5 Limitations
Small capacity (60K params), sigmoid/tanh activations (vanishing gradients), computationally limited to small images. Could not scale to natural image complexity.
15.6 Exercises
Exercise 16.1 LeNet Analysis
1. Calculate the exact number of parameters in each LeNet-5 layer and
verify the totals in the table.
2. LeNet used average pooling. Explain why modern networks prefer max
pooling or strided convolution.
3. What would happen if you applied LeNet directly to 224×224 ImageNet
images? Calculate the output size after each layer.
15.6.
Exercises
82
Answer: Answer 16.1
(a) Conv1: 5 × 5 × 1 × 6 + 6 = 156. Pool1: trainable scale+bias per channel:
6 × 2 = 12. Conv2: 5 × 5 × 6 × 16 + 16 = 2416. Pool2: 16 × 2 = 32.
FC1: 400 × 120 + 120 = 48120. FC2: 120 × 84 + 84 = 10164. Output:
84 × 10 + 10 = 850. Total: ≈ 61,706.
(b) Max pooling: selects the most dominant activation (detects presence of
feature, not average response).
Average pooling can dilute a strong activa-
tion across a region. Modern networks use strided conv because it can learn
arbitrary downsampling, not just xed statistics.
(c) 224 × 224 →(Conv15 × 5)→ 220 × 220 × 6 →(AvgPool)→ 110 × 110 ×
6 →(Conv2)→ 106 × 106 × 16 →(AvgPool)→ 53 × 53 × 16. Then FC1 input:
53×53×16 = 44,944 units vs original 400. FC1 params: 44,944×120 = 5.4M
already 100x more, and the convolutional stack would be far too shallow
relative to the image size. The network would essentially learn global statistics
over the whole image rather than hierarchical features.
Chapter 16
AlexNet (2012)
16.1 The Problem
ImageNet (1000 classes, 1.2M images) was the rst large-scale challenge. No system
could handle this diversity. The best 2011 systems used hand-crafted features (Fisher
vectors, SIFT, HOG) with SVMs, achieving ∼28% top-5 error.
16.2 Core Insight
Alex Krizhevsky, Ilya Sutskever, and Georey Hinton trained a deep CNN on two
GPUs with several critical innovations, achieving 16.4% top-5 error a 12-point
absolute improvement. This single result launched the deep learning revolution.
16.3 Architecture
11 × 11, s = 4 → 5 × 5 → 3 × 3 → 3 × 3 → 3 × 3 → FC(4096) → FC(1000)
| {z }
| {z }
| {z }
| {z }
|
{z
}
| {z }
| {z }
Conv1
Conv2
Conv3
Conv4
Conv5
×2
Softmax
(16.1)
16.4 Key Innovations
1. ReLU:
Replaced tanh with ReLU. Result: 6× faster training convergence due
to no vanishing gradient.
2.
Multi-GPU training:
Split the network across 2 GPUs with cross-GPU
connections at specic layers.
83
16.5.
Exercises
84
3. Data augmentation:
Random crops (224×224 from 256×256) and horizontal
ips multiplied training set by 2048×, dramatically reducing overtting.
4. Dropout:
Applied to FC layers with p = 0.5. For each training forward pass,
randomly zero 50% of FC activations. This acts as training an exponential ensemble
of networks.
Key Insight: Why Dropout Works The Ensemble View
n
With n neurons, there are 2 possible subnetworks. Dropout samples a different subnetwork at each training step. At test time, using all weights scaled
by (1 − p) approximates the ensemble average.
This is the most powerful
regularisation technique discovered for large FC layers.
5. Local Response Normalisation (LRN):
Normalises responses across ad-
jacent channels, mimicking lateral inhibition in biology. Later shown to be largely
unnecessary.
6. Overlapping pooling:
3×3 pool with stride 2 (vs non-overlapping). Marginal
accuracy improvement.
16.5 Exercises
Exercise 17.1 AlexNet Innovations
1. Why does ReLU lead to faster training convergence than tanh? Provide
a mathematical explanation involving gradient ow.
2. Dropout is described as training an ensemble. If FC1 has 4096 neurons
and dropout
p = 0.5, how many distinct subnetworks are implicitly
trained? Is this computationally feasible?
3. The top-5 error dropped from 26.2% to 16.4% a 40% relative reduction. Why was this historically signicant?
16.5.
Exercises
85
Answer: Answer 17.1
(a) Tanh: gradient ≤ 1 everywhere, ≈ 0 for large |z|. Through L layers, gradient shrinks as
Q
′
ℓ tanh (zℓ ) ≤ 1 but practically very small. ReLU: gradient
is exactly 1 for positive inputs no shrinkage. Additionally, tanh requires
2z
computing e
(expensive); ReLU is a thresholding operation (trivial). Empirically, ReLU converges ∼ 6× faster on CIFAR-10 as reported by Krizhevsky.
(b) 24096 ≈ 101233 possible subnetworks. This is astronomically large far
beyond any computational feasibility. Dropout samples from this space implicitly, training each sub-network with the shared weights. The ensemble is
free it comes from the weight sharing across all subnetworks.
(c) The prior best method used hand-crafted features (Fisher vectors, HOG,
SIFT). The 40% relative improvement showed that
learned features massively
outperformed the best decades of manual feature engineering.
It demon-
strated: (1) deep networks can be trained on large-scale data, (2) GPUs unlock
this scale, (3) representation learning is superior to feature engineering. This
catalysed the entire eld to pivot to deep learning.
Chapter 17
VGGNet (2014)
17.1 Core Insight
If AlexNet used 11×11 and 5×5 kernels, why not use only 3×3 kernels everywhere?
Two stacked 3 × 3 convolutions have the same receptive eld as one 5 × 5 convolution, but fewer parameters:
2 × 32 = 18
vs
52 = 25,
saving 28% per channel.
(17.1)
Three stacked 3 × 3 convolutions = one 7 × 7 convolution (receptive eld), with
3 × 9 = 27 vs 49 parameters (45% fewer).
Moreover, two 3×3 layers with ReLU in between provide more non-linearities
than one 5 × 5 layer increasing representational capacity.
17.2 Architecture
VGG-16 stacks 13 conv layers (all 3×3) + 3 FC layers. The spatial resolution halves
after each of 5 max-pool stages, while channel depth doubles:
64 → 128 → 256 →
512 → 512.
17.3 Legacy
The principle use small kernels, add depth became the dominant design paradigm.
VGG features became the de-facto transfer learning backbone for years.
86
17.4.
Limitation
87
17.4 Limitation
138 million parameters (mostly in FC layers).
Three FC layers at the end con-
tribute ∼100M parameters for minimal gain. VGG-16 requires ∼500MB of storage
impractical for mobile deployment.
17.5 Exercises
Exercise 18.1 VGG Design Principle
1. Prove that two 3 × 3 conv layers have the same receptive eld as one
5 × 5 conv layer, and compare parameter counts for C input and C
output channels.
2. VGG-16's three FC layers together have ≈ 122M parameters, while the
conv stack has only ≈ 15M. What does this tell you about the bottleneck,
and how does modern pooling (GAP) address it?
3. Derive the output size of a 224 × 224 image through VGG-16's convolutional body (show sizes after each block).
Answer: Answer 18.1
(a) RF of two 3 × 3 layers: 1 + (3 − 1) + (3 − 1) = 5. RF of one 5 × 5: 5. Equal.
2
2
Parameters: Two 3 × 3 layers with C channels each: 2 × 3 × C × C = 18C .
2
2
One 5 × 5 with C channels: 25C . Saving: 7C or 28%.
(b)
The
FC
layers
25088×4096+4096×4096≈119M)
(≈
are
122M
the
params,
overwhelming
of
majority
which
of
pa-
rameters. They classify from the 7 × 7 × 512 convolutional feature map but
do not re-use weights across spatial positions one set of weights for one
spatial arrangement of features. Global Average Pooling replaces FC layers
by collapsing the 7 × 7 × 512 map to a 512-vector before classication, using
only 512 × 1000 ≈ 512K params a 230× reduction.
(c) VGG-16 blocks: Block1: 2×conv+pool:
224 → 224 → 112. Block2:
2×conv+pool: 112 → 56.
Block3: 3×conv+pool: 56 → 28.
Block4:
3×conv+pool: 28 → 14. Block5: 3×conv+pool: 14 → 7. Final: 7 × 7 × 512.
Chapter 18
GoogLeNet / Inception (2014)
18.1 Core Problem
Deeper and wider networks are better, but depth and width both cost parameters.
How do we build a very powerful network without proportionally more parameters?
18.2 The Inception Module
Instead of choosing between 1 × 1, 3 × 3, or 5 × 5 convolutions at each layer, apply
all of them in parallel and concatenate the results:
i
h
(a)
(b)
(c)
Inception(x) = Concat W1×1 ∗x, W3×3 ∗(W1×1 ∗x), W5×5 ∗(W1×1 ∗x), MaxPool∗W1×1
(18.1)
The 1 × 1 convolutions before the 3 × 3 and 5 × 5 are bottleneck layers: they
reduce the channel depth before the expensive spatial convolutions, dramatically
cutting FLOPs.
1 × 1 convolution = learned channel mixing. A 1 × 1 conv mixes channels
linearly at each spatial location. It changes Cin channels to Cout channels with
only Cin × Cout parameters and no spatial processing. Used to reduce channels
(bottleneck) before expensive 3 × 3 or 5 × 5 convolutions.
18.3 Key Insight: Multi-Scale Processing
Visual recognition requires processing at multiple scales simultaneously. The inception module is an approximate implementation of a sparse, multi-scale convolutional
88
18.4.
GoogLeNet Architecture
89
architecture. Dierent neurons specialise in dierent scales automatically through
training.
18.4 GoogLeNet Architecture
22 layers deep, 6.8M parameters (12× fewer than AlexNet with better accuracy).
Uses auxiliary classiers at intermediate depths to inject gradient signal into early
layers.
18.5 Exercises
Exercise 19.1 Inception Module
1. An inception module takes a 28 × 28 × 192 input. The 3 × 3 branch has
a 1 × 1 bottleneck reducing to 96 channels before the 3 × 3. Compute
the FLOPs for the 3 × 3 branch with and without the bottleneck.
2. Why does concatenating multi-scale features (from 1 × 1, 3 × 3, 5 × 5)
provide a better representation than any single scale?
3. What is the purpose of the auxiliary classiers in GoogLeNet? Explain
from the perspective of vanishing gradients.
Answer: Answer 19.1
(a) Without bottleneck (direct 3 × 3, 192 → 192): FLOPs = 32 × 192 × 192 ×
28×28 ≈ 83M. With bottleneck (192 → 96 via 1×1, then 96 → 192 via 3×3):
1 × 1: 192 × 96 × 28 × 28 ≈ 14.5M; 3 × 3: 9 × 96 × 192 × 28 × 28/2 ≈ 41M.
Total≈ 55.5M. Reduction: 83 → 55.5M, saving ≈ 33%.
(b) Some visual cues are ne-grained (texture: 1 × 1, 3 × 3) while others
are coarse (shape: 5 × 5). A single xed scale cannot capture both. By
concatenating multi-scale features, each subsequent layer can access both local
texture information and wider context simultaneously, enabling richer pattern
recognition.
(c) GoogLeNet is 22 layers deep. With only the nal softmax, gradients from
the loss must backpropagate through all 22 layers shrinking at each layer.
Auxiliary classiers at layers 4 and 7 add additional loss terms (×0.3 weight)
that inject gradients directly into the intermediate layers, partially bypassing
the long backprop chain.
In modern architectures, BatchNorm + ResNet
connections make this unnecessary.
Chapter 19
ResNet (2015)
19.1 The Degradation Problem
Adding more layers to a plain network
hurts training accuracy not just test accu-
racy. This is not overtting (training error also increases). Somehow, optimisation
becomes harder in deeper networks.
Key Insight: The Paradox
A 56-layer plain network should at least match a 20-layer network, because
the extra 36 layers could learn identity mappings. Yet empirically, the 56-layer
network performs worse than the 20-layer one. The network fails to learn the
identity optimisation fails.
19.2 Core Insight: Residual Learning
Instead of learning a mapping H(x) directly, learn the residual F(x) = H(x) − x,
and add the input back:
y = F(x, {Wi }) + x.
(19.1)
The identity mapping is now trivially achievable: set F = 0 (push all weights towards
zero). This makes the trivial solution easy to reach, and any improvement is on
top of it.
19.3 Why Residual Connections Help Gradient Flow
The gradient of the loss w.r.t. the input of a residual block is:
∂L
∂L ∂y
∂L
=
·
=
∂x
∂y ∂x
∂y
90
∂F
1+
.
∂x
(19.2)
19.4.
The Bottleneck Block
91
Key observation: Even if ∂F/∂x ≈ 0 (the residual branch does nothing useful), the gradient ∂L/∂x = ∂L/∂y ows through unchanged via the skip connection.
No vanishing gradient from the skip path.
19.4 The Bottleneck Block
For deeper networks (ResNet-50+), each block uses a bottleneck:
1×1
3×3
1×1
256 −−→ 64 −−→ 64 −−→ 256
Parameters: 256 × 64 + 64 × 9 × 64 + 64 × 256 = 16,384 + 36,864 + 16,384 = 69,632.
Compare to two 3 × 3 layers: 2 × 9 × 256 × 256 = 1,179,648 17× more expensive.
19.5 Exercises
Exercise 21.1 Residual Connections
1. Through a sequence of L residual blocks xL = x0 +
PL
ℓ=1 Fℓ (xℓ−1 ), derive
the gradient ∂L/∂x0 and show it never vanishes due to skip connections.
2. Why is the plain network's failure to learn identity mappings a problem
with the
optimiser, not the model capacity ?
3. Describe the dierence between ResNet-34 (basic blocks) and ResNet-50
(bottleneck blocks). When would you prefer each?
19.5.
Exercises
92
Answer: Answer 21.1
(a) From He et al.: xL = x0 +
PL−1
ℓ=0 Fℓ (xℓ ). Then:
∂L
∂L ∂xL
∂L
=
·
=
∂x0
∂xL ∂x0
∂xL
!
∂ X
1+
Fℓ .
∂x0 ℓ
∂L
ows directly to x0 without passing through any weight
∂xL
∂L
matrix or activation. Even if the second term vanishes, the gradient is
̸= 0.
∂xL
The rst term
No vanishing gradient from the skip path, regardless of depth.
(b) The plain 56-layer network has sucient capacity to represent the 20-layer
solution (the extra 36 layers simply learn identities). The problem is that SGD
with gradient descent struggles to nd this solution in a high-dimensional loss
landscape with many saddle points.
Residual connections reshape the loss
landscape to make the identity solution a local attractor the problem is
xed by changing the parameterisation, not the capacity.
(c) ResNet-34 uses basic blocks (3 × 3, 3 × 3): fewer FLOPs per block, less
memory overhead, faster in practice for smaller channel counts.
ResNet-50
uses bottleneck blocks (1 × 1, 3 × 3, 1 × 1): more ecient at 256+ channels,
allows building deeper networks at lower FLOPs. Prefer ResNet-34 for small/medium problems with tight compute budgets; ResNet-50+ for large-scale
tasks where depth and capacity matter.
Chapter 20
DenseNet (2017)
20.1 Core Insight: Dense Connectivity
DenseNet extends the ResNet idea:
instead of adding only the previous layer's
output, connect every layer to every subsequent layer:
xℓ = Hℓ [x0 , x1 , . . . , xℓ−1 ]
(20.1)
where [·] denotes channel concatenation.
Benets:
Feature reuse: shallow features are available to all deeper layers without
re-learning.
Stronger gradient ow: direct connections to all previous layers provide
multiple gradient paths.
Parameter eciency: each layer is narrow (growth rate k = 1232 channels)
because it receives all previous features.
Implicit deep supervision: the loss gradient reaches every layer directly.
20.2 Growth Rate Analysis
If each dense layer produces k channels, and the input has k0 channels, the ℓ-th layer
receives k0 + k(ℓ − 1) input channels. Total parameters in a dense block of L layers:
L
X
k 2 L2
.
Params ≈
(k0 + k(ℓ − 1)) · k ≈
2
ℓ=1
93
20.3.
Exercises
94
With k = 32 and L = 12: ≈ 73,728 parameters vs much more for equivalent ResNet
block.
20.3 Exercises
Exercise 22.1 DenseNet Connectivity
1. A dense block has L = 6 layers and growth rate k = 12, with 64 input
channels. List the input channel count for each layer.
2. Why does DenseNet use 1 × 1 bottleneck convolutions before each 3 × 3
conv (DenseNet-BC)?
3. Compare:
ResNet and DenseNet both address vanishing gradients.
What is the architectural and philosophical dierence?
Answer: Answer 22.1
(a) Layer 1: 64 channels in. Layer 2: 64 + 12 = 76. Layer 3: 76 + 12 = 88.
Layer 4:
88 + 12 = 100. Layer 5: 100 + 12 = 112. Layer 6: 112 + 12 = 124
channels in. Each layer produces 12 channels out.
(b) At layer ℓ, the input has k0 + k(ℓ − 1) channels, which grows with depth.
The 3×3 conv on 100+ channels is expensive. The 1×1 bottleneck (DenseNetBC) rst reduces to 4k channels before the 3 × 3 conv, capping the cost at
4k · 9 · k regardless of how many previous layers contributed.
(c) ResNet adds the residual: y = x + F(x), which propagates gradients
summation. Features from dierent depths are mixed. DenseNet concatenates : y = [x0 , . . . , xℓ−1 , F(·)], preserving all features separately. Philosoph-
by
ically: ResNet renes a single representation; DenseNet maintains a growing
collection of all intermediate representations.
DenseNet achieves better pa-
rameter eciency by forcing explicit feature reuse.
Chapter 21
EcientNet (2019)
21.1 The Scaling Problem
How do you scale a network more depth, more width, or higher resolution? These
three dimensions trade o accuracy against computation. Previous work scaled only
one dimension at a time arbitrarily.
21.2 Compound Scaling
EcientNet uses a compound coecient ϕ to scale all three dimensions simultaneously:
subject to α · β
2
depth:
d = αϕ
(21.1)
width:
w = βϕ
(21.2)
resolution:
r = γϕ
(21.3)
· γ 2 ≈ 2 (so that total FLOPs ≈ 2ϕ × baseline).
Optimal base coecients
found by grid search on the baseline network: α = 1.2,
β = 1.1, γ = 1.15.
21.3 MBConv: The Building Block
EcientNet uses MBConv (Mobile Inverted Bottleneck Convolution):
1×1
DWConv 3×3
1×1
Cin −−→ 6Cin −−−−−−−→ 6Cin −−→ Cout
95
21.4.
Exercises
96
with a squeeze-and-excitation (SE) module between the DW conv and the output
projection. SE globally pools the feature map, passes through two FC layers, and
produces a channel-wise attention vector to recalibrate activations.
21.4 Exercises
Exercise 23.1 EcientNet Scaling
1. If ϕ = 1, compute the depth, width, and resolution scaling factors using
EcientNet's coecients.
2. Why is it important that the compound constraint is α · β 2 · γ 2 ≈ 2
rather than α · β · γ ≈ 2?
3. Explain the Squeeze-and-Excitation module mathematically and describe what problem it solves.
Answer: Answer 23.1
d = 1.21 = 1.2, w = 1.11 = 1.1, r = 1.151 = 1.15. Check:
1.2 × 1.12 × 1.152 = 1.2 × 1.21 × 1.3225 ≈ 1.92 ≈ 2. ✓
(b) FLOPs of a conv layer scale as width2 ×resolution2 (width enters twice:
input channels × output channels; resolution enters twice: H × W ). FLOPs
2 2
ϕ
2 2
are proportional to w r for xed depth. For a factor 2 in FLOPs: d·w ·r ≈
2ϕ , which at ϕ = 1 requires α · β 2 · γ 2 ≈ 2.
P
1
(c) SE module: (1) Squeeze: zc = HW
m,n Fc [m, n] global average pool
to a C -vector. (2) Excitation: s = σ(W2 · δ(W1 · z)) two FC layers with
bottleneck ratio r = 16, producing a C -vector of channel attention weights in
[0, 1]. (3) Rescale: F̃c = sc · Fc scale each channel map by its attention
(a) ϕ = 1:
weight. Problem solved: standard conv treats all channels equally. SE allows
the network to learn which channels are most informative for the current input,
providing dynamic channel-wise attention.
Chapter 22
ConvNeXt (2022)
22.1 The Question
Vision Transformers (ViT) began outperforming CNNs on ImageNet in 2021. The
can we modernise a ResNet using only standard convolutions to match ViT performance?
ConvNeXt paper asked:
22.2 Key Design Changes
Starting from ResNet-50 and applying incremental changes:
Modication
Accuracy gain
Source
Training recipe (AdamW, 300 epochs, etc.)
+2.7%
ViT recipe
7 × 7 depthwise conv (large kernel)
+0.1%
Swin Transformer
Inverted bottleneck
+0.1%
MobileNetV2
1 × 1 conv as pointwise (×4 width)
+0.3%
Transformer MLP
Fewer activations (one per block)
+0.2%
Transformer design
Fewer normalisation layers
+0.1%
Transformer design
BatchNorm → LayerNorm
+0.1%
Transformer design
Separate downsampling layers
+0.4%
Swin
Total:
ResNet-50 (76.1%) → ConvNeXt-T (82.1%), matching Swin-T.
22.3 The ConvNeXt Block
7×7
DWConv LN 1×1 (×4) GELU 1×1 (×1/4)
x −−−−−−−→−→−−−−−→−−−→−−−−−−→ +x
97
22.4.
Exercises
98
22.4 Exercises
Exercise 24.1 ConvNeXt Design Decisions
1. Why does moving to a 7 × 7 depthwise conv (from 3 × 3) increase expressiveness without greatly increasing parameters?
2. ConvNeXt uses LayerNorm instead of BatchNorm. Explain the dierence and why LayerNorm is preferred in this architecture.
3. Transformers use an MLP with 4× expansion in the FFN. ConvNeXt
mimics this with 4× channel expansion in the pointwise layers. What is
the connection?
Answer: Answer 24.1
(a) Depthwise conv has only K 2 × C parameters (one kernel per channel).
Changing K from 3 to 7:
9C → 49C params 5.4× more but since
depthwise convolutions are already very cheap (no channel mixing), the absolute cost is modest.
Meanwhile, the larger 7 × 7 kernel provides a larger
eective receptive eld per layer (RF=7 vs RF=3), capturing more context at
each depth level.
(b) BatchNorm normalises over the batch dimension:
x̂b,c,h,w = (xb,c,h,w −
µc )/σc where µc , σc are over the batch. Requires a large batch to be stable,
and has dierent training/inference behaviour.
LayerNorm normalises over
the channel dimension for each sample independently: x̂c = (xc − µ)/σ where
µ, σ are over channels. Has identical training/inference behaviour, works with
batch size 1, and aligns with Transformer conventions (Transformers almost
exclusively use LayerNorm). ConvNeXt adopts LayerNorm to align the normalisation regime with Transformers and enable more stable training.
4d
d
(c) The Transformer FFN block is: input (dim d) −
→ GELU →
− . This is a
1 × 1 conv with 4× expansion followed by projection back exactly what
ConvNeXt implements as the pointwise layers around the depthwise conv.
The connection is direct: ConvNeXt's block is architecturally analogous to a
Transformer block where the self-attention is replaced by a large depthwise
conv.
Part V
Phase 5: Modern Paradigms
99
Chapter 23
Vision Transformers (ViT)
23.1 The Core Idea
What if images could be processed like sequences of tokens, using the self-attention
mechanism from NLP?
Patch tokenisation.
Divide the H × W × C image into non-overlapping P × P
patches:
N=
Each patch is attened to a P
2
HW
P2
patches.
(23.1)
C -dimensional vector and linearly projected to di-
mension D : the patch embedding.
A learnable [CLS] token is prepended, and positional embeddings are added:
Z0 = [xcls ; xp1 E; . . . ; xpN E] + Epos ,
2
E ∈ R(P C)×D , Epos ∈ R(N +1)×D .
(23.2)
23.2 Self-Attention in Images
For each pair of patches (i, j), the attention score measures how relevant patch j
is to computing the new representation of patch i:
Attention(Q, K, V) = softmax
QK⊤
√
dk
V,
(23.3)
N ×dk
where Q, K, V ∈ R
are linear projections of the patch embeddings.
Global receptive eld from layer 1.
Unlike CNNs,
attend to every other patch simultaneously.
dierence ViTs have O(N
2
every ViT layer can
This is the key architectural
) interactions per layer while CNNs have O(N ) (local
only).
100
23.3.
The Full ViT Block
101
23.3 The Full ViT Block
Z′ℓ = MSA(LN(Zℓ−1 )) + Zℓ−1
(23.4)
Zℓ = MLP(LN(Z′ℓ )) + Z′ℓ
(23.5)
MSA = Multi-Head Self-Attention, MLP = 2-layer FC network with GELU.
23.4 ViT Complexity Analysis
Self-attention FLOPs per layer:
CNN (conv layer) FLOPs per layer:
For large images (high N ), the N
with P
2
O(N 2 D) (N = HW/P 2 )
(23.6)
O(N K 2 C 2 )
(23.7)
term becomes prohibitive. A 224 × 224 image
= 16 gives N = 196 manageable. But P = 4 gives N = 3136 16×
more attention computations.
23.5 CNN vs Transformer: The Core Trade-o
Property
CNN
ViT
Inductive biases
Locality, translation equivariance
None (learned from data)
Receptive eld
Grows with depth
Global from layer 1
Data eciency
High (works well with less data)
Low (needs ∼14M+ images)
Scalability
Saturates earlier
Scales better with data/compute
2
Computation
O(N KC ) per layer
Spatial resolution
Preserved or halved
O(N 2 D) per layer
Fixed (N patches)
23.6 When to Use CNN vs Transformer
Small datasets (< 100K images): Use CNN (stronger inductive biases, less
data needed to generalise).
Large-scale pretraining + ne-tuning: ViT dominates (scales better with
data and compute).
Dense prediction (segmentation, detection):
Transformer (hierarchical ViT with local attention).
Hybrid models or Swin
23.7.
Exercises
102
Mobile/edge deployment: CNN (MobileNet, EcientNet) attention is
computationally expensive.
23.7 Exercises
Exercise 25.1 Vision Transformers
1. A 224 × 224 RGB image is processed by ViT-B/16 (patch size 16). How
many patches are there?
What is the dimension of each patch token
before projection?
2. Derive the scaled dot-product attention formula and explain why the
√
dk scaling is necessary.
3. ViT requires massive datasets (JFT-300M) to match CNN performance.
Explain this from the perspective of inductive biases.
Answer: Answer 25.1
(a) N = (224/16)2 = 142 = 196 patches. Each patch is 16 × 16 × 3 = 768
dimensional before projection.
√
(b) Attention(Q, K, V ) = softmax(QK ⊤ /
dk )V . The scores QK ⊤ have entries with variance proportional to dk (each is a dot product of dk random
values). Without scaling, large dk leads to extreme softmax inputs the
√
dk
softmax saturates to near one-hot, giving near-zero gradients. Scaling by
normalises the variance to ∼ 1, keeping the softmax in its gradient-sensitive
regime.
(c) CNNs encode locality and translation equivariance as hard constraints
in their architecture.
These match the statistics of natural images, so few
examples are needed to learn good features. ViT has
no such constraints it
must learn from data that (1) nearby patches are more correlated than distant
ones and (2) patterns repeat across positions.
With insucient data, ViT
learns spurious attention patterns. With 300M+ images, it learns these priors
implicitly from statistics, at which point it can leverage its global attention
to capture long-range dependencies that CNNs miss.
Part VI
Phase 6: CV Tasks
103
Chapter 24
Image Classication
24.1 Formulation
Denition: Image Classication
Given an image x ∈ R
H×W ×C
and a label set Y = {1, . . . , K}, learn fθ : x 7→ y
minimising expected risk R(f ) = E(x,y) [ℓ(f (x), y)].
24.2 Cross-Entropy Loss Derivation
K
The CNN outputs logits z ∈ R . Applying softmax gives probabilities:
ezk
pk = PK
j=1 e
zj
.
(24.1)
The cross-entropy loss is the negative log-likelihood of the true class y :
LCE = − log py = −zy + log
K
X
ezj .
(24.2)
j=1
Gradient:
∂LCE
= pk − 1[k = y].
∂zk
(24.3)
This is beautifully simple: push the probability of the correct class up (gradient
= py − 1 < 0) and push all others down (gradient = pk > 0).
104
24.3.
Label Smoothing
105
24.3 Label Smoothing
Instead of hard labels yk = 1[k = true class], use soft labels:
ỹk = (1 − ϵ)1[k = true] + ϵ/K.
(24.4)
This prevents the model from being overcondent (logit magnitudes growing too
large), improving calibration and generalisation (ϵ = 0.1 is typical).
24.4 Exercises
Exercise 26.1 Classication Loss
1. Derive the gradient of cross-entropy loss w.r.t. the logit vector z in full.
2. Show that minimising cross-entropy is equivalent to maximising the likelihood under a categorical distribution.
3. What does the temperature parameter T do in pk = ezk /T /
P
je
zj /T
?
How does it aect uncertainty estimates?
Answer: Answer 26.1
(a) L = −zy + log
zj
je .
P
For
k ̸= y :
∂L
∂zk
z
= Pe ekzj = pk .
j
∂L
∂L
= −1 + py . Combined: ∂z
= pk − 1[k = y].
∂zy
k
P zj
ezy
(b) Maximising log p(y|x; θ) = log P ezj = zy − log
je
j
For
k = y:
= −LCE .
So
minimising LCE maximises the log-likelihood. ✓
(c) High T : softens the distribution towards uniform (all pk ≈ 1/K ) high
uncertainty/entropy, more exploratory.
Low
T:
sharpens towards one-hot
T > 1 (temperature scaling) is used to
calibrate overcondent models. In knowledge distillation, high T encourages
high condence.
At test time,
the student to match the teacher's soft probability distribution.
Chapter 25
Object Detection
25.1 Problem Formulation
Object detection outputs bounding boxes {(xi , yi , wi , hi , ci )} centre, width, height,
and class for each detected object. Unlike classication, there can be
at unknown locations.
multiple objects
25.2 Key Concepts
Intersection over Union (IoU):
IoU(A, B) =
|A ∩ B|
.
|A ∪ B|
(25.1)
A detection is a true positive if IoU with the ground-truth box exceeds a threshold
(typically 0.5).
Anchor boxes.
Fixed reference boxes of various scales and aspect ratios tiled over
the image. The network predicts
osets from anchors to ground-truth boxes:
tx = (x − xa )/wa ,
ty = (y − ya )/ha
(25.2)
tw = log(w/wa ),
th = log(h/ha ).
(25.3)
Using log-scale for width/height ensures the prediction is always positive.
25.3 Two-Stage vs One-Stage Detectors
Two-stage (Faster R-CNN):
1. Region Proposal Network (RPN): proposes candidate object regions.
106
25.4.
Loss Function for Detection
107
2. RoI pooling: extracts features for each proposal.
3. Classication + regression head for each proposal.
Accurate but slower (∼ 10 FPS).
One-stage (YOLO, SSD):
Directly regress bounding boxes and class probabil-
ities from a grid over the feature map in a single forward pass. Faster (> 30 FPS)
but historically less accurate (now competitive).
25.4 Loss Function for Detection
Ldet = Lcls + λ Lreg
(25.4)
cls is cross-entropy over positive + negative anchors, and Lreg is smooth-L1
where L
loss (Huber loss) over the box regression osets for positive anchors only.
25.5 Exercises
Exercise 27.1 Object Detection
1. Given a 13 × 13 feature map with 5 anchors per cell and 80 classes
(YOLO-style), how many total predictions does the network make per
image?
2. Explain why log-scale is used for width/height regression but linear scale
is used for centre oset.
3. Non-maximum suppression (NMS): describe the algorithm and the role
of the IoU threshold.
25.5.
Exercises
108
Answer: Answer 27.1
(a) Each cell predicts 5 boxes, each with 4 coordinates + 1 objectness score
+ 80 class probabilities = 85 values. Total:
13 × 13 × 5 = 845 boxes, 13 ×
13 × 5 × 85 = 71,825 prediction values.
(b) Width/height in log-scale: the anchor has a xed wa , ha . If we predict
tw = w/wa linearly, small boxes (e.g., tw = 0.1) and large boxes (tw = 10)
have very dierent gradient magnitudes, making training unstable. Using tw =
log(w/wa ): the prediction is symmetric around tw = 0 (meaning predicted =
anchor), and equal absolute changes in tw correspond to equal relative size
changes. Centre osets are bounded in [0, 1] (cell normalised), so linear is
ne.
(c) NMS algorithm: (1) Sort all predicted boxes by condence score (descending). (2) Take the highest-condence box; add to nal detections. (3)
Remove all remaining boxes with IoU > threshold (e.g., 0.5) with the selected
box (these likely detect the same object). (4) Repeat from step 2 on remaining boxes until none remain. The IoU threshold trades recall (low threshold
removes more boxes, might miss detections) vs precision (high threshold keeps
duplicates).
Chapter 26
Semantic Segmentation
26.1 Problem Formulation
Assign a class label to
every pixel : f : RH×W ×C → {1, . . . , K}H×W .
26.2 Fully Convolutional Networks (FCN)
Replace all FC layers with convolutional layers. The output is a K -channel score
map at reduced resolution, then upsampled to full resolution via:
Bilinear interpolation: simple, no learned parameters.
Transposed convolution (deconv): learned upsampling.
Skip connections in FCN:
Fuse low-level (high-resolution, low-semantic) fea-
tures with high-level (low-resolution, high-semantic) features to recover ne spatial
detail.
26.3 U-Net Architecture
U-Net's encoder-decoder with skip connections is the dominant segmentation architecture:
Encoder: Standard conv+pool stages, progressively reducing spatial resolution.
Decoder: Transposed conv to upsample, with skip connections concatenating
encoder features at each resolution.
Loss: Pixel-wise cross-entropy or Dice loss.
109
26.4.
Exercises
110
Dice loss:
P
2 i ŷi yi
P .
LDice = 1 −
=1− P
|Ŷ | + |Y |
i ŷi +
i yi
2|Ŷ ∩ Y |
(26.1)
Better than cross-entropy for imbalanced segmentation (when the object occupies a
small fraction of pixels).
26.4 Exercises
Exercise 28.1 Segmentation
1. Why can't a standard classication CNN (VGG-16 with FC layers) be
used directly for pixel-wise segmentation?
2. Derive the gradient of Dice loss w.r.t. a predicted logit ŷi .
3. In U-Net, the skip connections concatenate encoder and decoder features.
What information does the encoder provide that the decoder
lacks?
Answer: Answer 28.1
(a) FC layers lose spatial information: a 7 × 7 × 512 feature map is attened
to a 25088-dim vector. The spatial locations of individual pixels are lost you cannot recover which output neuron corresponds to which input pixel.
Moreover, FC layers only work on xed input sizes. FCN replaces FCs with
convolutions, preserving spatial layout throughout.
(b) Let D =
P
i ŷi yi , P =
P
i ŷi , T =
P
i yi . Dice = 1 − 2D/(P + T ).
∂LDice
2yj (P + T ) − 2D
2D − 2yj (P + T )
=−
=
.
∂ ŷj
(P + T )2
(P + T )2
This naturally emphasises false negatives (where yj = 1 but ŷj is small) more
than false positives.
(c) After successive pooling, the decoder operates at low resolution and has
lost ne spatial details (exact boundary locations, thin structures). The encoder at the corresponding resolution has high-resolution feature maps that
preserve these ne details. Skip connections directly supply this spatial detail
to the decoder, allowing it to produce sharp boundaries rather than blurry
upsampled predictions.
Part VII
Phase 7: The Complete CV Pipeline
111
Chapter 27
Data: Acquisition, Preprocessing, and
Augmentation
27.1 The Data Flywheel
Key Insight:
In modern computer vision,
data quality and quantity often matters
more than architecture choice. A simple ResNet-50 trained on ImageNet21K typically outperforms an elaborate architecture trained on ImageNet-1K
alone.
27.2 Preprocessing Pipeline
Standard ImageNet preprocessing:
1. Resize shortest side to 256 pixels.
2. Random crop 224 × 224 (training) or centre crop 224 × 224 (validation).
3. Horizontal ip (training only, p = 0.5).
4. Normalise: subtract ImageNet mean [0.485, 0.456, 0.406], divide by std [0.229, 0.224, 0.225]
(per channel).
27.3 Data Augmentation
Standard geometric augmentations:
random crop, horizontal ip, random ro-
tation (±15), random scale.
112
27.4.
Exercises
Colour augmentations:
113
brightness, contrast, saturation, hue jitter (Random-
ColorJitter).
Advanced augmentations:
Mixup: x̃ = λxi +(1−λ)xj , ỹ = λyi +(1−λ)yj . Trains on convex combinations
of pairs.
CutMix: Replace a rectangular region of one image with the corresponding
region from another. Labels mixed proportionally to area.
RandAugment: Randomly apply N transforms from a xed set, each with
magnitude M . Strong regulariser for large models.
AutoAugment: Search for the optimal augmentation policy on a validation
set.
27.4 Exercises
Exercise 29.1 Data and Augmentation
1. Why is mean-subtraction and std-normalisation important? What problems does it solve for optimisation?
2. Describe the Mixup loss function and explain why training on convex
label combinations improves generalisation.
3. For a medical imaging dataset with severe class imbalance (99% negative, 1% positive), what augmentation and loss function strategies would
you apply?
27.4.
Exercises
114
Answer: Answer 29.1
(a) Without normalisation: if input pixel values are in [0, 255], the weight gradients in the rst layer are ∼ 255× larger than if inputs are in [0, 1], creating
poorly conditioned loss surfaces. Mean subtraction centres the data around
zero gradients are balanced in sign and magnitude.
Std normalisation
ensures each channel contributes equally regardless of its absolute range. Together, they make the loss landscape more spherical, allowing larger learning
rates and faster convergence.
(b) Mixup loss:
Lmix = λL(f (x̃), yi ) + (1 − λ)L(f (x̃), yj ).
By training on
interpolated images with proportional labels, the network learns smoother
decision boundaries it cannot place sharp class boundaries between training
examples. This acts as a strong regulariser and encourages predictions to be
proportional to class membership rather than hard-clipped.
Result: better
calibration and lower test error.
(c) Strategies: (1) Oversampling of the positive class (SMOTE or repeated
L = −w+ y log p̂ − w− (1 − y) log(1 − p̂)
with w+ /w− = 99 (inverse class frequency).
(3) Focal loss: Lfocal =
γ
−(1−p̂) y log p̂ down-weights easy negatives (the 99% majority) and focuses
sampling).
(2) Loss
reweighting:
learning on hard examples. (4) Augmentation of positive cases: aggressive
augmentation (rotation, ipping, colour jitter) to generate more positive training examples.
Chapter 28
Training: Optimisation and Regularisation
28.1 The Optimisation Problem
N
1 X
θ = arg min
L(fθ (xi ), yi ) + λR(θ)
N i=1
θ
∗
(28.1)
28.2 Stochastic Gradient Descent
θt+1 = θt − η∇θ Lmini-batch (θt )
(28.2)
vt+1 = µvt − η∇θ L
(28.3)
θt+1 = θt + vt+1
(28.4)
SGD with Momentum:
Momentum (µ = 0.9) accumulates gradient history, smoothing out oscillations and
accelerating along consistent gradient directions.
AdamW:
mt+1 = β1 mt + (1 − β1 )gt
(28.5)
vt+1 = β2 vt + (1 − β2 )gt2
(28.6)
m̂ = mt+1 /(1 − β1t+1 ), v̂ = vt+1 /(1 − β2t+1 )
m̂
θt+1 = θt − η √
− ηλθt
v̂ + ϵ
(28.7)
115
(28.8)
28.3.
Learning Rate Schedules
116
AdamW decouples weight decay from the adaptive learning rate (unlike Adam, which
conates them).
28.3 Learning Rate Schedules
Step decay: halve LR every k epochs.
Cosine annealing: ηt = ηmin + 12 (ηmax − ηmin )(1 + cos(πt/T )).
Warmup: start with very small LR for the rst few epochs, then ramp up.
Critical for large batch training (avoids gradient explosion at the start).
1-cycle policy: super-convergence technique combining warmup, cosine anneal, and nal decay.
28.4 Batch Normalisation
xi − µ B
x̂i = p 2
,
σB + ϵ
where
yi = γ x̂i + β
µB , σB2 are computed over the mini-batch.
Learnable scale
(28.9)
γ and shift β
restore representational capacity.
Why BN helps:
1. Reduces internal covariate shift each layer sees inputs with stable statistics.
2. Acts as a regulariser (adds noise via batch statistics similar eect to dropout).
3. Enables much higher learning rates.
4. Mitigates vanishing/exploding gradients.
28.5.
Exercises
117
28.5 Exercises
Exercise 30.1 Optimisation
1. Derive the bias-correction terms in Adam: why must we divide mt by
(1 − β1t ) and vt by (1 − β2t )?
2. Batch Normalisation has dierent behaviour at training and test time.
Describe the dierence and explain why it's necessary.
3. The learning rate warmup is critical for Transformers but less so for
small CNNs. Why?
Answer: Answer 30.1
(a) Initialise m0 = v0 = 0. After t steps: mt = (1 − β1 )
Pt
t−i
i=1 β1 gi . E[mt ] =
(1 − β1t )E[g] (geometric series). Without correction, mt is biased towards zero
t
t
especially in early steps (when β1 ≈ 1 is large). Dividing by (1 − β1 ) gives
E[m̂t ] = E[g] an unbiased estimate of the true gradient mean. Same logic
for vt .
2
are computed over the current mini-batch statistics
(b) Training: µB , σB
change each step, introducing stochastic noise (regularisation).
Test time:
using batch statistics is unreliable (batch might be small or single image).
Instead, running means and variances accumulated during training are used
(frozen):
µrunning = 0.9µrunning + 0.1µB . These give stable, deterministic nor-
malisation at inference.
(c) Large Transformers (ViT-L, ViT-H) have hundreds of millions of parameters and are initialised with small random weights. At the start of training,
gradients can be extremely large (many layers multiplied together), causing
instability. Warmup grows the learning rate from near-zero over ∼ 10K steps,
allowing the network to nd stable initial directions before full-speed updates.
Small CNNs (ResNet-50) have BatchNorm, which stabilises activations and
gradients from the start they are less sensitive to the initial learning rate.
Chapter 29
Evaluation, Debugging, and Deployment
29.1 Evaluation Metrics
Classication:
Top-1/Top-5 accuracy (ImageNet standard).
Confusion matrix for multi-class reveals per-class failure modes.
·R
for imbalanced problems.
F1-score = 2 PP+R
ROC AUC for binary classication.
Detection:
mAP (mean Average Precision): AP averaged over classes and IoU thresholds.
AP at IoU = 0.5 (PASCAL VOC) or 0.50.95 (COCO).
Segmentation:
mIoU (mean Intersection over Union): average IoU across all classes.
Dice coecient (equivalent to F1 for segmentation).
118
29.2.
The Debugging Framework
119
29.2 The Debugging Framework
Key Insight: Systematic Debugging in 5 Steps
1. Overt a single batch: If the model cannot t 816 training examples,
there is a code bug or an architectural issue.
2. Check loss at initialisation: For K -class classication, expected initial loss = log K . Deviations indicate wrong loss function or data issues.
3. Training vs validation gap: Large gap ⇒ overtting (add regularisation, more data). No gap with high error ⇒ undertting (larger model,
longer training).
4. Learning curve analysis: If validation loss plateaus early, LR too
small or stuck in local minimum. If validation loss spikes, LR too large.
5. Gradient ow check: Log gradient magnitudes at each layer. Nearzero in early layers = vanishing gradients. Very large = exploding gradients.
29.3 Transfer Learning Decision Framework
Dataset size
Similarity to pretraining data
Strategy
Small
High
Freeze backbone, train head only
Small
Low
Fine-tune last k layers
Large
High
Fine-tune all layers (low LR)
Large
Low
Fine-tune all layers (moderate LR)
Very large
Any
Train from scratch
29.4 Deployment Considerations
Model compression:
Pruning: Remove weights below a threshold; retrain.
Structured pruning
(remove entire channels/layers) is more hardware-friendly.
Quantisation: Reduce weight precision from FP32 to INT8 (or lower). 4×
smaller model, 24× faster inference on appropriate hardware.
29.5.
Exercises
120
Knowledge distillation: Train a small student network to mimic the output
distribution of a large teacher, using soft labels (high temperature softmax of
teacher outputs).
ONNX / TorchScript / TensorRT:
Export trained models to hardware-optimised
inference runtimes. TensorRT achieves 310× speedup over standard PyTorch on
NVIDIA GPUs via kernel fusion, FP16 computation, and layer optimisation.
29.5 Exercises
Exercise 31.1 Pipeline and Debugging
1. You train a ResNet-50 on a 10-class dataset (1000 images/class). After 20 epochs, training accuracy = 98%, validation accuracy = 62%.
Diagnose the problem and list 5 interventions in order of priority.
2. Explain mean Average Precision (mAP) step by step for a single object
class with 10 predicted boxes.
3. You need to deploy a model on a smartphone (< 5MB, < 30ms/frame).
Describe a complete pipeline from a trained ResNet-50 to a deployable
model.
29.5.
Exercises
121
Answer: Answer 31.1
(a) Training 98%, validation 62%: severe overtting (36-point gap). Interventions in priority order:
1. Data augmentation (RandomCrop, Flip, ColorJitter): fastest, most
impactful for small datasets. Eectively multiplies training set.
2. Regularisation: weight decay (λ = 1e−4), dropout before FC head
(p = 0.5).
3. Reduce model complexity: try ResNet-18 or MobileNet-V3 instead
of ResNet-50 (smaller model for small dataset).
4. Transfer learning: use ImageNet-pretrained ResNet-50, ne-tune only
the last layer(s).
The pretrained features generalise better with 10K
images.
5. Collect more data or use semi-supervised learning (pseudo-labelling
on unlabelled data).
(b) For one class with 10 predicted boxes (sorted by condence): (1) For each
prediction, check if IoU with any ground-truth box ≥
0.5 and not already
matched mark as TP or FP. (2) Accumulate precision and recall at each
threshold (each successive prediction). (3) Plot the precision-recall curve. (4)
AP = area under the PR curve (computed as
P
k Precision(k) · ∆Recall(k)).
(5) mAP = average AP over all classes.
(c)
ResNet-50
to
smartphone:
(1)
Knowledge
MobileNetV3-Small as student, ResNet-50 as teacher.
distillation:
train
MobileNetV3-Small
≈ 2.5MB. (2) Post-training quantisation: quantise to INT8 via TFLite
calibration (measure activation ranges on calibration data, set INT8 thresholds).
≈ 2× size reduction, 1.52× speedup. (3) Export to TFLite: use
TFLite converter with INT8 optimisation mode.
(4) Benchmark
on de-
vice: prole latency on the target SoC. Enable NNAPI (Android) or CoreML
(iOS) for DSP/Neural Engine acceleration. (5) Verify accuracy drop: INT8
MobileNetV3-Small typically within 12% of FP32, well within acceptable
limits.
Chapter 30
Architectural Decision Framework
30.1 The Full Decision Tree
Key Insight: How to Choose an Architecture
→ standard CNN/ViT backbone + linear head. Detection → add FPN + detection head. Segmentation →
1. What task?
Classication
encoder-decoder (U-Net) or DETR-style.
2. How much data?
< 10K : use pretrained backbone, ne-tune head.
10K 1M : ne-tune backbone with appropriate LR. > 1M : consider
training from scratch.
3. Compute budget?
Server, medium:
Mobile/edge:
MobileNetV3,
ResNet-50, EcientNet-B4.
EcientNet-B0.
Large-scale:
ViT-L,
EcientNet-B7, Swin-L.
4. Need spatial outputs? (segmentation, detection) ⇒ Avoid aggressive
downsampling; use FPN or dilated conv in the backbone.
5. Need rotation/scale invariance? Consider augmentation (easiest),
then group-equivariant CNNs (most principled).
122
30.2.
Final Exercises
123
30.2 Final Exercises
Exercise 32.1 Architectural Design
1. You are building a real-time (30 FPS) autonomous driving perception
system for a 1080p camera, detecting pedestrians, vehicles, and lane
lines.
Specify the complete architecture (backbone, neck, heads), loss
functions, training strategy, and deployment pipeline.
2. A medical imaging startup has 500 labelled chest X-rays (binary: normal/pneumonia). Describe the complete ML pipeline from raw images
to a deployed model that achieves clinically acceptable performance.
3. Compare ResNet-50, EcientNet-B3, and ViT-B/16 across: parameter
count, ImageNet accuracy, inference speed on CPU, data eciency, and
suitability for ne-tuning.
comparisons.
Provide specic numbers and justify your
30.2.
Final Exercises
124
Answer: Answer 32.1
(a) Autonomous driving perception system:
Backbone: ResNet-50 or EcientDet backbone (pretrained on COCO) good balance of accuracy and speed. Use FPN (Feature Pyramid Network)
to produce multi-scale features at {P3 , P4 , P5 }.
Necks+Heads: (i) Object detection (pedestrians, vehicles): YOLOX or Faster
R-CNN head on FPN features; (ii) Lane detection: lightweight segmentation
head (DeepLabV3 with MobileNet decoder) sharing the backbone.
Loss: Detection: focal loss (for class imbalance many easy negatives) +
IoU regression loss. Segmentation: cross-entropy + Dice loss for lane pixels.
Training: Pretrain on COCO (detection) + BDD100K (autonomous driving). Data augmentation: mosaic, copy-paste, photometric distortion. Mixedprecision training (FP16) for speed.
Deployment: Export to TensorRT, target NVIDIA Xavier/Orin SoC on the
vehicle.
INT8 quantisation with calibration on real driving data.
< 30ms/frame on a 1080p centre crop.
Aim for
Use model parallelism if multiple
cameras.
(b) Medical imaging pipeline (500 X-rays):
(1)
Preprocessing: CLAHE (contrast-limited adaptive histogram equalisation)
for X-ray contrast normalisation. Resize to 224 × 224. Normalise with ImageNet stats (pretrained backbone expects this).
(2)
Architecture: DenseNet-121 pretrained on CheXpert (chest X-ray dataset)
much better initialisation than ImageNet for medical imaging. Fine-tune
last 2 blocks + FC head.
(3)
Data augmentation: Horizontal ip, random rotation (±10), Random-
Crop, slight brightness/contrast jitter. No colour jitter (X-rays are grayscale).
Training: With only 500 images, use stratied 5-fold cross-validation.
#negative to handle imbalance. AdamW,
Loss: weighted BCE with w+ =
#positive
(4)
LR=1e−4 for unfrozen layers, 1e−3 for head.
(5)
Evaluation: AUC-ROC (primary), sensitivity, specicity, F1. Use operat-
ing point on ROC chosen by clinical requirement (e.g., sensitivity ≥ 95%).
(6)
Deployment: TorchScript export, local inference (data cannot leave hospi-
tal). Uncertainty estimation via MC-Dropout (run forward 20 times, average
+ std) to ag low-condence predictions for human review.
(c)
Model
Params
Top-1 Acc
CPU Inference
ResNet-50
25M
76.1%
EcientNet-B3
12M
81.6%
ViT-B/16
86M
81.8%*
∼50ms
∼35ms
∼100ms
Data Eciency
High (simple, robust BN)
High (BN, standard convs)
Low (needs ≫ 1M images)
*When pretrained on ImageNet-21K. With only ImageNet-1K: ViT-B ≈77.9%
Closing Remarks
You have now completed a rst-principles journey through computer vision. Every
major concept from the sampling theorem to Vision Transformers has been
derived, implemented, and stress-tested.
The architecture choices that seem arbitrary in retrospect all follow a clear logic:
Convolutions arise inevitably from the requirement for linear, shift-invariant
feature extraction.
Weight sharing is justied by the stationarity of natural image statistics.
Residual connections solve a pure optimisation problem.
ViTs are convolutions where the kernel is learned as a dynamic function of the
input.
The eld continues to evolve. What stays constant is the underlying principle:
match the inductive biases of your model to the structure of your data,
and let the data do the rest.
125
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )