Level 3 In-Depth AI · Deep Learning
Convolutional Neural Networks
Networks built for images. A small filter slides across the picture looking for the same pattern everywhere, and stacking many such layers builds up from edges to textures to whole objects.
- Level
- ●●●●● Intermediate
- Reading
- 15 min
- To learn it well
- 1.5 hours to read, an afternoon to practise
- Builds on
- 14 concepts →
- Quiz
- 5 questions ↓
The full path from zero — 14 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Convolutional Neural Networks
Read them roughly in this order. See it on the concept map →
Why it matters
A photo is a grid of numbers. A modest 224 × 224 colour image has 224 × 224 × 3 = 150,528 of them (Images as Data). Feed that into an ordinary fully connected network and the very first layer needs 150,528 weights per hidden unit: about 9.6 million weights for just 64 units. Worse, each of those units learns to look at fixed pixel positions. A cat in the top-left corner and the same cat in the bottom-right would be two unrelated patterns that must be learned separately.
A convolutional neural network (CNN or convnet) fixes both problems with one idea. Instead of connecting every pixel to every unit, it slides a small filter, a 3 × 3 grid of weights for example, across the image and applies the same weights at every position. A filter that detects a vertical edge detects it anywhere.
CNNs are why computers learned to see. AlexNet, a CNN, won the 2012 ImageNet competition by a margin that shocked the field and started the deep-learning boom. CNNs still power phone cameras, medical scan readers, self-driving perception, document scanners and the image side of many multimodal models. The same sliding idea works on audio (Audio as Data), on time series, and inside image generators such as the U-Net in Stable Diffusion. Vision Transformers now compete with CNNs on large datasets, but convolution remains one of the most useful ideas in deep learning.
The intuition
Imagine searching a large page for every occurrence of the letter "e" using a small cardboard stencil with an "e" cut out. You slide the stencil over the page, one position at a time, and at each spot you note how well the stencil matches what is underneath. At the end you have a map of where the "e"s are.
A convolution layer does exactly this, with three differences:
- The stencil is a small grid of learned numbers, the filter. Training decides which patterns are worth looking for.
- "How well it matches" is a multiply-and-add: a dot product between the filter and the patch of image under it.
- A layer has many filters, say 64, each producing its own map. Each output map is called a feature map.
Then you stack layers. The first layer's filters find simple things: edges at different angles, blobs of colour. The second layer slides its filters over the feature maps of the first, so it finds combinations of edges: corners, stripes, textures. Further up you get parts (an eye, a wheel), and near the top whole objects.
Key idea A convolution layer applies the same small filter at every position of its input. This weight sharing means far fewer parameters, and a pattern learned in one place is recognised everywhere. Stacking layers builds a hierarchy from edges to objects.
How it works
Convolution by hand
Here is a 5 × 5 grayscale image (bigger numbers are brighter) and a 3 × 3 filter. The filter has −1s in its left column and +1s in its right column, so it responds strongly where the right side is brighter than the left. That is a vertical edge.
Place the filter over the top-left 3 × 3 patch of the image:
Multiply each pair of overlapping numbers and add the nine products:
That is the top-left output. Slide the filter one pixel right (the orange window in the figure), and you get . One more step right gives 19. Then move down one row and start again from the left. The full output, the feature map, is
The big numbers sit in the middle and right columns, exactly where the image jumps from dark (0–2) to bright (6–8). The filter has found the vertical edge. In a real network nobody designs this filter. It starts random, and Backpropagation tunes its nine numbers to whatever patterns help reduce the loss.
In symbols, for an input and a filter with bias , the output at row , column is
The two sums run over the rows and columns of the filter. Read it as "line up the filter's corner with pixel , multiply the overlapping pairs and add them up". A nonlinearity such as ReLU is applied afterwards (Activation Functions).
Note Mathematicians would call this cross-correlation. True convolution flips the filter first. Deep learning libraries skip the flip and call it convolution anyway. Since the filter is learned, the difference doesn't matter.
Padding and stride
Our 5 × 5 image gave a 3 × 3 output, because a 3 × 3 filter fits in only 3 positions across. Two settings control the output size.
- Padding adds a border of zeros around the input. With one pixel of padding, the 5 × 5 image becomes 7 × 7 and the output stays 5 × 5. "Same" padding like this keeps sizes constant and lets edge pixels be seen as often as central ones.
- Stride is how far the filter jumps each step. Stride 2 skips every other position and roughly halves the height and width.
For an input of size , filter size , padding and stride , the output size is
The brackets mean "round down". Check: gives . With : . With : .
Channels
A colour image has three channels (red, green, blue), so it is really a 3-D block of numbers: 3 × height × width. A filter then has a depth to match: a "3 × 3" filter on an RGB image is actually 3 × 3 × 3 = 27 weights, and it sums over all three channels at once. A layer with 64 such filters outputs 64 feature maps, a block of 64 channels. The next layer's filters must then be 64 deep.
So the parameters of one convolution layer are
where and are the numbers of input and output channels and the is each filter's bias. A first layer with 64 filters of size 3 × 3 on an RGB image has parameters. Compare that with the 9.6 million a fully connected layer needed for 64 units. Yet the convolution layer produces 64 full-size feature maps, not 64 single numbers.
Pooling
Pooling shrinks a feature map by summarising small regions. Max pooling with a 2 × 2 window and stride 2 keeps the largest value in each 2 × 2 block:
Average pooling takes the mean instead (here 3.75, 1.25, 1 and 5.5). Pooling has no weights. It halves the height and width, which cuts computation in later layers, and it makes the output a little less sensitive to exactly where a feature appeared. Many modern networks use stride-2 convolutions instead of pooling, and end with global average pooling, which averages each whole feature map down to a single number.
Receptive field
The receptive field of a unit is the patch of the original image that can affect it. A unit in the first 3 × 3 layer sees 3 × 3 pixels. A unit in a second 3 × 3 layer sees 3 × 3 first-layer units, which together cover 5 × 5 pixels. A third layer covers 7 × 7. Pooling and strides make it grow much faster. This is how a deep CNN's top layers can "see" whole objects even though every filter is tiny. Two stacked 3 × 3 layers cover the same 5 × 5 area as one 5 × 5 filter, with fewer weights (18 versus 25 per channel pair) and an extra nonlinearity. That is why modern CNNs use 3 × 3 filters almost everywhere.
Equivariance and the built-in assumptions
Shift the input image two pixels to the right and the feature maps shift two pixels to the right too. This property is translation equivariance, and it comes for free from weight sharing. Add pooling or global averaging and the final answer becomes nearly invariant to where the object is.
These are inductive biases: assumptions built into the architecture. A CNN assumes that nearby pixels belong together (locality) and that a pattern means the same thing wherever it appears. For natural images both are true, which is why CNNs learn from far fewer examples than a fully connected network would need.
A whole network
A typical image classifier repeats a simple pattern: convolution, normalisation (Normalization Layers: BatchNorm and LayerNorm), ReLU, sometimes pooling. As the height and width shrink, the number of channels grows: 224 × 224 × 3 → 112 × 112 × 64 → … → 7 × 7 × 512. Global average pooling and a final linear layer give one score per class, turned into probabilities by softmax. Deep CNNs also need Residual Connections to train well. Classic CNN Architectures: LeNet to ResNet walks through LeNet, AlexNet, VGG, ResNet and EfficientNet.
In code
First the hand-worked example, from scratch in NumPy and then with PyTorch's built-in convolution to confirm:
import numpy as np
import torch
import torch.nn.functional as F
image = np.array([[3, 1, 0, 2, 5],
[1, 0, 1, 6, 7],
[2, 1, 0, 7, 8],
[0, 2, 1, 8, 6],
[1, 0, 2, 6, 7]], dtype=float)
kernel = np.array([[-1, 0, 1],
[-1, 0, 1],
[-1, 0, 1]], dtype=float) # vertical-edge detector
def conv2d(img, k, stride=1):
kh, kw = k.shape
oh = (img.shape[0] - kh) // stride + 1
ow = (img.shape[1] - kw) // stride + 1
out = np.zeros((oh, ow))
for i in range(oh):
for j in range(ow):
patch = img[i*stride:i*stride+kh, j*stride:j*stride+kw]
out[i, j] = np.sum(patch * k) # multiply and add
return out
print(conv2d(image, kernel))
# [[-5. 13. 19.]
# [-1. 18. 19.]
# [ 0. 18. 18.]]
# PyTorch shapes are (batch, channels, height, width)
x = torch.tensor(image, dtype=torch.float32).view(1, 1, 5, 5)
w = torch.tensor(kernel, dtype=torch.float32).view(1, 1, 3, 3)
print(F.conv2d(x, w).squeeze()) # same 3x3 numbers
print(F.conv2d(x, w, padding=1).shape) # torch.Size([1, 1, 5, 5])
print(F.conv2d(x, w, stride=2).shape) # torch.Size([1, 1, 2, 2])
Now a tiny CNN that learns to tell vertical bars from horizontal ones. The twist: during training the bars only ever appear in the first half of the image, and we test on bars in the second half. A fully connected network (MLP) with seven times as many parameters is trained the same way for comparison.
import torch
import torch.nn as nn
torch.manual_seed(0)
def make_images(n, positions): # 12x12 noise plus one bar: vertical (0) or horizontal (1)
X = 0.3 * torch.rand(n, 1, 12, 12)
y = torch.randint(0, 2, (n,))
for i in range(n):
p = positions[torch.randint(len(positions), (1,)).item()]
if y[i] == 0: X[i, 0, :, p] += 1.0 # vertical bar in column p
else: X[i, 0, p, :] += 1.0 # horizontal bar in row p
return X, y
X_train, y_train = make_images(800, positions=range(0, 6)) # bars only in the first half
X_test, y_test = make_images(400, positions=range(6, 12)) # bars only in the second half
cnn = nn.Sequential(
nn.Conv2d(1, 8, kernel_size=3, padding=1), nn.ReLU(), # 1x12x12 -> 8x12x12
nn.MaxPool2d(2), # -> 8x6x6
nn.Conv2d(8, 16, kernel_size=3, padding=1), nn.ReLU(), # -> 16x6x6
nn.AdaptiveAvgPool2d(1), nn.Flatten(), # -> 16 numbers
nn.Linear(16, 2))
mlp = nn.Sequential(nn.Flatten(), nn.Linear(144, 64), nn.ReLU(), nn.Linear(64, 2))
for name, model in [("CNN", cnn), ("MLP", mlp)]:
opt = torch.optim.Adam(model.parameters(), lr=1e-2)
for epoch in range(10):
for i in range(0, 800, 32):
loss = nn.functional.cross_entropy(model(X_train[i:i+32]), y_train[i:i+32])
opt.zero_grad(); loss.backward(); opt.step()
with torch.no_grad():
acc = (model(X_test).argmax(1) == y_test).float().mean().item()
n = sum(p.numel() for p in model.parameters())
print(f"{name}: {n:5d} parameters, accuracy on bars in unseen positions {acc:.3f}")
# CNN: 1282 parameters, accuracy on bars in unseen positions 0.967
# MLP: 9410 parameters, accuracy on bars in unseen positions 0.000
The MLP scores 0%, worse than guessing. It learned a shortcut tied to position: in training, only vertical bars ever lit up the bottom rows, and only horizontal bars lit up the right-hand columns. On the test set those cues point exactly the wrong way. The CNN's shared filters learned "vertical line" and "horizontal line" as patterns, wherever they are.
Common pitfalls
- Channel order. PyTorch expects
(batch, channels, height, width). Images loaded with PIL, NumPy or OpenCV are usually(height, width, channels), and OpenCV uses BGR rather than RGB. Usetensor.permute(2, 0, 1)and check a few images visually. - Unnormalised inputs. Pixel values 0–255 make training slow and unstable. Scale to 0–1, and for pretrained networks subtract and divide by the same mean and standard deviation used in their training.
- Shrinking too fast. Without padding, each 3 × 3 layer trims a pixel from every edge. Strides and pooling halve the size. Work out the shapes (or print them) before adding a
Linearlayer whose input size depends on them. - Training from scratch on a small dataset. With a few thousand images, a CNN pretrained on ImageNet and fine-tuned will almost always beat one trained from scratch.
- Assuming full invariance. CNNs handle shifts well, but not rotations, large changes of scale, or unusual lighting unless they saw them in training. Data Augmentation supplies those variations.
Watch out CNNs can latch onto shortcuts, just like the MLP above. A famous kind of failure is a model that "detects" a disease from a hospital's watermark or a ruler in the photo, rather than from the lesion. Test on data from a different source than the training data, and use Interpretability and Explainability tools to check what the model looks at.
Where it leads
- Classic CNN Architectures: LeNet to ResNet: LeNet, AlexNet, VGG, Inception, ResNet, EfficientNet and ConvNeXt.
- Image Classification, Object Detection and Image Segmentation: the main vision tasks, all built on CNN backbones for a decade.
- Transfer Learning: reusing a pretrained CNN's features for your own problem.
- Vision Transformers: replaces convolutions with attention over image patches, and wins when data is plentiful.
- Graph Neural Networks: generalise "look at your neighbours with shared weights" from pixel grids to arbitrary graphs.
- One-dimensional convolutions slide along sequences such as audio and text, an alternative to recurrent networks.
A bit of history
In 1959 the neuroscientists David Hubel and Torsten Wiesel found that individual neurons in a cat's visual cortex respond to edges at particular angles in particular places. Their work later won a Nobel Prize. Kunihiko Fukushima's Neocognitron (1980) built a layered model of that hierarchy. Yann LeCun and colleagues at Bell Labs then trained convolutional networks with backpropagation to read handwritten zip codes (1989), leading to LeNet-5 (1998), which was used commercially to read handwritten bank cheques in the US.
For years CNNs stayed a niche. In 2012 Alex Krizhevsky, Ilya Sutskever and Geoffrey Hinton trained AlexNet, a CNN with about 60 million parameters, on two GPUs. It achieved 15.3% top-5 error on ImageNet against 26.2% for the next-best entry, and computer vision switched to deep learning almost overnight. VGG (2014), GoogLeNet (2014) and ResNet (2015) followed, and by 2015 ResNets had passed the roughly 5% top-5 error often quoted for a human annotator on that benchmark. In 2013 Matthew Zeiler and Rob Fergus visualised what each layer of a trained CNN responds to, giving the edges-to-objects picture shown above.
Try it
- By hand, apply the horizontal-edge filter
[[-1,-1,-1],[0,0,0],[1,1,1]]to the 5 × 5 image above. Then check your answer with theconv2dfunction. Why are the numbers so much smaller than for the vertical filter?- What is the output size of a 32 × 32 input with a 5 × 5 filter, padding 2 and stride 2? How many parameters does
nn.Conv2d(16, 32, kernel_size=5)have?- In the bars experiment, print
cnn[0].weightafter training. Do any of the eight 3 × 3 filters look like line detectors?Hint for 2: use the output-size formula; for the parameters, .
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Stanford CS231n: Deep Learning for Computer Vision
Famous course notes on neural nets, backprop, CNNs and training, written very clearly.
CNN Explainer
An interactive visualisation of a convolutional network classifying images.
Dive into Deep Learning
An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.
A guide to convolution arithmetic for deep learning
Clear pictures and formulas for how padding, stride and dilation change output sizes, including transposed convolutions.
ImageNet Classification with Deep Convolutional Neural Networks
AlexNet: the GPU-trained CNN that won ImageNet by a huge margin and started the deep learning boom.
Visualizing and Understanding Convolutional Networks
Showed what each layer of a trained CNN responds to, from edges to object parts, and used that to improve the network.
Feature Visualization
Beautiful interactive article showing the patterns that excite neurons at each depth of an image network.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/dl/cnn.md