Chapter 17: From Dense Networks to Convolutional Layers
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 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.
import time
import numpy as np
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
torch.set_num_threads(2)
X, y = load_digits(return_X_y=True); X = X.reshape(-1, 8, 8) / 16
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
def canvas(imgs, shifts, size=16):
"""Each 8x8 digit on a size x size canvas, its top-left corner at (4 + dy, 4 + dx)."""
out = np.zeros((len(imgs), size, size))
for i, (im, (dy, dx)) in enumerate(zip(imgs, shifts)):
out[i, 4 + dy:12 + dy, 4 + dx:12 + dx] = im
return out
centre = lambda imgs: canvas(imgs, np.zeros((len(imgs), 2), int))
rng = np.random.default_rng(0)
test_sets = {'centred': centre(Xte),
'shifted up to 2 px': canvas(Xte, rng.integers(-2, 3, (len(Xte), 2))),
'shifted up to 4 px': canvas(Xte, rng.integers(-4, 5, (len(Xte), 2)))}
fig, axes = plt.subplots(1, 3, figsize=(7, 2.4))
for ax, (name, C) in zip(axes, test_sets.items()):
ax.imshow(C[0], cmap='gray_r'); ax.set_title(name, fontsize=9); ax.axis('off')
plt.tight_layout(); plt.show()
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.
T = lambda a: torch.tensor(a, dtype=torch.float32).unsqueeze(1) # (n, 1, 16, 16): one channel
yte_t = torch.tensor(yte)
def fit(net, X, y, epochs=30, aug=False, seed=0):
torch.manual_seed(seed); opt = torch.optim.Adam(net.parameters(), 1e-3); loss_fn = nn.CrossEntropyLoss()
g, r = torch.Generator().manual_seed(0), np.random.default_rng(1)
for ep in range(epochs):
C = canvas(X, r.integers(-4, 5, (len(X), 2))) if aug else centre(X)
Xe, ye = T(C), torch.tensor(y)
net.train()
for idx in torch.randperm(len(Xe), generator=g).split(64):
opt.zero_grad(); loss_fn(net(Xe[idx]), ye[idx]).backward(); opt.step()
net.eval()
return net
def accuracy(net, C):
with torch.no_grad():
return float((net(T(C)).argmax(1) == yte_t).float().mean())
def mlp():
return nn.Sequential(nn.Flatten(), nn.Linear(256, 128), nn.ReLU(), nn.Linear(128, 128), nn.ReLU(), nn.Linear(128, 10))
torch.manual_seed(0); dense = fit(mlp(), Xtr, ytr)
for name, C in test_sets.items():
print(f'dense network, test digits {name:<20} accuracy {accuracy(dense, C):.3f}')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:
perm = np.random.default_rng(3).permutation(256)
shuffle = lambda C: C.reshape(len(C), -1)[:, perm].reshape(-1, 16, 16)
torch.manual_seed(0); net = mlp(); opt = torch.optim.Adam(net.parameters(), 1e-3); g = torch.Generator().manual_seed(0)
Xp, yp = T(shuffle(centre(Xtr))), torch.tensor(ytr)
for ep in range(30):
for idx in torch.randperm(len(Xp), generator=g).split(64):
opt.zero_grad(); nn.CrossEntropyLoss()(net(Xp[idx]), yp[idx]).backward(); opt.step()
net.eval()
print(f'dense network on shuffled pixels: accuracy {accuracy(net, shuffle(test_sets["centred"])):.3f}')
fig, axes = plt.subplots(1, 2, figsize=(4.6, 2.4))
axes[0].imshow(test_sets['centred'][0], cmap='gray_r'); axes[1].imshow(shuffle(test_sets['centred'][:1])[0], cmap='gray_r')
for ax, t in zip(axes, ['the digit', 'its pixels shuffled']): ax.set_title(t, fontsize=9); ax.axis('off')
plt.tight_layout(); plt.show()dense network on shuffled pixels: accuracy 0.978

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:
looks at small neighbourhoods (local connectivity);
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:
(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”.
def conv2d(img, K, b=0.0):
"""A 'valid' convolution (no padding, stride 1), written with loops to show the formula."""
k = K.shape[0]; H, W = img.shape
out = np.zeros((H - k + 1, W - k + 1))
for i in range(H - k + 1):
for j in range(W - k + 1):
out[i, j] = np.sum(K * img[i:i + k, j:j + k]) + b
return out
img = np.array([[0, 0, 0, 1, 1]] * 5, dtype=float)
K = np.array([[-1, 0, 1]] * 3, dtype=float)
print('image:\n', img.astype(int)); print('kernel:\n', K.astype(int)); print('output:\n', conv2d(img, K).astype(int))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
kernels = {'vertical edges': np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]),
'horizontal edges': np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]]),
'diagonal (↘)': np.array([[2, 1, 0], [1, 0, -1], [0, -1, -2]]),
'blur': np.ones((3, 3)) / 9}
d = test_sets['centred'][3]
fig, axes = plt.subplots(1, 5, figsize=(12, 2.6))
axes[0].imshow(d, cmap='gray_r'); axes[0].set_title('input', fontsize=9)
for ax, (name, Kk) in zip(axes[1:], kernels.items()):
ax.imshow(conv2d(d, Kk), cmap='RdBu_r', vmin=-3, vmax=3) if name != 'blur' else ax.imshow(conv2d(d, Kk), cmap='gray_r')
ax.set_title(name, fontsize=9)
for ax in axes: ax.axis('off')
plt.tight_layout(); plt.show()
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 patch.
Weight sharing: the same 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 input channels and output channels has filters, each of shape : each filter looks at all input channels at once and sums over them, producing one output channel.
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 ( pixels) around the input; (“same” padding) keeps the size. Stride moves the kernel pixels at a time, dividing the output size by about . For an input of size :
def out_size(n, k, p=0, s=1):
return (n + 2 * p - k) // s + 1
def conv_params(c_in, c_out, k):
return c_out * (c_in * k * k + 1)
for n, k, p, s in [(5, 3, 0, 1), (16, 3, 1, 1), (16, 3, 1, 2), (224, 7, 3, 2), (224, 11, 2, 4)]:
layer = nn.Conv2d(3, 64, k, stride=s, padding=p)
print(f'n={n:<3} k={k:<2} p={p} s={s}: output {out_size(n, k, p, s):>3} (PyTorch: {layer(torch.zeros(1, 3, n, n)).shape[-1]:>3}),'
f' parameters for 3 -> 64 channels: {conv_params(3, 64, k):>6} (PyTorch: {sum(q.numel() for q in layer.parameters())})')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 mixing with 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.
def receptive_field(layers):
"""layers: (kernel, stride) pairs from the input up; returns the receptive field after each."""
rf, jump, out = 1, 1, []
for k, s in layers:
rf += (k - 1) * jump; jump *= s; out.append(rf)
return out
print('three 3x3 convolutions: ', receptive_field([(3, 1)] * 3))
print('conv, pool 2, conv, pool 2, conv (ours): ', receptive_field([(3, 1), (2, 2), (3, 1), (2, 2), (3, 1)]))
print('a 7x7 convolution: ', receptive_field([(7, 1)]))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 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.
def cnn():
return nn.Sequential(
nn.Conv2d(1, 16, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2), # 16x16 -> 8x8
nn.Conv2d(16, 32, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2), # 8x8 -> 4x4
nn.Conv2d(32, 64, 3, padding=1), nn.ReLU(),
nn.AdaptiveMaxPool2d(1), nn.Flatten(), # global max pooling: 64 numbers
nn.Linear(64, 10))
count = lambda net: sum(p.numel() for p in net.parameters())
torch.manual_seed(0); conv = fit(cnn(), Xtr, ytr)
print(f'parameters: dense network {count(dense)}, convolutional network {count(conv)}')
for name, C in test_sets.items():
print(f'test digits {name:<20} dense {accuracy(dense, C):.3f} convolutional {accuracy(conv, C):.3f}')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:
shifts = [(0, 1), (0, 2), (0, 4), (1, 1), (2, 2)]
def shifted_by(s): return canvas(Xte, np.tile(s, (len(Xte), 1)))
print('shift (down, right): ' + ' '.join(f'{str(s):>7}' for s in shifts))
print('convolutional: ' + ' '.join(f'{accuracy(conv, shifted_by(s)):>7.3f}' for s in 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:
def cnn_no_stride():
return nn.Sequential(nn.Conv2d(1, 16, 3, padding=1), nn.ReLU(), nn.Conv2d(16, 32, 3, padding=1), nn.ReLU(),
nn.Conv2d(32, 64, 3, padding=1), nn.ReLU(), nn.AdaptiveMaxPool2d(1), nn.Flatten(), nn.Linear(64, 10))
torch.manual_seed(0); t0 = time.time(); flat = fit(cnn_no_stride(), Xtr, ytr)
print(f'no striding: {count(flat)} parameters, trained in {time.time() - t0:.0f} s')
for name, C in test_sets.items():
print(f'test digits {name:<20} accuracy {accuracy(flat, C):.3f}')
print('exact shifts: ' + ' '.join(f'{str(s)}: {accuracy(flat, shifted_by(s)):.3f}' for s in shifts))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:
torch.manual_seed(0); dense_aug = fit(mlp(), Xtr, ytr, aug=True)
torch.manual_seed(0); conv_aug = fit(cnn(), Xtr, ytr, aug=True)
for name, C in test_sets.items():
print(f'test digits {name:<20} dense + augmentation {accuracy(dense_aug, C):.3f} convolutional + augmentation {accuracy(conv_aug, C):.3f}')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
W = conv_aug[0].weight.detach().numpy()[:, 0]
d = T(test_sets['centred'][3:4])
with torch.no_grad(): maps = conv_aug[1](conv_aug[0](d))[0].numpy()
fig, axes = plt.subplots(2, 16, figsize=(15, 2.4))
for i in range(16):
axes[0, i].imshow(W[i], cmap='RdBu_r', vmin=-np.abs(W).max(), vmax=np.abs(W).max()); axes[1, i].imshow(maps[i], cmap='gray_r')
axes[0, i].axis('off'); axes[1, i].axis('off')
fig.suptitle('the 16 learned filters (top) and their feature maps for one digit (bottom)', fontsize=10)
plt.show()
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 filters of shape ; its output size is ; 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¶
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?
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).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.
What is the receptive field of a unit after the network of Exercise 3?
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.
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.
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).