Level 8 · PractitionerLesson 8.1 38 min read 10 question quiz 11 marks of written practice

Convolutions: How Machines See Edges and Shapes

Why not a plain dense network?

A modest 224 × 224 colour photo has 150,528 input numbers (Level 3). A dense first layer of just 1,000 neurons would need 150 million weights, before the network has learned anything. Worse, a dense layer ignores the structure of an image:

  • It treats the pixel in the top-left corner and its neighbour as unrelated inputs, though neighbouring pixels belong together.
  • A cat in the corner and a cat in the centre activate completely different weights, so it would have to learn "cat" separately for every position.

Two ideas fix both problems:

IdeaMeaningBenefit
Local connectionsEach output looks at a small patch of the image, such as 3 × 3 pixelsNearby pixels are processed together
Weight sharingThe same small set of weights is used at every positionFar fewer parameters, and a feature learned in one place is recognised everywhere

Together they give the convolution, the operation at the heart of a convolutional neural network (CNN).

The convolution operation

A kernel (or filter) is a small grid of weights, usually 3 × 3. It slides across the image. At each position:

  1. Lay the kernel over a patch of the image.
  2. Multiply each kernel weight by the pixel under it.
  3. Add up the nine products. That sum is one number of the output.
A convolution, step by stepA stepped animation. A 6 by 6 greyscale image is dark on the left and bright on the right, with the boundary one column further left in the bottom three rows. A 3 by 3 kernel with columns of minus 1, 0 and 1 detects vertical edges. An amber window slides across the image; at each position the sum of the right column minus the left column fills one cell of a 4 by 4 feature map. The finished map reads, row by row: 0, 27, 27, 0; 9, 27, 18, 0; 18, 27, 9, 0; 27, 27, 0, 0. It is large where the window straddles the edge and 0 on flat areas.Convolution: multiply the patch by the kernel, add, move oninput image, 6 × 6000999000999000999009999009999009999kernel−101−101−101vertical edgesfeature map, 4 × 40row by row: (0 − 0) + (0 − 0) + (0 − 0) = 0270row by row: (9 − 0) + (9 − 0) + (9 − 0) = 2727270row by row: (9 − 0) + (9 − 0) + (9 − 0) = 27272700row by row: (9 − 9) + (9 − 9) + (9 − 9) = 02700279row by row: (0 − 0) + (0 − 0) + (9 − 0) = 9270270279row by row: (9 − 0) + (9 − 0) + (9 − 0) = 2727270270279row by row: (9 − 0) + (9 − 0) + (9 − 0) = 27272702702790row by row: (9 − 9) + (9 − 9) + (9 − 9) = 0027270927180182790272700the feature map is brightest exactly where the image has a vertical edge
The same nine weights are used at every position: weight sharing.

Press Play to watch the kernel slide. The output grid, called a feature map, records how strongly the kernel's pattern appears at each position.

A worked patch

Patch of the imageKernelProducts
0, 0, 9−1, 0, 10, 0, 9
0, 0, 9−1, 0, 10, 0, 9
0, 0, 9−1, 0, 10, 0, 9

The sum is 27: a strong response. This kernel subtracts the left column from the right column, so it responds wherever the image gets brighter from left to right: a vertical edge. On a flat patch, all the same brightness, the left and right cancel and it outputs 0.

It is a dot product again

Flatten the patch and the kernel into lists of nine numbers and the convolution at one position is their dot product, plus a bias. A convolutional layer is a neuron with nine weights, reused at every position of the image.

Kernels that find features

Different kernels detect different patterns.

Kernels and their feature mapsA 14 by 14 picture of a bright house on a dark background, with a pointed roof and a dark door, passed through four kernels. The vertical edge kernel lights up the walls and door edges, pink on the left of bright areas and blue on the right. The horizontal edge kernel lights up the roof line, the floor and the top of the door. The blur kernel, every weight one ninth, gives a softened copy. The sharpen kernel, 5 in the centre and minus 1 on four sides, exaggerates the outline.One picture, four kernels, four different feature mapsinputvertical edges−1 0 1−2 0 2−1 0 1horizontal edges−1 −2 −10 0 01 2 1blur1 1 11 1 1 ÷ 91 1 1sharpen0 −1 0−1 5 −10 −1 0pink: strong positive response · blue: strong negative · edge maps outline the house
A CNN learns its own kernels, and the first layer's often look just like these.
KernelWeightsWhat it finds
Vertical edges (Sobel)−1 0 1 / −2 0 2 / −1 0 1Left-to-right changes in brightness
Horizontal edges (Sobel)−1 −2 −1 / 0 0 0 / 1 2 1Top-to-bottom changes
Blurevery weight 1/9The average of the neighbourhood, smoothing noise
Sharpen0 −1 0 / −1 5 −1 / 0 −1 0Exaggerates differences from the neighbours

