Level 8 · PractitionerLesson 8.2 40 min read 10 question quiz 12 marks of written practice

Convolutional Networks: From Pixels to Predictions

Pooling: keeping the strongest signal

After a convolution and ReLU, a pooling layer shrinks each feature map. Max pooling with a 2 × 2 window and stride 2 keeps only the largest value in each 2 × 2 block.

Max poolingA 4 by 4 feature map divided into four coloured 2 by 2 blocks: 1, 3, 4, 6; 0, 2, 1, 0; 0, 2, 1, 1; and 8, 5, 3, 7. In each block the largest value is highlighted: 6, 2, 2 and 8. Max pooling keeps only those, giving a 2 by 2 output of 6, 2, 2, 8. Notes: 16 values become 4, there are no parameters, small shifts change little, and the next layer sees a bigger patch.2 × 2 max pooling: keep the strongest value in each block1302461002851137feature map, 4 × 4max6228pooled, 2 × 2• 16 values become 4• no parameters to learn• small shifts matter less• later layers see more
Pooling summarises; it does not learn.
BenefitWhy
Smaller mapsA quarter of the values, so later layers are cheaper
Tolerance to small shiftsMoving a feature by one pixel usually keeps the same maximum
Larger view for later layersEach value now summarises a bigger patch of the original image

Pooling has no parameters to learn. Average pooling takes the mean instead of the maximum, and global average pooling averages each whole feature map down to a single number, which modern networks use just before the final layer.

The CNN architecture

A classic CNN repeats a pattern of convolution, ReLU and pooling, then finishes with dense layers:

The architecture of a CNNA pipeline of 3D blocks from left to right. The input image, 32 by 32 by 3, is a tall thin blue block. A convolution with ReLU gives 32 by 32 by 16, the same height but deeper, in violet. Max pooling halves it to 16 by 16 by 16, in teal. Another convolution gives 16 by 16 by 32, deeper again, and pooling gives 8 by 8 by 32. Then the volume is flattened into 2,048 numbers, a thin pink bar, followed by a dense layer of 128 and a softmax layer of 10 classes, shown as probabilities cat 0.82, dog 0.11 and fox 0.04.A small CNN: the maps get smaller while the channels multiplyinput32×32×3conv + ReLU32×32×16max pool16×16×16conv + ReLU16×16×32max pool8×8×32flatten2,048dense128softmax10cat 0.82dog 0.11fox 0.04feature detection: convolution, ReLU, pooling, repeated → classification: flatten, dense, softmax
Where becomes what: fewer positions, richer descriptions of each.
  1. Convolution + ReLU: detect features.
  2. Pooling: shrink the maps, keeping the strongest signals.
  3. Repeat, with more filters each time.
  4. Flatten the final volume into one long vector.
  5. Dense layers combine the features, ending in softmax over the classes.

Two trends run through the network: the spatial size shrinks (32 × 32, then 16 × 16, then 8 × 8) while the number of channels grows (3, then 16, then 32). The network trades "where" for "what": fewer positions, but richer descriptions of each.

What each layer learns

Each value in a deeper layer depends on a larger patch of the original image, called its receptive field. Two stacked 3 × 3 convolutions see a 5 × 5 patch; three see 7 × 7; pooling doubles the growth.

Receptive fields grow with depthThree tilted grids stacked like floors: the input, 7 by 7, at the bottom; layer 1, 5 by 5, in the middle; layer 2, 3 by 3, on top. One cell of layer 2 is highlighted. It depends on a highlighted 3 by 3 block of layer 1, each of which depends on 3 by 3 of the input, so it sees a highlighted 5 by 5 patch of the input. Dashed lines from the top cell to the corners of that patch form a cone.Each layer up sees a bigger patch of the imagelayer 2layer 1inputits receptive field growseach of those sees 3 × 35 × 5 in total
Stacked 3 × 3 convolutions see 5 × 5, then 7 × 7: bigger things deeper down.

So deeper layers can detect larger and more complex things. Researchers who visualised trained networks (Matthew Zeiler and Rob Fergus, 2013) found a clear hierarchy:

DepthTypical features
Layer 1Edges at different angles, colour blobs
Layer 2Corners, curves, simple textures
Layer 3Repeating patterns, mesh, text-like marks
Layer 4Object parts: eyes, wheels, legs
Layer 5Whole objects and faces

