AI from scratch · Chapter 6

Seeing: convolutions

A photo of a cat and the same photo shifted one pixel to the left are, number by number, completely different. Yet they're obviously the same cat. A plain network from chapter 3 would have to learn "cat" separately at every position. Convolutional networks don't: they slide one small detector across the whole image. This chapter builds one and trains it, right here in your browser, to read digits you draw.

1. A picture is a grid of numbers

Draw a digit in the box. To a network it's 28 × 28 = 784 numbers between 0 (black) and 1 (white), the same size as the classic MNIST dataset of handwritten digits. Hover over the small copy to see the numbers.

draw here ·
28 × 28, centered like MNIST

Hover over the 28 × 28 image to read its pixels.

The pictureA photo is a mosaic: every tile has one brightness.
The mathA matrix \(I\) with \(I[r][c] \in [0, 1]\): row \(r\), column \(c\). Color images have three of them stacked (red, green, blue), a 3-D array.

How many numbers describe a 28 × 28 color image?

\(28 \times 28 \times 3 = 2{,}352\): a red, a green and a blue value per pixel.

To a network a picture is a grid of brightness numbers; color stacks three grids.

2. A filter slides over it

A filter (or kernel) is a tiny grid of weights, here 3 × 3. Put it on a spot of the image, multiply the 9 pixels under it by its 9 weights, add them up: that's one output number. Slide it to every position and you get a new image, the feature map. The filter below finds edges where the image goes from dark (left) to bright (right). Pick others, and hover the output to see the arithmetic.


the filter
feature map (blue −, orange +)

Hover over the feature map.

The same 9 weights are used everywhere, so the filter finds a vertical edge wherever it is. That's the trick: weight sharing. A network layer has many filters side by side, each looking for its own pattern, and the next layer's filters look at those maps, finding edges of edges: corners, loops, strokes, and eventually whole shapes. Between layers a pooling step keeps only the strongest response in each 2 × 2 patch, so the network cares less about exactly where a stroke is.

The math, step by step

Put the filter's top-left corner at row \(r\), column \(c\), multiply, add. For a \(3 \times 3\) filter \(K\):

\[ F[r][c] = \sum_{i=0}^{2} \sum_{j=0}^{2} I[r + i][c + j] \cdot K[i][j] \]

That's chapter 1's dot product again, between the filter and one patch of the image, both flattened into lists of 9. (Mathematicians would flip the filter first and call this a cross-correlation; networks skip the flip, since the filter is learned anyway.)

Worked example. The vertical-edge filter is \(\begin{pmatrix} -1 & 0 & 1 \\ -2 & 0 & 2 \\ -1 & 0 & 1 \end{pmatrix}\). On a patch that's dark (0) on the left and bright (1) on the right: \((-1 - 2 - 1)\cdot 0 + (1 + 2 + 1) \cdot 1 = 4\), a strong response. On a flat patch, all 1: the weights add up to 0, so the response is 0. Bright on the left: −4. The sign tells the edge's direction.

Sizes. A \(k \times k\) filter fits in \(n - k + 1\) positions along an \(n\)-pixel side: 28 − 3 + 1 = 26, which is why the feature map above is 26 × 26. Padding the border with zeros keeps the size; a stride \(s\) (jumping \(s\) pixels at a time) gives \(\lfloor (n - k)/s \rfloor + 1\).

The vertical-edge filter lands on a patch where every pixel is 0.6. What does it output?

\(0.6 \times (\text{sum of weights}) = 0.6 \times 0 = 0\). Filters whose weights add up to zero ignore flat areas and react only to change.

The network below slides 5 × 5 filters over the 28 × 28 image (no padding, stride 1). How wide is each feature map?

\(28 - 5 + 1 = 24\). Then 2 × 2 pooling halves it to 12.

A filter is one small dot product slid everywhere, so it finds its pattern wherever the pattern is.

Why sharing one filter everywhere works so well
  1. Each output \(F[r][c]\) depends only on the patch at \((r, c)\). So shift the image one pixel right and the whole feature map shifts one pixel right, unchanged otherwise. A vertical edge is found the same way at every position.
  2. That matches photos: an edge, an eye or a wheel looks the same wherever it is in the frame. A dense layer would have to learn "edge" separately at every position, from examples at every position.
  3. The saving in numbers: a dense layer making the same 8 × 24 × 24 = 4,608 outputs from 784 pixels needs \(784 \times 4{,}608 \approx 3.6\) million weights; 8 shared 5 × 5 filters need 200.
  4. Fewer numbers to fit means less data needed and less overfitting (chapter 11): the architecture already "knows" that patterns are local and can be anywhere.
  5. Stacking adds reach: two 3 × 3 layers see a 5 × 5 patch of the image, three see 7 × 7. Deep layers end up looking at whole objects built from the edges below.

3. Train a network that reads digits

Our network: 8 filters of 5 × 5 (learned, not hand-picked) → ReLU → 2 × 2 max pooling → one dense layer of 10 outputs → softmax (chapter 5). About 12,000 weights. It trains on digits drawn in your computer's fonts, randomly rotated, scaled and thickened, with backprop (chapter 4) written out by hand in this page. Press train and watch the filters grow from noise into stroke detectors.

The math: counting weights, and backprop through a filter

Count. 8 filters × 25 weights + 8 biases = 208. After pooling there are \(8 \times 12 \times 12 = 1{,}152\) numbers, and the dense layer maps them to 10 scores: \(1{,}152 \times 10 + 10 = 11{,}530\). Total 11,738. A plain dense layer producing the same 8 × 24 × 24 = 4,608 numbers from 784 pixels would need \(784 \times 4{,}608 \approx 3.6\) million weights. Weight sharing is a 17,000× saving, and it builds in the rule "an edge is an edge wherever it is".

Backward through a convolution. Each filter weight \(K[i][j]\) touched every output \(F[r][c]\), multiplied by the pixel \(I[r+i][c+j]\). Chapter 4's rule "blame from every use adds up" gives

\[ \frac{\partial L}{\partial K[i][j]} = \sum_{r, c} \frac{\partial L}{\partial F[r][c]} \cdot I[r + i][c + j] \]

which is itself a convolution: of the image with the map of blame. Max pooling passes each blame back only to the pixel that won the max (the others didn't affect the output). ReLU passes it through where the input was positive and blocks it where it was zero.

In a 2 × 2 max pool, the four inputs are (0.1, 0.9, 0.3, 0.2). Blame 1.0 arrives at the output. How is it passed back?

The output is the 0.9 input, so its slope is 1 for that input and 0 for the rest.

the 8 learned 5 × 5 filters

their feature maps for your drawing

Training learns the filters themselves, by sending blame back through every place each filter was used.

4. Draw, and it reads

Draw a digit in the box at the top (or below, it's the same drawing) and the network gives its probabilities. Draw big, roughly centered, with one continuous shape like the printed digits it learned from.

Train the network first (section 3).

It will make mistakes, especially on digits drawn very differently from fonts: it has only ever seen typefaces. Real digit readers train on tens of thousands of real handwritten samples (MNIST has 60,000), with more layers. But it's the same machine: filters that slide, pooling that forgives, a softmax that votes, and gradient descent that tunes every weight. Next: what happens when the input isn't a grid but a sentence: attention and transformers.

A small CNN is the whole machine at toy size: shared filters, pooling that forgives small shifts, a softmax that votes.

Where it breaks: shifts, turns and textures

All chapters: AI from scratch. Inspired by 3Blue1Brown's But what is a convolution?

Last updated