Module 7 · Convolutional neural networks
Time: about 7 hours with readings · Lab: python course/labs/lab07_convolution.py
You need: Module 1 §2 (an image as a grid of numbers with 3 colour channels) and §5 (learned features), Module 2 §3–§4 (dot products, the chain rule) and §9 (mean and standard deviation), and Module 5 (layers, ReLU, backpropagation).
By the end you can:
- explain why images need convolutions rather than fully connected layers;
- compute a convolution by hand, and work out output sizes from kernel, padding and stride;
- explain pooling, receptive fields, batch normalisation and residual connections;
- explain depthwise separable convolutions and MobileNetV2's inverted residual block with real numbers.
Why this matters in TrayCheck
MobileNetV2 has 155 layers (Lab 8 counts them): 35 ordinary convolutions, 17 depthwise convolutions, 52 batch-normalisation layers, 35 ReLUs and 10 residual Add layers. This module explains each kind, so the architecture stops being a black box.
Why this matters for the internship
This is the most technical module, and the role doesn't expect you to compute convolutions. What you do need is the one-paragraph version, because it explains both why image models work and how they fail:
A convolutional network learns small pattern detectors (edges, colours, textures) and slides each one across the whole image, so a pattern is recognised wherever it appears. Later layers combine those into larger patterns: grains of rice, the shape of a bowl, a fried egg. The network only knows the patterns its training photos contained.
That last sentence is the practical point. A change of crockery, lighting, camera height or plating style changes the patterns in the photo, and the model has no way to know it should ignore them. That is why the PoC must test on the site's own trays (Module 9 §6). Read §1 and §2 for the idea; treat the rest as optional depth.
1. Why not a fully connected network on pixels?
Lab 7 compares two ways to turn a 96 × 96 × 3 photo into 32 feature maps of the same size:
fully connected: 8,154,021,888 parameters
3x3 convolution: 896 parameters (9,100,471x fewer)
Where the first number comes from: the input has 96 × 96 × 3 = 27,648 numbers and the output 96 × 96 × 32 = 294,912. A fully connected layer gives every output its own weight for every input (Module 2 §3): 27,648 × 294,912 weights, plus 294,912 biases, is 8,154,021,888. Billions of parameters, hopeless to train on 400 photos. It also ignores two facts about images:
- Locality: nearby pixels are related; a pixel's meaning comes from its neighbourhood.
- Translation equivariance: an edge or a grain of rice looks the same wherever it appears.
A convolution builds both facts in. It slides a small filter (kernel) across the image and computes the same weighted sum of each local patch, sharing the same few weights everywhere.
2. The convolution operation
For a 3 × 3 kernel K and image I, the output at position (i, j) is
That's 9 multiply-adds per output: a dot product (Module 2 §3) between the kernel and the 3 × 3 patch under it. (Mathematicians call this cross-correlation; true convolution flips the kernel. Deep learning libraries compute cross-correlation and call it convolution. It makes no difference when the kernel is learned.)
By hand: finding an edge
A 5 × 5 greyscale image, dark on the left (0) and bright on the right (10), and a 3 × 3 kernel that subtracts the left column from the right column:
image kernel
0 0 10 10 10 -1 0 1
0 0 10 10 10 -1 0 1
0 0 10 10 10 -1 0 1
0 0 10 10 10
0 0 10 10 10
Place the kernel over the top-left 3 × 3 patch (columns 1–3). Each row of the patch is 0, 0, 10, so each row contributes −1×0 + 0×0 + 1×10 = 10, and three rows give 30. Slide one column right (columns 2–4, where each row reads 0, 10, 10): each row gives −0 + 0 + 10 = 10, total 30. Slide again (columns 3–5, all 10s): −10 + 0 + 10 = 0, total 0. Repeating down the rows gives a 3 × 3 output:
30 30 0
30 30 0
30 30 0
Large where the brightness changes from left to right, zero where it is flat: a vertical edge detector. Move the edge one column to the right in the image and the 30s move one column right in the output. That is translation equivariance, for free: the same 9 weights are used at every position, so a pattern is detected wherever it appears.
The grid of outputs one kernel produces is called a feature map: a map of where in the image that kernel's pattern occurs.
Lab 7 implements it in two lines of NumPy and applies classic hand-designed kernels to a
bibimbap photo. A Sobel kernel [[-1,0,1],[-2,0,2],[-1,0,1]] responds to vertical edges,
and an all-1/9 kernel blurs. See course/labs/output/lab07_filters.png. A CNN learns its
kernels by gradient descent: the 9 numbers start random and backpropagation adjusts them like any
other weights. Visualisations of trained networks show the first layers learning edge and colour
detectors much like these, middle layers textures and parts, and deep layers object-like patterns
(Module 1 §5).
Channels. Real images have 3 channels (red, green, blue), and later layers have many more: a layer with 32 kernels produces 32 feature maps, which the next layer receives as 32 channels. So a kernel must look at all incoming channels at once: with Cin input channels it has shape 3 × 3 × Cin, and its output at each position is the sum over all of them. A layer with Cout such kernels has 3 × 3 × Cin × Cout weights + Cout biases. For 3 → 32 that's 3 × 3 × 3 × 32 + 32 = 896.
3. Padding, stride, pooling: how sizes change
For input size n, kernel k, padding p, stride s:
input 96x96, 3x3 kernel:
'valid' (no padding), stride 1 -> 94x94
'same' (pad 1 pixel), stride 1 -> 96x96
'same', stride 2 -> 48x48 (MobileNetV2 halves the size 5 times)
MobileNetV2 at 96x96: 96x96 -> 48x48 -> 24x24 -> 12x12 -> 6x6 -> 3x3
Pooling summarises each small window, for example by its maximum (2 × 2 max-pooling halves each side). Modern networks such as MobileNetV2 mostly downsample with stride-2 convolutions instead, then finish with global average pooling: average each of the 1280 final channels over the 3 × 3 grid to get one 1280-number vector per photo.
Receptive field. The receptive field of an output is the patch of the original image that can affect it. One 3 × 3 layer: 3 × 3 pixels. A second 3 × 3 layer on top looks at a 3 × 3 patch of the first layer's outputs, each of which saw 3 × 3 pixels, overlapping; together they span 5 × 5 pixels (each extra layer adds one pixel on every side). A third gives 7 × 7. With stride-2 layers each step covers twice the ground, so it grows much faster (27 × 27 after five layers in the lab). Deep layers therefore combine information from the whole photo, which is how a network can recognise "bibimbap" from the arrangement of many parts.
4. Batch normalisation
Batch normalisation (BN) standardises each channel inside the network, as Module 4 §1 standardised inputs, then lets the network choose its own scale and centre:
(ε is a tiny number that prevents dividing by zero.) Worked example: one channel's values across a batch of four images are 2, 4, 6, 8. Mean 5, variance 5, SD 2.24; standardised: −1.34, −0.45, 0.45, 1.34. With learned γ = 2 and β = 1 the outputs are −1.68, 0.11, 1.89, 3.68.
Why it helps: every layer's inputs are the previous layer's outputs, and those keep changing size as earlier layers train. BN keeps each layer's inputs at a steady scale, so a single learning rate suits the whole network and deep networks train much faster. γ and β are learned so that, if the standardised scale isn't the most useful one, the network can undo it. Two modes matter:
| Mode | Statistics used |
|---|---|
| Training | the current batch's mean and variance, while updating running averages |
| Inference | the stored running averages: deterministic, batch-independent |
Each BN layer stores 4 numbers per channel (γ, β, running mean, running variance). That's why
block_2_expand_BN with 144 channels has 576 parameters, of which only γ and β are ever trainable.
5. Residual connections
Very deep plain networks get harder to train as they get deeper. The chain rule explains why. Backpropagation multiplies one local slope per layer (Module 5 §2). If those slopes are typically 0.5, then after 20 layers the slope reaching the early layers is 0.5²⁰ ≈ 0.000001: the early layers barely learn (vanishing gradients). If they're typically 1.5, it's 1.5²⁰ ≈ 3,300: training blows up.
ResNet (2015) fixed this with a skip connection: a block computes F(x) and outputs
Two consequences. First, the block only has to learn a correction to its input; if it has nothing
useful to add, F can stay near zero and the block passes its input through. Second, the slope of
y with respect to x is 1 + (slope of F): even when F's slope is tiny, the 1 carries the
gradient straight back through the "+" undiminished. Residual connections are now in almost every
deep architecture. MobileNetV2 has 10 of them (the Add layers).
6. MobileNet's trick: depthwise separable convolutions
A standard 3 × 3 convolution mixes spatial information and channels in one expensive step. A depthwise separable convolution splits that into two cheap steps:
- Depthwise: one 3 × 3 filter per channel (spatial filtering, no channel mixing).
- Pointwise: a 1 × 1 convolution that mixes channels.
Count the parameters for 144 channels in, 144 out. Standard: 144 kernels of 3 × 3 × 144 = 3 × 3 × 144 × 144 = 186,624. Depthwise separable: 144 depthwise filters of 3 × 3 (1,296), plus a 1 × 1 convolution mixing 144 channels into 144 (144 × 144 = 20,736), total 22,032. The multiply-adds are those numbers times the 24 × 24 = 576 positions. Lab 7:
standard: 186,624 parameters, 107.5 M multiply-adds
depthwise separable: 22,032 parameters, 12.7 M multiply-adds (8.5x cheaper)
That saving, applied throughout the network, is why MobileNets run fast on phones and CPUs.
MobileNetV2's inverted residual block
MobileNetV2 (2018) arranges these into inverted residual blocks with linear bottlenecks. Here is block_2, printed by Lab 8 from the actual trained model:
block_2_expand Conv2D 1x1 out (24, 24, 144) 3,456 params expand 24 -> 144 channels (x6)
block_2_expand_BN / relu
block_2_depthwise DepthwiseConv2D out (24, 24, 144) 1,296 params 3x3 spatial filter per channel
block_2_depthwise_BN / relu
block_2_project Conv2D 1x1 out (24, 24, 24) 3,456 params project back to 24 channels
block_2_project_BN (no ReLU: "linear bottleneck")
block_2_add Add out (24, 24, 24) residual: input + block output
These are exactly the numbers Lab 7 computed by hand (3,456 + 1,296 + 3,456). The design logic:
- Expand, filter, compress. The depthwise filter works in a wide 144-channel space where it is cheap, while the block's input and output stay narrow (24 channels), saving memory between blocks.
- Linear bottleneck. The final projection has no ReLU, because applying ReLU in a narrow space throws information away (the paper's argument).
- Inverted residual. The skip connection joins the narrow ends, the reverse of classic ResNet bottlenecks, which join wide ends. It's only used when input and output shapes match (stride 1, same channel count).
Where CNNs came from
LeNet-5 for handwritten digits (LeCun et al., 1998) → AlexNet wins ImageNet (2012) → VGG (2014) → ResNet (2015) → MobileNet (2017) → MobileNetV2 (2018) → EfficientNet (2019). Since 2020, Vision Transformers compete with CNNs on large datasets. For a small CPU-friendly classifier with 400 training photos, a pre-trained MobileNetV2 remains a sensible choice.
Check your understanding
1. A 3x3 conv layer maps 32 channels to 64. How many parameters, including biases?
3 × 3 × 32 × 64 + 64 = 18,496.
2. What's the output size of a 3x3 convolution with stride 2 and padding 1 on a 48x48 input?
⌊(48 + 2 − 3)/2⌋ + 1 = ⌊47/2⌋ + 1 = 23 + 1 = 24, so 24 × 24.
3. Why do batch normalisation layers behave differently during training and prediction?
During training they normalise with the current batch's statistics, which change from batch to batch. At prediction time they use stored running averages, so a single photo's prediction is deterministic and doesn't depend on what else is in the batch.
4. Explain in one sentence why depthwise separable convolutions are cheaper.
They split spatial filtering (one small filter per channel) from channel mixing (a 1 × 1 convolution), instead of doing both at once with a full 3 × 3 × C_in filter per output channel. That cuts the cost by roughly a factor of the kernel area (here 8.5×).
5. Why is there no ReLU after MobileNetV2's projection layer?
The projection squeezes the features into a narrow, low-dimensional space; a ReLU there would zero out information that can't be recovered. Keeping it linear preserves it (the "linear bottleneck").
Go deeper
Short on time or new to this? The study guide says exactly which of these to read first.
Core
- Stanford CS231n notes, Convolutional Neural Networks: Architectures, Convolution / Pooling Layers (cs231n.github.io/convolutional-networks): the canonical explanation, with the output-size formula and parameter counting.
- Dive into Deep Learning, chapter Convolutional Neural Networks (from From Fully Connected Layers to Convolutions through Pooling and LeNet) and from Modern Convolutional Neural Networks: Batch Normalization and Residual Networks (ResNet) and ResNeXt.
- Understanding Deep Learning (Prince), Chapter 10, Convolutional networks and Chapter 11, Residual networks.
Optional
- Deep Learning (Goodfellow et al.), Chapter 9, Convolutional Networks.
- 3Blue1Brown, But what is a convolution?: convolution beyond images.
- Olah, Mordvintsev & Schubert, Feature Visualization, Distill (2017): what CNN layers detect.
- DeepLearning.AI Deep Learning Specialization, Course 4, Convolutional Neural Networks, with lectures on ResNets, depthwise separable convolutions and MobileNet.
- Papers: LeCun et al. 1998 (Gradient-based learning applied to document recognition); Krizhevsky et al., NeurIPS 2012; He et al., Deep Residual Learning, CVPR 2016; Howard et al., MobileNets, arXiv 2017; Sandler et al., MobileNetV2: Inverted Residuals and Linear Bottlenecks, CVPR 2018.
Interview angle
"MobileNetV2 is built from inverted residual blocks: a 1×1 convolution expands the channels six times, a depthwise 3×3 filters each channel separately, and a linear 1×1 projects back down, with a skip connection when shapes match. Depthwise separable convolutions are why it's small and fast. For a 144-channel layer they're about 8.5 times cheaper than a standard convolution, which matters for a model meant to run on a kitchen laptop."