No one told the network to look for eyes or wheels. Those detectors emerged because they helped reduce the loss.

Famous architectures

YearNetworkKey ideaSize
1998LeNet-5 (Yann LeCun)Convolution and pooling for handwritten digits; read millions of bank chequesAbout 60 thousand parameters
2012AlexNetDeep CNN on GPUs with ReLU and dropout; won ImageNet by a huge margin8 layers, about 60 million parameters
2014VGG-16Only small 3 × 3 kernels, stacked deep16 layers, 138 million parameters
2014GoogLeNet (Inception)Parallel kernels of several sizes in each block22 layers, about 7 million parameters
2015ResNetResidual (shortcut) connectionsUp to 152 layers and beyond
2019EfficientNetScaling depth, width and resolution togetherSmall and very accurate
2020Vision Transformer (ViT)Treats image patches like words, using attention (Level 10)From tens of millions of parameters up

Residual connections

Before 2015, adding more layers past about 20 made networks worse, even on their training data: the gradients could not get through. The ResNet team, led by Kaiming He, added a shortcut that carries a block's input straight past it and adds it to the output:

Residual block

output = F(x) + x, where F is a couple of convolution layers

A residual blockAn input x passes through a 3 by 3 convolution, a ReLU and another 3 by 3 convolution, which compute F of x, the change to learn. An orange shortcut arc carries x straight past the layers to an adding node, giving the output F of x plus x. A dashed red arrow below shows the gradient flowing straight back along the shortcut during training, so it cannot vanish.A residual block: learn the change, keep the originalxconv 3×3ReLUconv 3×3+F(x) + xF(x): the layers learn only the changeidentity shortcut: x skips the layers and is added backbackward: the gradient also flows straight back along the shortcut, so it cannot vanish
If a block has nothing useful to add, it can learn F(x) = 0 and pass x through untouched.

The block now only has to learn the change F(x) to make to its input, and if no change helps it can push F towards zero and pass x through untouched. During backpropagation, the gradient flows straight back along the shortcut, so even the earliest layers receive a strong learning signal. Residual connections are now everywhere, including inside every transformer.

Making vision models work in practice

Data augmentation

Show the network modified copies of each training image: flipped, cropped, rotated slightly, with brightness and colour changed. The label stays the same, so the network learns that these changes do not matter, and it sees far more variety than the dataset contains.

Data augmentationA pixel-art cat on a blue background, labelled cat, becomes six training examples: flipped left to right, rotated slightly, cropped and zoomed, made brighter, with its colours shifted, and with random noise added. Each is still labelled cat.Data augmentation: one labelled image, many training examplesoriginallabel: catstilla catflippedstilla catrotatedstilla catcropped and zoomedstilla catbrighterstilla catcolours shiftedstilla catnoisy
The network learns that flips, crops and lighting do not change what the object is.

Other essentials

  • Dropout: during training, randomly switch off a fraction of neurons (often half) at each step, so the network cannot rely on any single one. It is a strong defence against overfitting.
  • Batch normalisation: rescale each layer's outputs to a steady mean and spread during training, which makes deep networks train faster and more reliably.
  • Transfer learning: start from a network already trained on ImageNet, keep its convolutional layers as a feature extractor, and train only a new final layer on your own small dataset. A few hundred images can then be enough.

Beyond "what is in the picture?"

TaskOutputExample
ClassificationOne label for the image"golden retriever"
Object detectionA box and a label for every objectA self-driving car finding pedestrians; YOLO (2015) does it in real time
SegmentationA label for every pixelOutlining a tumour on a scan; U-Net (2015)
Face recognitionAn embedding per face, compared by distancePhone unlock

Hands-on: a hand-built CNN

Max pooling

Python
def max_pool(grid, size=2):
    out = []
    for r in range(0, len(grid), size):
        row = []
        for c in range(0, len(grid[0]), size):
            row.append(max(grid[r + i][c + j] for i in range(size) for j in range(size)))
        out.append(row)
    return out

feature_map = [[1, 3, 0, 2],
               [4, 6, 1, 0],
               [0, 2, 8, 5],
               [1, 1, 3, 7]]
