Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 17: From Dense Networks to Convolutional Layers

Open in Colab

The ability of convolutional networks to learn the features themselves is what made them work.

after Yann LeCun

17.1 Why Dense Networks Fall Short

Chapter 15’s networks are fully connected (dense): every input is connected to every unit of the first layer. For images, that design has three problems.

Too many parameters. A small colour photograph of 224×224 pixels has 224×224×3=150 528224 \times 224 \times 3 = 150\,528 inputs. A first layer of 1 000 units needs 150 million weights, before the network has learned anything, and each of them must be estimated from data.

No notion of neighbourhood. A dense layer treats the pixels as an unordered list. It does not know that two pixels are next to each other, although in an image that is what matters most: edges, strokes and textures are made of neighbouring pixels.

No tolerance to shifts. A dense layer learns a separate weight for each position. A stroke that it has learned at one place means nothing to it one pixel further.

We check the last two claims with scikit-learn’s digits (8×8 pixels), each placed in the centre of a 16×16 canvas so that it can be moved around.

<Figure size 700x240 with 3 Axes>

A training loop for any network; aug=True moves every training digit to a random position (up to 4 pixels each way) at every epoch, which Section 17.5 uses.

dense network, test digits centred              accuracy 0.972
dense network, test digits shifted up to 2 px   accuracy 0.167
dense network, test digits shifted up to 4 px   accuracy 0.100

Trained on centred digits, the dense network gets 0.972 on centred test digits, and 0.167 on the same digits moved by at most two pixels: barely better than guessing. Now the neighbourhood claim. We shuffle the pixels of every image with one fixed permutation, the same for training and test, so the images look like noise to us, and train again:

dense network on shuffled pixels: accuracy 0.978
<Figure size 460x240 with 2 Axes>

The accuracy is the same (0.978): the dense network never used the arrangement of the pixels, because it cannot. Everything an image’s geometry tells us, it must learn again from examples, at every position.

What we want instead is a layer that:

  1. looks at small neighbourhoods (local connectivity);

  2. applies the same detector everywhere (weight sharing), so that a stroke learned in one place is recognised in all places, with far fewer parameters.

That layer is the convolution.

17.2 The Convolution Operation

A convolution slides a small grid of weights, the kernel (or filter), over the image. At each position it multiplies the kernel with the patch of the image under it, element by element, and sums:

out[i,j]=∑u=0k−1∑v=0k−1K[u,v]  img[i+u, j+v]+b\text{out}[i, j] = \sum_{u=0}^{k-1} \sum_{v=0}^{k-1} K[u, v] \; \text{img}[i + u, \, j + v] + b

(Strictly, this is a cross-correlation; a mathematical convolution flips the kernel first. Deep learning libraries compute the formula above and call it convolution, and since the kernel is learned, the flip makes no difference.)

A worked example: a 5×5 image with a vertical edge, and a 3×3 kernel that responds to “dark on the left, bright on the right”.

image:
 [[0 0 0 1 1]
 [0 0 0 1 1]
 [0 0 0 1 1]
 [0 0 0 1 1]
 [0 0 0 1 1]]
kernel:
 [[-1  0  1]
 [-1  0  1]
 [-1  0  1]]
output:
 [[0 3 3]
 [0 3 3]
 [0 3 3]]

The output is 3×3 (a 3×3 kernel fits in 3 positions along each side of a 5×5 image). It is 3 where the kernel straddles the edge, and 0 in the flat region on the left: the kernel is an edge detector, and its output, the feature map, says where in the image the feature is.

Here are four hand-made kernels applied to a digit:

Source
<Figure size 1200x260 with 5 Axes>

Red marks where a kernel’s pattern is present, blue where its opposite is. Before deep learning, such filters were designed by hand (Sobel, Gabor). A convolutional layer learns its kernels from data, by backpropagation, like any other weights.

Two properties come with this design:

  • Local connectivity: each output depends only on a k×kk \times k patch.

  • Weight sharing: the same k×kk \times k weights are used at every position. A 3×3 kernel has 9 weights (plus a bias), whatever the image size.

17.3 Convolutional Layers in Depth

Channels

Images have channels (red, green, blue), and so do the feature maps inside a network (one per filter). A convolutional layer with CinC_{\text{in}} input channels and CoutC_{\text{out}} output channels has CoutC_{\text{out}} filters, each of shape Cin×k×kC_{\text{in}} \times k \times k: each filter looks at all input channels at once and sums over them, producing one output channel.

parameters=Cout×(Cin×k×k+1)\text{parameters} = C_{\text{out}} \times (C_{\text{in}} \times k \times k + 1)

Padding and stride

Without padding, each 3×3 convolution shrinks the image by 2 pixels; after a few layers, the borders are lost. Padding adds a frame of zeros (pp pixels) around the input; p=(k−1)/2p = (k-1)/2 (“same” padding) keeps the size. Stride ss moves the kernel ss pixels at a time, dividing the output size by about ss. For an input of size nn:

nout=⌊n+2p−ks⌋+1n_{\text{out}} = \left\lfloor \frac{n + 2p - k}{s} \right\rfloor + 1
n=5   k=3  p=0 s=1: output   3  (PyTorch:   3), parameters for 3 -> 64 channels:   1792 (PyTorch: 1792)
n=16  k=3  p=1 s=1: output  16  (PyTorch:  16), parameters for 3 -> 64 channels:   1792 (PyTorch: 1792)
n=16  k=3  p=1 s=2: output   8  (PyTorch:   8), parameters for 3 -> 64 channels:   1792 (PyTorch: 1792)
n=224 k=7  p=3 s=2: output 112  (PyTorch: 112), parameters for 3 -> 64 channels:   9472 (PyTorch: 9472)
n=224 k=11 p=2 s=4: output  55  (PyTorch:  55), parameters for 3 -> 64 channels:  23296 (PyTorch: 23296)

The first layer of ResNet (Chapter 18) is the fourth line: 7×7 kernels, stride 2, padding 3, 224 → 112, with 9 472 parameters, against 150 million for a dense layer of 1 000 units on the same image. The last line is AlexNet’s first layer (11×11, stride 4).

Pooling

A pooling layer summarises each small window of a feature map, without weights: max pooling keeps the largest value, average pooling the mean. A 2×2 pool with stride 2 halves the height and width. Pooling makes the next layers cheaper, and makes the network tolerant to small shifts within the window. Global pooling summarises each whole feature map into a single number, whatever its size: it turns “where is this feature?” into “is this feature anywhere?”.

1×1 convolutions

A 1×1 kernel looks at a single pixel, across all channels: it is a small dense layer applied at every position. It is used to change the number of channels cheaply (a Cin→CoutC_{\text{in}} \to C_{\text{out}} mixing with CinCoutC_{\text{in}} C_{\text{out}} weights), as in Inception and ResNet’s bottlenecks.

The receptive field

A unit after one 3×3 convolution sees a 3×3 patch of the input; after two, a 5×5 patch; each further 3×3 layer adds 2, and each stride multiplies the growth of all later layers. This receptive field is why depth matters for vision: early layers see edges, later layers see whole parts and objects.

three 3x3 convolutions:                  [3, 5, 7]
conv, pool 2, conv, pool 2, conv (ours):  [3, 4, 8, 10, 18]
a 7x7 convolution:                       [7]

Three stacked 3×3 convolutions see 7×7, like one 7×7 convolution, with 3×9=273 \times 9 = 27 weights per channel pair instead of 49, and three non-linearities instead of one. That is why modern networks (VGG, ResNet) use mostly 3×3 kernels.

Equivariance and invariance

A convolution is equivariant to shifts: shift the input, and the feature map shifts by the same amount. A classifier should be invariant: shift the input, and the answer stays the same. Global pooling turns the first into the second. We check it on the next network.

17.4 A Convolutional Network for Digits

Three convolutional layers (16, 32 and 64 filters of 3×3, with padding 1), each followed by ReLU; max pooling of 2×2 after the first two; global max pooling; and a dense layer to the 10 classes.

parameters: dense network 50698, convolutional network 23946
test digits centred              dense 0.972   convolutional 0.976
test digits shifted up to 2 px   dense 0.167   convolutional 0.344
test digits shifted up to 4 px   dense 0.100   convolutional 0.315

With half the parameters (23 946 against 50 698), the convolutional network matches the dense one on centred digits (0.976). But on shifted digits it also fails: 0.344. Each convolution is equivariant and global pooling is invariant, so where does the dependence on position come from?

From the stride-2 pooling. Max pooling with stride 2 keeps one value out of each 2×2 window, so a shift of one pixel changes which values survive; after two such layers, only shifts by multiples of 4 pixels give the same pooled grid. Testing with exact shifts:

shift (down, right):   (0, 1)   (0, 2)   (0, 4)   (1, 1)   (2, 2)
convolutional:          0.628    0.441    0.893    0.256    0.128

A shift of 4 pixels to the right (0.893) does much better than shifts of 1 or 2. A network without any striding keeps exact equivariance until the global pooling, which makes it invariant:

no striding: 23946 parameters, trained in 58 s
test digits centred              accuracy 0.989
test digits shifted up to 2 px   accuracy 0.989
test digits shifted up to 4 px   accuracy 0.981
exact shifts:  (0, 1): 0.989  (0, 2): 0.989  (0, 4): 0.989  (1, 1): 0.987  (2, 2): 0.987