For decades, computer vision engineers designed kernels like these by hand. The breakthrough of convolutional networks is that the kernel weights are parameters: they are learned by backpropagation, like any other weights. When researchers look inside trained networks, the first layer's kernels turn out to be edge detectors, colour blobs and stripe detectors, very like the ones people designed, plus many nobody had thought of.

Convolution lab

Draw a picture, choose or design a 3 × 3 kernel, and see the feature map it produces. This tool needs JavaScript, so turn it on to use it. Everything you need to answer the exam question is explained in the text above.

Draw a shape in the lab, then try each kernel and watch which parts of your drawing light up in the feature map.

Stride, padding and the output size

Two settings control how the kernel moves.

  • Stride: how many pixels the kernel jumps each time. Stride 1 visits every position; stride 2 skips every other one and halves the output size.
  • Padding: a border of zeros added around the image, so the kernel can be centred on edge pixels too. "Same" padding keeps the output the same size as the input; "valid" (no padding) shrinks it.
Padding and strideTwo panels. With padding 1 and stride 1, a 5 by 5 image is surrounded by a ring of zeros, so a 3 by 3 window can sit on the corner pixel, and the output is also 5 by 5. With no padding and stride 2, a 3 by 3 window on a 7 by 7 image jumps two pixels at a time, shown by three outlined positions along the top row, giving a 3 by 3 output: 7 minus 3, divided by 2, plus 1, equals 3.Padding keeps the size; a bigger stride shrinks itpadding 1, stride 1: 5 × 5 in, 5 × 5 out000000000000000000000000the kernel can now sit on the corner pixelno padding, stride 2: 7 × 7 in, 3 × 3 outthe window jumps 2 pixels each time(7 − 3) ÷ 2 + 1 = 3
Output size = (n + 2p − k) ÷ s + 1.
Output size

output = (n + 2p − k) ÷ s + 1, for an n × n input, a k × k kernel, padding p and stride s

Input nKernel kPadding pStride sOutput
6301(6 − 3) ÷ 1 + 1 = 4
6311(6 + 2 − 3) ÷ 1 + 1 = 6
7312(7 + 2 − 3) ÷ 2 + 1 = 4
224732(224 + 6 − 7) ÷ 2 + 1 = 112 (rounded down)

Colour images and many filters

A colour image has three channels, so a kernel for it is a small block: 3 × 3 × 3, with 27 weights covering the red, green and blue values of a patch at once, plus a bias. Its output is still a single number per position, so one kernel produces one feature map.

A convolutional layer uses many kernels, often 32, 64 or more, each learning to detect a different pattern. Their feature maps are stacked into an output volume, which becomes the input to the next layer.

A convolutional layer on a colour imageOn the left an input volume of 32 by 32 by 3, three stacked slabs for the red, green and blue channels. A small amber block, a 3 by 3 by 3 kernel, sits on it, covering all three channels of a patch. Dashed lines lead from it to one cell of an output volume on the right, a stack of 8 coloured feature maps, 32 by 32 by 8, one per filter. A note says each filter has 27 weights and a bias, gives one number per position, and 8 filters make 224 parameters.On colour images a kernel is a small block; many filters make a stack of mapsinput: 32 × 32 × 3red, green and blue channels3×3×327 weights + 1 biasone number per position× 8 different filters= 224 parametersoutput: 32 × 32 × 88 feature maps, one per filter
Each filter spans every input channel and produces one feature map.
Parameters in a convolutional layer

(k × k × input channels + 1) × number of filters

A layer of 64 filters of size 3 × 3 over a colour image has (3 × 3 × 3 + 1) × 64 = 1,792 parameters, whatever the size of the image. Compare that with the 150 million of the dense layer, and you see why convolution made computer vision practical.