print(max_pool(feature_map))

Line detector: convolution, ReLU, pooling, decision

This tiny CNN has two fixed kernels, one for horizontal lines and one for vertical lines. It convolves, applies ReLU, takes the global maximum of each feature map, and picks the larger.

Python
def conv2d(img, k):
    n = len(img)
    return [[sum(img[r + i][c + j] * k[i][j] for i in range(3) for j in range(3))
             for c in range(n - 2)] for r in range(n - 2)]

def relu_max(grid):
    return max(max(0, v) for row in grid for v in row)

horizontal = [[-1, -1, -1], [2, 2, 2], [-1, -1, -1]]
vertical = [[-1, 2, -1], [-1, 2, -1], [-1, 2, -1]]

def blank():
    return [[0] * 6 for _ in range(6)]

h_line, v_line, cross = blank(), blank(), blank()
for i in range(1, 5):
    h_line[2][i] = 1
    v_line[i][3] = 1
    cross[2][i] = cross[i][2] = 1

for name, img in [("horizontal line", h_line), ("vertical line", v_line), ("cross", cross)]:
    h = relu_max(conv2d(img, horizontal))
    v = relu_max(conv2d(img, vertical))
    verdict = "horizontal" if h > v else "vertical" if v > h else "both equally"
    print(f"{name:15}: horizontal score {h}, vertical score {v} -> {verdict}")

A real CNN does exactly this, except that it learns dozens of kernels per layer instead of using two we chose, stacks many layers, and learns the final decision too.

Data augmentation by flipping

Python
image = [[1, 2, 3],
         [4, 5, 6],
         [7, 8, 9]]
flipped = [row[::-1] for row in image]          # mirror left to right
rotated = [list(row) for row in zip(*image[::-1])]  # rotate 90 degrees clockwise
print("original:", image)
print("flipped: ", flipped)
print("rotated: ", rotated)

Try this

  1. Add a diagonal line image. What do the two detectors say? Design a third kernel for diagonals.
  2. Pool the feature map with size 4. What single number do you get, and what does it mean?

Level check

  • Explain max pooling and give three benefits of pooling
  • Describe the layers of a classic CNN and how the shape of the data changes through it
  • Explain receptive fields and the hierarchy of features a CNN learns
  • Name three famous CNN architectures and the key idea each introduced
  • Explain how residual connections work and why they let networks go deeper
  • Describe data augmentation, dropout and transfer learning

Key terms you must be able to define

Pooling
Shrinking a feature map by summarising each small block, usually by its maximum.
Max pooling
Keeping only the largest value in each window, such as each 2 × 2 block.
Flatten
Turning a volume of feature maps into one long vector for the dense layers.
Receptive field
The patch of the original image that one value in a layer depends on.
Feature hierarchy
Simple features in early layers combining into complex ones in later layers.
Residual connection
A shortcut that adds a block's input to its output, so the block learns only the change: F(x) + x.
Data augmentation
Training on modified copies of the data, such as flipped or cropped images, to add variety.
Dropout
Randomly switching off neurons during training so the network cannot rely on any one of them.
Batch normalisation
Rescaling a layer's outputs during training to keep their mean and spread steady.
Object detection
Finding every object in an image, with a bounding box and a label for each.
Segmentation
Labelling every pixel of an image with the class it belongs to.

Flashcards

DefinePooling
AnswerShrinking a feature map by summarising each small block, usually by its maximum.
DefineMax pooling
AnswerKeeping only the largest value in each window, such as each 2 × 2 block.
DefineFlatten
AnswerTurning a volume of feature maps into one long vector for the dense layers.
DefineReceptive field
AnswerThe patch of the original image that one value in a layer depends on.
DefineFeature hierarchy
AnswerSimple features in early layers combining into complex ones in later layers.
DefineResidual connection
AnswerA shortcut that adds a block's input to its output, so the block learns only the change: F(x) + x.
DefineData augmentation
AnswerTraining on modified copies of the data, such as flipped or cropped images, to add variety.
DefineDropout
AnswerRandomly switching off neurons during training so the network cannot rely on any one of them.

Go further: notes for future AI engineers

Why residual connections fix the gradient

