Part 12 / Topic 1 of 6
Convolutional networks
A dense layer treats pixel (0,0) and pixel (7,7) as unrelated inputs. A convolution slides one small filter (say 3×3) across the image, reusing the same weights at every position — so a pattern learned anywhere is recognised everywhere, with few parameters.
- Filters detect local patterns (edges, strokes); stacking layers composes them into shapes.
- Padding keeps the size; pooling (e.g. MaxPool 2×2) halves the resolution and buys small shift-invariance.
# examples/01_a_small_cnn_on_8x8_digit.py (abridged)
model = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=3, padding=1), nn.ReLU(),
nn.MaxPool2d(2), # 8x8 -> 4x4
nn.Conv2d(16, 32, kernel_size=3, padding=1), nn.ReLU(),
nn.Flatten(), nn.Linear(32 * 4 * 4, 10),
)
# test accuracy: 0.95
# parameters: 9930
Ten classes, 0.95 accuracy, 9,930 parameters — Part 10's dense MLP needed a comparable score from far more weights. Weight sharing is the whole trick.
🧪 Quick quiz
- What makes CNNs suited to images?
Show the answer
Shared small filters detect local patterns anywhere in the image — measured here, a 9,930-parameter CNN reached 0.95 on the digits test set.
Done here? The practice set for Part 12 — 4 exercises with solutions — is on the part page.