Lesson 9 · The primitives toolbox
Grids and images: convolutions
The problem
In the last lesson, a tiny network found pepperoni anywhere on a slice, using 50 weights. An MLP with 2,354 weights missed every pepperoni that had moved. The tiny network won by weight sharing: it used one small detector at every position of the image.
This lesson opens up that detector. What does it compute at each position? What patterns can it find? And how does a network learn good detectors by itself?
Slide a filter
Start with an image small enough to work by hand: 6 × 6 pixels, dark (0) with a bright bar (1s) in the middle. The detector is a 3 × 3 grid of weights. Its left column is −1, its middle column is 0 and its right column is +1.
Put the detector over the top-left 3 × 3 patch of the image. Multiply each weight by the pixel under it, and add up the 9 products. That sum is one output number. Then move the detector one pixel right and do it again. When it reaches the right-hand edge, go back to the left, one row down.
Image (6 × 6)
Filter
Filter × patch
Feature map (4 × 4)
Filter at row 1, column 1 of the feature map
Sum of the 9 products = 1 + 1 = 2
Zero products are left out of the sum.
This sliding is called a convolution. The small grid of weights is the filter (also called a kernel). At each position, the sum is a dot product. Write the filter and the patch as two lists of 9 numbers, then multiply matching entries and add. It's the same weighted sum that a neuron computes, with the same 9 weights reused at every position.
Each position gives one number, and together they make a grid. This grid is the feature map: how strongly the filter's pattern appears at each place in the image. A 3 × 3 filter fits in positions across and 4 down, so the feature map is 4 × 4.
Worked example
Two positions of the vertical-edge filter on the bar image
Row 2, column 1 (counting from 0, as in the formula below). The patch is rows 2–4 and columns 1–3 of the image. Its left column is 0, 0, 0 and its right column is 1, 1, 1 (the bar's left side). The filter multiplies the left column by −1, the middle by 0 and the right by +1: .
Now the formula. Write for the pixel in row , column . Write for the filter's weights, with rows and columns 0 to 2, and for a bias. The feature map's entry at row , column is
In words: put the filter's top-left corner on pixel , multiply each weight by the pixel under it, and add everything up, plus the bias. The sums over and walk over the 9 cells of the filter. The same appears for every and , which is weight sharing in symbols.
Convolution or cross-correlation?
In maths and signal processing, a convolution flips the filter before sliding it. Deep-learning libraries, PyTorch included, don't flip it. Strictly, what they compute is called cross-correlation. Since the network learns its filters, the flip makes no difference: it would learn the flipped filter instead.
What a filter finds
Predict first
The vertical-edge filter (columns −1, 0, +1) slides over an image of horizontal stripes. What does the feature map look like?
Choose a filter and an image below. You can also tap any cell of the filter to change its weight.
Image
Filter
tap a cell to change it
Feature map
Largest value 2.11 (green), smallest −2 (pink)
Green: the pattern is there. Pink: its opposite is. Pale: neither.
Things to notice:
- On the pepperoni slice, the vertical-edge filter lights up green on the pepperoni's left side and pink on its right side. The horizontal-edge filter does the same for its top and bottom.
- The spot filter (a bright plus with dark corners) peaks in the middle of the pepperoni. Its weights add up to 0, so flat cheese scores about 0. The dark herbs score negative.
- Blur averages each patch, so single dark herbs fade into the cheese.
- On the stripes, the vertical-edge filter gives a map of zeros, as the question above predicted.
If the pepperoni sat elsewhere, the bright spot in each map would move with it. That's the equivariance from the last lesson. The filter doesn't know or care where it is.
Learning the filters
Nobody sets a network's filters by hand. Each filter's 9 weights and its bias are parameters, like any other weights. Backpropagation gives each weight its gradient, and the optimiser nudges the filters towards whatever helps the loss.
A network built mostly from convolution layers is called a convolutional network (CNN). Here's the smallest useful one, the tiny network from the last lesson:
- Convolution with 4 filters of 3 × 3. Each 12 × 12 slice gives 4 feature maps of 10 × 10.
- ReLU, so each map keeps only the places where its pattern is present.
- Keep the biggest value in each map. That's 4 numbers: how strongly each filter fired anywhere on the slice.
- A linear layer turns those 4 numbers into 2 logits: plain or pepperoni.
Press play to train it on 200 slices with the pepperoni anywhere. The top row shows each filter's 9 weights. The bottom row shows its feature map on one test slice.
Step 0 · test accuracy 50%
Test slice
Filter 1
Filter 2
Filter 3
Filter 4
Top row: each filter’s 9 weights (green +, pink −). Bottom row: its feature map on the test slice, after ReLU.
Things to notice:
- At step 0, the filters are random noise, and the test accuracy is about 50%, a coin toss.
- By step 50, the network gets all 100 test slices right. The loss keeps falling after that, as the network grows more confident.
- Filters 2 and 3 become edge detectors. Filter 2 turns pink on top and green below: it fires where darker cheese sits above the bright pepperoni, along the pepperoni's top edge. Filter 3 fires on the pepperoni's top-right rim. Their maps light up around the pepperoni and nowhere else.
- Filters 1 and 4 barely change. Their starting weights are mostly negative, so ReLU makes their maps all zero on every slice. No gradient reaches them, so they never learn. Two good detectors are enough for this task.
DigressionStacking layers grows what each unit seesOne 3 × 3 layer sees 3 × 3 pixels. Two layers see 5 × 5. Real CNNs stack many. · 2 min
Each entry of a feature map looks at a 3 × 3 patch of the image. Now run a second 3 × 3 convolution over that feature map. Each of its entries looks at 3 × 3 entries of the first map. Each of those looks at its own 3 × 3 patch. Together they cover 5 × 5 pixels of the image.
The patch of the original image that one unit can see is its receptive field. With 3 × 3 filters, each layer adds 2 pixels: after layers it's .
1 layer of 3 × 3 filters: one unit sees 3 × 3 pixels
So early layers find small things (edges, spots) and later layers combine them into bigger things (a whole pepperoni, a slice, a pizza). The Convolutional networks course shows how real networks grow the receptive field faster, by shrinking the maps between layers.
DigressionConvolutions beyond imagesSound, time series and board games are grids too. · 2 min
A convolution needs data laid out on a grid, where nearby cells belong together and a pattern means the same thing wherever it is. Images are the classic case, but not the only one.
- Sound and time series are 1-D grids: one number per moment. A 1-D filter slides along time and finds short shapes, like a drum hit or a sudden jump in sales, whenever they happen.
- Board games are 2-D grids. AlphaGo, the program that beat a top professional Go player in 2016, read the 19 × 19 board with convolutional layers.
- Video games, read from the screen. DeepMind's 2015 Atari agent fed screen images through convolutional layers to choose its moves. The Reinforcement learning course comes back to it.
In each case, the assumption is the same as for images. If your data has no grid, or position carries meaning that must not be shared, a convolution is the wrong building block.
In PyTorch
Here's the worked example in PyTorch. The function F.conv2d (from torch.nn.functional) wants 4-D tensors, so the code adds two dimensions of size 1 to the image and to the filter.
# The lesson's 6×6 worked example: a bright bar (1s) on a dark background (0s).
BAR_IMAGE = torch.tensor(
[
[0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0],
],
dtype=torch.float32,
)
VERTICAL_EDGE = torch.tensor([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]], dtype=torch.float32)
def feature_map(image: torch.Tensor, filt: torch.Tensor) -> torch.Tensor:
"""Slide a filter over one greyscale image (no padding, step 1). F.conv2d wants 4-D tensors."""
x = image[None, None] # (6, 6) → (1, 1, 6, 6): a batch of 1 image with 1 channel
w = filt[None, None] # (3, 3) → (1, 1, 3, 3): 1 filter that reads 1 channel
return F.conv2d(x, w)[0, 0] # (1, 1, 4, 4) → (4, 4)feature_map(BAR_IMAGE, VERTICAL_EDGE) returns the 4 × 4 grid from the worked example. Its first two columns read 2, 3, 3, 2, and its last two read −2, −3, −3, −2.
In a network, you use the layer nn.Conv2d. It holds the filters as learnable weights. Its input has shape (batch, channels, height, width). A greyscale image has 1 channel; a colour photo has 3 (red, green and blue).
def conv_layer_shapes() -> dict[str, tuple[int, ...]]:
"""What nn.Conv2d(1, 4, kernel_size=3) does to a batch of 32 pizza images."""
torch.manual_seed(0)
conv = nn.Conv2d(in_channels=1, out_channels=4, kernel_size=3)
x = torch.rand(32, 1, 12, 12) # (batch, channels, height, width)
y = conv(x) # (32, 4, 10, 10): 4 feature maps per image, each 12 − 3 + 1 = 10 wide
return {
"input": tuple(x.shape),
"output": tuple(y.shape),
"weight": tuple(conv.weight.shape), # (4, 1, 3, 3): 4 filters, each reading 1 channel, 3×3
"bias": tuple(conv.bias.shape), # (4,): one bias per filter
}Read the shapes:
nn.Conv2d(1, 4, kernel_size=3): 1 channel in, 4 filters out, each 3 × 3.- Input
(32, 1, 12, 12): a batch of 32 greyscale slices. - Output
(32, 4, 10, 10): for each slice, 4 feature maps of by 10. Each filter's map becomes one output channel. - Weight
(4, 1, 3, 3): 4 filters, each reading 1 input channel, each 3 × 3. Bias(4,): one per filter.
The tiny CNN from the figure is four layers in an nn.Sequential. It trains with the Lesson 4 template unchanged; only the data and the model are new.
def make_cnn(filters: int = 4) -> nn.Sequential:
"""A one-layer convolutional network: 4 filters, ReLU, the biggest value in each map, then a linear layer."""
return nn.Sequential(
nn.Conv2d(1, filters, kernel_size=3), # (n, 1, 12, 12) → (n, 4, 10, 10)
nn.ReLU(),
nn.AdaptiveMaxPool2d(1), # (n, 4, 1, 1): how strongly each filter fired anywhere
nn.Flatten(), # (n, 4)
nn.Linear(filters, 2), # (n, 2) logits: plain or pepperoni
)def image_loaders(batch_size: int = 32, seed: int = 0) -> tuple[DataLoader, DataLoader]:
"""Training (200 slices) and test (100 slices) loaders, pixels scaled from 0–9 to 0–1."""
data = load("pizza-images")
def dataset(split: str) -> TensorDataset:
x = torch.tensor(data[split]["images"], dtype=torch.float32).reshape(-1, 1, 12, 12) / 9
return TensorDataset(x, torch.tensor(data[split]["y"]))
shuffle_gen = torch.Generator().manual_seed(seed)
return (
DataLoader(dataset("train"), batch_size=batch_size, shuffle=True, generator=shuffle_gen),
DataLoader(dataset("test"), batch_size=256),
)
def train_cnn(epochs: int = 40, seed: int = 0) -> tuple[nn.Sequential, list[dict]]:
seed_everything(seed)
model = make_cnn()
train_loader, test_loader = image_loaders(seed=seed)
history = fit(model, train_loader, test_loader, epochs=epochs, lr=0.01)
return model, historyIt reaches 100% on the 100 test slices.
nn.Conv2d has more options that this lesson leaves at their defaults. stride=2 moves the filter two pixels at a time. padding=1 adds a border of zeros so the map stays 12 × 12. Pooling layers such as nn.MaxPool2d(2) shrink each map by keeping the biggest value in every 2 × 2 block. The Convolutional networks course covers all three.
Common misconceptions
"Each position of the image has its own filter." There is one filter, and the same 9 weights are used at every position. That's what makes a convolution cheap and lets it find a pattern anywhere.
"A filter gives one number per image." It gives a whole grid, the feature map, with one number per position. Turning that grid into one number (like keeping its biggest value) is a separate step.
"The output is smaller because the convolution throws information away." That's not the reason. Without padding, a 3 × 3 filter fits in only places across a 12-pixel row. Padding the edges with zeros keeps the size the same.
"Someone has to design the edge filters." In this lesson, the hand-set filters show what a filter can do. In a real network, every filter is learned by gradient descent, and the network finds the patterns that help.
Recap
- A convolution slides a small filter over an image and takes a dot product with the patch at each position. The grid of results is a feature map.
- The same filter weights are used at every position, so a pattern is found wherever it appears, and the map moves when the pattern moves.
- A 3 × 3 filter on an image gives a map of without padding.
- A filter lights up where its pattern is: edges, spots or blur. A CNN learns its filters by gradient descent, like any other weights.
- Stacking layers grows the receptive field, so later layers find bigger patterns.
- PyTorch names used:
nn.Conv2d(input(batch, channels, height, width), weight(filters, channels, k, k)),F.conv2d,nn.AdaptiveMaxPool2d. - The Convolutional networks course builds deep image networks from here: stride, padding, pooling, and how to train them.