In a plain deep network the gradient reaching layer 1 is a product of one factor per layer, so it vanishes or explodes. With a residual block y = F(x) + x, the derivative of y with respect to x is F′(x) + 1. The "+ 1" means that even if F′ is tiny, the gradient passes back almost unchanged along the identity path, and stacking blocks adds paths of every length instead of multiplying one long chain. A ResNet behaves somewhat like an ensemble of many shallower networks.

The cost of convolution

A convolutional layer's parameter count is small, but its compute is not: a 3 × 3 kernel with 64 input and 64 output channels on a 112 × 112 map needs about 3 × 3 × 64 × 64 × 112 × 112, roughly 460 million multiply-adds, for one image. Efficient architectures such as MobileNet split it into a cheap per-channel convolution and a 1 × 1 convolution that mixes channels (a depthwise separable convolution), cutting the cost about eightfold, which is how vision models run on phones.

Misconceptions to avoid

Avoid these
  • Thinking pooling layers learn something. They have no parameters at all.
  • Expecting the spatial size to grow through a CNN. It shrinks while the number of channels grows.
  • Believing deeper always meant better before ResNet. Plain networks got worse past about 20 layers.
  • Applying augmentation that changes the label, such as flipping a 6 into a 9, or a left arrow into a right arrow.
  • Forgetting to switch dropout off when using the model. It is only for training.
Fun fact

In 2015 a ResNet with 152 layers made only 3.57% top-5 errors on the ImageNet challenge, lower than the roughly 5% error rate estimated for a careful human on the same task.

Knowledge check

0 of 10 answered
1What does 2 × 2 max pooling do to the block [1, 3 / 4, 6]?
2How many parameters does a max pooling layer have?
3Through a classic CNN, what happens to the feature maps?
4What is a receptive field?
5Which features do the first layers of a trained CNN typically detect?
6What does a residual connection compute?
7Which network introduced residual connections in 2015?
8Which is a sensible data augmentation for photos of cats and dogs?
9What is dropout?
10A school has 300 labelled photos of local birds. What is the most practical approach?
Score 0 / 10

Check you could explain this

12 marks
1Describe the structure of a typical convolutional neural network for classifying images.5 marks
Describe

Mark scheme0 / 5
  • LConvolutional layers with filters detect features
  • LReLU activation after each convolution
  • LPooling layers shrink the feature maps
  • LRepeated, with spatial size shrinking and channels growing
  • LFlatten, dense layers and softmax output
Model answer

A typical CNN starts with convolutional layers, in which many filters slide over the image to detect features, each followed by a ReLU activation. Pooling layers, usually 2 × 2 max pooling, then shrink the feature maps. This pattern of convolution, ReLU and pooling is repeated several times, so the maps get smaller in width and height while the number of channels grows. Finally the volume is flattened into a vector, passed through one or more dense layers, and a softmax output layer gives a probability for each class.

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

2Explain how residual connections allow very deep networks to be trained.4 marks
Explain

Mark scheme0 / 4
  • LA shortcut adds the block's input to its output: F(x) + x
  • LThe block only has to learn the change / can pass the input through
  • LGradients flow back directly along the shortcut
  • LSo they do not vanish, and early layers still learn
Model answer

A residual connection adds a shortcut around a block of layers, so the block's output is F(x) + x: its input added to whatever the layers compute. The layers therefore only need to learn the change to make to the input, and if nothing helps they can learn to pass the input through unchanged. During backpropagation the gradient flows straight back along the shortcut, so it does not vanish as it passes through many layers, and even the earliest layers receive a strong learning signal. This let networks grow from about 20 layers to more than 150.

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 how transfer learning helps when only a small dataset is available.3 marks
Explain

Mark scheme0 / 3
  • LStart from a network pretrained on a large dataset such as ImageNet
  • LIts early layers already detect general features such as edges and shapes
  • LOnly a new final layer, or a little fine-tuning, is trained on the small dataset
Model answer

Transfer learning starts from a network that has already been trained on a huge dataset such as ImageNet. Its convolutional layers have already learned to detect general features such as edges, textures, shapes and object parts, which are useful for almost any image task. So only a new final layer, plus perhaps a little fine-tuning of the later layers, needs to be trained on the small dataset, which can work well with only a few hundred examples and far less computing.

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 / 12