Topic 1 of 5 · 5 min read
Convolutional networks for images
Goal: Explain how a convolution layer detects a local pattern and compute the output size of a convolution layer.
A convolution layer slides one small filter over the whole image and records how strongly each patch matches it, so the same pattern is found wherever it appears. Stacking such layers builds from edges to textures to object parts.
Check yourself · 1 of 3
A 3x3 convolution filter is applied at every position of an image. What does that sharing give you?
Why it matters
Images have two properties a plain fully connected layer ignores: nearby pixels belong together, and a pattern means the same thing in any position. A fully connected layer on a 224x224 RGB image has about 150,000 inputs per neuron. A 3x3 filter has 27 weights per output channel and reuses them at every position. That is far fewer parameters, and a cat in the corner is detected by the same weights as a cat in the centre.
The parts
- Filter (kernel): a small grid of learned weights, for example 3x3 across all input channels.
- Feature map: the output of one filter. Ten filters give ten feature maps, which become the channels of the next layer.
- Stride: how many pixels the filter moves each step. Stride 2 roughly halves the width and height.
- Padding: zeros added around the border so edge pixels are not lost.
- Pooling: summarises a small window, usually its maximum, to shrink the map and tolerate small shifts.
The output width is floor((W - K + 2P) / S) + 1, where W is input size, K kernel size, P padding and S stride. For W=32, K=5, P=0, S=1 the output is 28.
Before and after
A common bug is guessing the size of the first fully connected layer:
import torch.nn as nn
# Weak: 32x32 input, conv(5) then pool(2) gives 16 x 14 x 14, not 16 x 32 x 32
net = nn.Sequential(
nn.Conv2d(3, 16, kernel_size=5),
nn.ReLU(),
nn.MaxPool2d(2),
nn.Flatten(),
nn.Linear(16 * 32 * 32, 10), # shape error
)
# Fixed: 32 -> 28 after the conv, 28 -> 14 after the pool
net = nn.Sequential(
nn.Conv2d(3, 16, kernel_size=5),
nn.ReLU(),
nn.MaxPool2d(2),
nn.Flatten(),
nn.Linear(16 * 14 * 14, 10),
)
Where CNNs still win
Convolution builds in a locality assumption, so a CNN learns well from modest datasets. Vision transformers have no such prior and, in the original ViT paper, needed large-scale pretraining to match or beat strong CNNs. On a few thousand labelled images, or on a phone or camera with a tight latency budget, a small CNN such as a ResNet or MobileNet variant is usually the better first try.
What goes wrong
- Mixing up the size formula and forgetting padding, so the flatten layer has the wrong width.
- Expecting rotation or scale invariance: convolution gives shift tolerance only. Rotated or zoomed inputs need augmentation.
- Pooling too early on small objects, which erases the detail the classifier needs.
Examples
Computing a layer's output size
An input is 64x64 with a 3x3 kernel, padding 1 and stride 2. The size is floor((64 - 3 + 2) / 2) + 1 = floor(31.5) + 1 = 32. With 32 filters the layer outputs 32 channels of 32x32, so the next layer sees a 32 x 32 x 32 tensor.
Choosing a model for a factory camera
A line-inspection camera has 4,000 labelled photos and a device with no GPU. A ViT trained from scratch would overfit on 4,000 images and run slowly. A pretrained MobileNet-style CNN, fine-tuned on those photos, fits both limits.
Key points
- A convolution filter reuses the same small set of weights at every position, so a pattern is detected wherever it appears.
- Output size is floor((W - K + 2P) / S) + 1, and each layer's channel count equals its number of filters.
- Pooling shrinks feature maps and adds tolerance to small shifts, but it also discards fine detail.
- Convolution builds in locality, which is why CNNs train well on small image datasets and run cheaply on edge hardware.
- Convolution is shift-tolerant, not rotation- or scale-invariant; augmentation has to cover those.
Common mistakes
- Guessing the input width of the first fully connected layer instead of computing it or printing the tensor shape.
- Using a vision transformer trained from scratch on a few thousand images and expecting it to match a CNN.
- Assuming a CNN recognises rotated or mirrored objects without augmentation.
- Pooling or striding aggressively in the first layers, which throws away the detail small defects live in.
Check yourself · 2 of 3
A 32x32 input goes through a 5x5 convolution with stride 1 and no padding. What size is the output feature map?
Check yourself · 3 of 3
You have 3,000 labelled images and must run on a phone. Which starting model fits best?
Practice items, not counted towards your mastery.
Start here
- Stanford CS231n: Deep Learning for Computer Vision (opens in a new tab)CourseFree
Course notes on convolution layers, output-size arithmetic, pooling and transfer learning.
- An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale (opens in a new tab)PaperFree
The vision transformer paper: images as patch sequences, and when ViT needs large pretraining data.
- Denoising Diffusion Probabilistic Models (opens in a new tab)PaperFree
The paper that made step-by-step denoising a practical way to generate images.