Hands-on: convolution from scratch

Finding the edges of a bar

Python
image = [[0] * 8 for _ in range(8)]
for row in range(1, 7):
    image[row][3] = image[row][4] = 9           # a bright vertical bar

def conv2d(img, kernel):
    n, k = len(img), len(kernel)
    out = []
    for r in range(n - k + 1):
        row = []
        for c in range(n - k + 1):
            row.append(sum(img[r + i][c + j] * kernel[i][j]
                           for i in range(k) for j in range(k)))
        out.append(row)
    return out

def show(grid):
    for row in grid:
        print(" ".join(f"{v:4}" for v in row))

vertical = [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]
horizontal = [[-1, -2, -1], [0, 0, 0], [1, 2, 1]]
print("Vertical edges:")
show(conv2d(image, vertical))
print("Horizontal edges:")
show(conv2d(image, horizontal))

The vertical edge kernel lights up down both sides of the bar: positive where the image gets brighter to the right, negative where it gets darker. The horizontal kernel only fires at the bar's top and bottom ends.

Output sizes and parameter counts

Python
def output_size(n, k, padding=0, stride=1):
    return (n + 2 * padding - k) // stride + 1

print("6x6, 3x3 kernel, no padding:", output_size(6, 3))
print("6x6, 3x3 kernel, padding 1:", output_size(6, 3, padding=1))
print("224x224, 7x7 kernel, padding 3, stride 2:", output_size(224, 7, 3, 2))

def conv_params(k, channels_in, filters):
    return (k * k * channels_in + 1) * filters

def dense_params(inputs, neurons):
    return inputs * neurons + neurons

print(f"Conv layer, 64 filters of 3x3 on RGB: {conv_params(3, 3, 64):,} parameters")
print(f"Dense layer, 224x224x3 to 1,000 neurons: {dense_params(224 * 224 * 3, 1000):,} parameters")

Try this

  1. Add a blur kernel, with every weight 1/9, and run it on the bar. What happens to the bar's edges?
  2. Make the bar diagonal instead. Which kernel responds more strongly now?
  3. Design a 3 × 3 kernel that responds to a single bright pixel surrounded by dark ones.

Level check

  • Explain two problems with using dense layers for images, and how local connections and weight sharing fix them
  • Calculate one output value of a convolution by hand
  • Describe what edge, blur and sharpen kernels do, and explain how CNNs get their kernels
  • Use the formula to work out the output size for a given stride and padding
  • Explain how kernels work on colour images and what a layer of many filters produces
  • Calculate the number of parameters in a convolutional layer

Key terms you must be able to define

Convolution
Sliding a small kernel across an image and taking the weighted sum of each patch it covers.
Kernel (filter)
A small grid of weights, such as 3 × 3, that detects one pattern wherever it appears.
Feature map
The grid of outputs produced by one kernel, showing where its pattern appears.
Weight sharing
Using the same kernel weights at every position, so a pattern learned once is found everywhere.
Local connection
Each output depends only on a small patch of the input.
Stride
How many pixels the kernel moves between positions.
Padding
A border of zeros added around the input so the kernel can cover the edges.
Channel
One layer of an input or output volume, such as red, or one feature map.
Convolutional neural network (CNN)
A network built mainly from convolutional layers, the standard architecture for images.
Edge detector
A kernel that responds to sudden changes in brightness, such as the Sobel kernels.

Flashcards

DefineConvolution
AnswerSliding a small kernel across an image and taking the weighted sum of each patch it covers.
DefineKernel (filter)
AnswerA small grid of weights, such as 3 × 3, that detects one pattern wherever it appears.
DefineFeature map
AnswerThe grid of outputs produced by one kernel, showing where its pattern appears.
DefineWeight sharing
AnswerUsing the same kernel weights at every position, so a pattern learned once is found everywhere.
DefineLocal connection
AnswerEach output depends only on a small patch of the input.
DefineStride
AnswerHow many pixels the kernel moves between positions.
DefinePadding
AnswerA border of zeros added around the input so the kernel can cover the edges.
DefineChannel
AnswerOne layer of an input or output volume, such as red, or one feature map.

Go further: notes for future AI engineers

Convolution or cross-correlation?