With exactly the same number of parameters, it gets 0.989 on centred digits and on shifted ones, having seen only centred digits in training. The price is computation: every layer works on the full 16×16 grid instead of 8×8 and 4×4, about 10 times more multiplications here, and far more on real images. Practical networks therefore keep their strides and pooling, which they need to grow the receptive field cheaply, and obtain robustness to shifts another way: by showing the network shifted examples.

17.5 Data Augmentation

Data augmentation trains on randomly transformed copies of the training images: shifts, crops, flips, small rotations, changes of colour and brightness. Each transformation must keep the label true: flipping a photograph of a cat left to right is still a cat; flipping a 6 upside down makes a 9.

We train both networks again, each training digit moved to a random position (up to 4 pixels each way) at every epoch:

test digits centred              dense + augmentation 0.680   convolutional + augmentation 0.967
test digits shifted up to 2 px   dense + augmentation 0.713   convolutional + augmentation 0.952
test digits shifted up to 4 px   dense + augmentation 0.731   convolutional + augmentation 0.956

The convolutional network now handles shifted digits (0.952 and 0.956) while keeping 0.967 on centred ones. The dense network cannot: it has to learn every digit at 81 positions separately, with no sharing between them, and in 30 epochs it reaches only about 0.7 everywhere, worse than before on centred digits. Augmentation works with the convolution’s weight sharing, not instead of it.

17.6 What the Filters Learn

The first layer’s 16 filters are 3×3 images, and each produces a feature map. For a trained network:

Source
<Figure size 1500x240 with 32 Axes>

Many of the learned filters are edge and stroke detectors at various orientations, like the hand-made kernels of Section 17.2, and their feature maps light up along the digit’s strokes in different directions. Nobody told the network to look for edges: they are simply the most useful first step for recognising shapes.

In large networks trained on millions of photographs, visualisations by Zeiler and Fergus (2014) and later work show a hierarchy: the first layers detect edges and colours, the next textures and simple patterns, then parts (eyes, wheels, letters), and the last layers whole objects. Each layer combines the features of the layer below over a larger receptive field. This hierarchy is also why a network trained on one large image collection is useful for other image tasks: its early and middle layers are general-purpose feature extractors. Chapter 19 uses exactly that.

17.7 Summary

  • Dense layers on images need too many parameters, ignore which pixels are neighbours, and learn each position separately: shifted by 2 pixels, digits fell from 0.972 to 0.167 accuracy.

  • A convolution slides a small kernel over the image: local connectivity and weight sharing. Its output is a feature map.

  • A convolutional layer has CoutC_{\text{out}} filters of shape Cin×k×kC_{\text{in}} \times k \times k; its output size is ⌊(n+2p−k)/s⌋+1\lfloor (n + 2p - k)/s \rfloor + 1; its parameters do not depend on the image size.

  • Pooling summarises windows; global pooling makes the answer independent of position; 1×1 convolutions mix channels; stacked 3×3 convolutions grow the receptive field.

  • Convolutions are equivariant; strided pooling breaks exact invariance; data augmentation restores robustness in practice.

  • Learned first-layer filters are edge detectors; deeper layers build textures, parts and objects.

Exercises

  1. A dense layer maps a 64×64 grey image to 500 units. How many parameters does it have? How many does a convolutional layer with 32 filters of 5×5 have on the same image?

  2. Compute by hand the output of the kernel [[1, 0], [0, -1]] on the image [[1, 2, 3], [4, 5, 6], [7, 8, 9]] (valid, stride 1).

  3. An input of 32×32×3 goes through a 5×5 convolution with 16 filters, padding 2, stride 1, then a 2×2 max pool with stride 2, then a 3×3 convolution with 32 filters, padding 0, stride 2. Give the shape after each layer and the parameter count.

  4. What is the receptive field of a unit after the network of Exercise 3?

  5. Why can the network of Section 17.4 not recognise a digit shifted by 1 pixel, although each of its layers is equivariant? Name two ways to fix it, and their costs.

  6. For each augmentation, say whether it keeps the label for handwritten digits, for photographs of animals, and for chest X-rays: horizontal flip, rotation by 90°, a change of brightness, a crop of half the image.

  7. A 1×1 convolution maps 256 channels to 64. How many parameters does it have? What does it compute at each pixel?

Further Reading

  • Y. LeCun, L. Bottou, Y. Bengio, P. Haffner, “Gradient-based learning applied to document recognition”, Proceedings of the IEEE, 1998.

  • V. Dumoulin, F. Visin, “A guide to convolution arithmetic for deep learning”, arXiv:1603.07285, 2016.

  • M. Zeiler, R. Fergus, “Visualizing and understanding convolutional networks”, ECCV, 2014.

  • R. Zhang, “Making convolutional networks shift-invariant again”, ICML, 2019.

  • I. Goodfellow, Y. Bengio, A. Courville, Deep Learning, MIT Press, 2016, chapter 9 (Convolutional Networks).