Strictly, the operation in this lesson is cross-correlation: a true mathematical convolution flips the kernel first. Because a CNN learns its kernels, the flip makes no difference (it would simply learn the flipped kernel), so deep learning libraries implement cross-correlation and call it convolution. It is worth knowing when you read signal-processing texts.

Translation equivariance

Because the same kernel is applied everywhere, shifting the input shifts the feature map by the same amount: convolution is translation equivariant. That is the built-in assumption, the inductive bias, that makes CNNs so data-efficient for images. Pooling and the final layers then make the overall answer roughly invariant to position: a cat is a cat wherever it sits. Vision transformers (Level 10) drop this assumption and must learn it from much more data.

Misconceptions to avoid

Avoid these
  • Thinking a kernel's weights are designed by people in a CNN. They are learned by backpropagation.
  • Forgetting that a kernel on a colour image covers all three channels, so a 3 × 3 kernel has 27 weights, not 9.
  • Leaving the padding out of the output size formula, or forgetting to round down when the stride does not divide evenly.
  • Believing a convolutional layer's parameter count depends on the image size. It depends only on the kernel size, channels and number of filters.
  • Confusing a feature map with the kernel. The kernel is the small grid of weights; the feature map is its output.
Fun fact

Image filters in photo apps, such as blur, sharpen and edge detection, are convolutions with kernels a person designed. A convolutional network uses exactly the same operation, but learns the numbers in its kernels by itself.

Knowledge check

0 of 10 answered
1Why is a dense layer a poor first layer for photos?
2What does weight sharing in a convolutional layer mean?
3A 3 × 3 patch is all 4s and the kernel is all 1s. What is the output?
4Which kernel detects vertical edges?
5What size is the output of a 3 × 3 kernel on a 6 × 6 image, with no padding and stride 1?
6What does padding of 1 do for a 3 × 3 kernel with stride 1?
7How many weights does one 3 × 3 kernel have when it works on an RGB image?
8A convolutional layer has 32 filters of size 3 × 3 over 3 input channels. How many parameters does it have?
9What is a feature map?
10How does a CNN get the weights for its kernels?
Score 0 / 10

Check you could explain this

11 marks
1Explain how a convolutional layer processes an image.4 marks
Explain

Mark scheme0 / 4
  • LA small kernel / filter of weights
  • LSlides across the image, position by position
  • LAt each position multiplies the patch by the weights and sums
  • LProducing a feature map showing where the pattern occurs
Model answer

A convolutional layer uses small kernels, grids of weights such as 3 × 3. Each kernel slides across the image, one position at a time according to the stride. At each position it multiplies every weight by the pixel beneath it and adds the products, plus a bias, giving one number. The numbers from all the positions form a feature map, showing how strongly the kernel's pattern, such as a vertical edge, appears at each place in the image. A layer with many kernels produces many feature maps.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.

Think this answer or mark scheme is wrong? Report it

2Calculate the output size of a convolution on a 32 × 32 input with a 5 × 5 kernel, padding 2 and stride 1, and the number of parameters if the input has 3 channels and the layer has 16 filters.4 marks
Calculate

Mark scheme0 / 4
  • L(32 + 4 − 5) ÷ 1 + 1
  • LOutput is 32 × 32
  • L(5 × 5 × 3 + 1) = 76 per filter
  • L× 16 = 1,216 parameters
Model answer

Output size = (n + 2p − k) ÷ s + 1 = (32 + 4 − 5) ÷ 1 + 1 = 32, so the output is 32 × 32. Each filter has 5 × 5 × 3 = 75 weights plus 1 bias, which is 76 parameters, so 16 filters have 76 × 16 = 1,216 parameters.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.

Think this answer or mark scheme is wrong? Report it

3Explain why convolutional networks need far fewer parameters than dense networks for images.3 marks
Explain

Mark scheme0 / 3
  • LEach output connects only to a small local patch
  • LThe same kernel weights are shared across every position
  • LSo the count depends on kernel size and filters, not image size
Model answer

In a convolutional layer each output depends only on a small local patch of the image, such as 3 × 3 pixels, rather than on every pixel. The same kernel weights are also shared across every position in the image. So the number of parameters depends only on the kernel size, the number of input channels and the number of filters, not on the size of the image, which keeps it to thousands instead of hundreds of millions.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.

Think this answer or mark scheme is wrong? Report it

Machine mark 0 / 11