Chapter 17: From Dense Networks to Convolutional Layers — Implementation
A convolutional layer as one matrix product (im2col), checked against PyTorch
Max pooling in NumPy
A layer-by-layer summary: shapes, parameters, receptive fields
Looking inside: feature maps with forward hooks
Which pixels matter: a saliency map
Data augmentation with
torchvision.transforms
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
from torchvision.transforms import v2
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
torch.manual_seed(0); 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)
pad = lambda a: np.pad(a, ((0, 0), (4, 4), (4, 4))) # each digit in the centre of a 16x16 canvas
Xtr_t, Xte_t = torch.tensor(pad(Xtr), dtype=torch.float32).unsqueeze(1), torch.tensor(pad(Xte), dtype=torch.float32).unsqueeze(1)
ytr_t, yte_t = torch.tensor(ytr), torch.tensor(yte)
print(Xtr_t.shape, Xte_t.shape)torch.Size([1257, 1, 16, 16]) torch.Size([540, 1, 16, 16])
1. Convolution as One Matrix Product¶
Loops over positions are slow in Python. im2col copies every patch of the input into one row of a matrix; the layer is then a single matrix product with the filters, flattened into a matrix. Libraries use this idea (or a fast Fourier or Winograd variant) on GPUs.
def im2col(x, k, stride=1, padding=0):
"""x: (C, H, W) -> (number of positions, C*k*k), and the output height and width."""
x = np.pad(x, ((0, 0), (padding, padding), (padding, padding)))
C, H, W = x.shape
Ho, Wo = (H - k) // stride + 1, (W - k) // stride + 1
cols = np.empty((Ho * Wo, C * k * k))
for i in range(Ho):
for j in range(Wo):
cols[i * Wo + j] = x[:, i * stride:i * stride + k, j * stride:j * stride + k].ravel()
return cols, Ho, Wo
def conv_layer(x, W, b, stride=1, padding=0):
"""x: (C_in, H, W); W: (C_out, C_in, k, k); b: (C_out,) -> (C_out, H_out, W_out)."""
cols, Ho, Wo = im2col(x, W.shape[-1], stride, padding)
out = cols @ W.reshape(len(W), -1).T + b # (positions, C_out)
return out.T.reshape(len(W), Ho, Wo)
rng = np.random.default_rng(0)
x = rng.normal(size=(3, 9, 9)); W = rng.normal(size=(5, 3, 3, 3)); b = rng.normal(size=5)
for stride, padding in [(1, 0), (1, 1), (2, 1)]:
ours = conv_layer(x, W, b, stride, padding)
ref = F.conv2d(torch.tensor(x)[None], torch.tensor(W), torch.tensor(b), stride=stride, padding=padding)[0].numpy()
print(f'stride {stride}, padding {padding}: shape {ours.shape}, same as PyTorch: {np.allclose(ours, ref)}')stride 1, padding 0: shape (5, 7, 7), same as PyTorch: True
stride 1, padding 1: shape (5, 9, 9), same as PyTorch: True
stride 2, padding 1: shape (5, 5, 5), same as PyTorch: True
2. Max Pooling¶
def max_pool(x, k=2, stride=2):
"""x: (C, H, W) -> (C, H_out, W_out), the largest value of each k x k window."""
C, H, W = x.shape
Ho, Wo = (H - k) // stride + 1, (W - k) // stride + 1
out = np.empty((C, Ho, Wo))
for i in range(Ho):
for j in range(Wo):
out[:, i, j] = x[:, i * stride:i * stride + k, j * stride:j * stride + k].max(axis=(1, 2))
return out
z = rng.normal(size=(4, 8, 8))
print('same as PyTorch:', np.allclose(max_pool(z), F.max_pool2d(torch.tensor(z)[None], 2)[0].numpy()))
print('a 4x4 example:\n', np.arange(16).reshape(1, 4, 4)[0], '\n->\n', max_pool(np.arange(16.0).reshape(1, 4, 4))[0])same as PyTorch: True
a 4x4 example:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
->
[[ 5. 7.]
[13. 15.]]
3. A Layer-by-Layer Summary¶
Passing a dummy input through each layer gives its output shape; the parameters are counted per layer, and the receptive field follows the rule of the theory chapter (it grows by times the product of the strides so far).
def summary(net, shape=(1, 1, 16, 16)):
x, rf, jump = torch.zeros(shape), 1, 1
print(f'{"layer":<34}{"output shape":<18}{"parameters":>11}{"receptive field":>17}')
for layer in net:
x = layer(x)
k = getattr(layer, 'kernel_size', None)
if k is not None:
k = k if isinstance(k, int) else k[0]
s = layer.stride if isinstance(layer.stride, int) else layer.stride[0]
rf += (k - 1) * jump; jump *= s
n = sum(p.numel() for p in layer.parameters())
print(f'{str(layer)[:33]:<34}{str(tuple(x.shape[1:])):<18}{n:>11}{rf:>17}')
print(f'{"total":<52}{sum(p.numel() for p in net.parameters()):>11}')
cnn = nn.Sequential(
nn.Conv2d(1, 16, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(16, 32, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(32, 64, 3, padding=1), nn.ReLU(),
nn.AdaptiveMaxPool2d(1), nn.Flatten(), nn.Linear(64, 10))
summary(cnn)layer output shape parameters receptive field
Conv2d(1, 16, kernel_size=(3, 3), (16, 16, 16) 160 3
ReLU() (16, 16, 16) 0 3
MaxPool2d(kernel_size=2, stride=2 (16, 8, 8) 0 4
Conv2d(16, 32, kernel_size=(3, 3) (32, 8, 8) 4640 8
ReLU() (32, 8, 8) 0 8
MaxPool2d(kernel_size=2, stride=2 (32, 4, 4) 0 10
Conv2d(32, 64, kernel_size=(3, 3) (64, 4, 4) 18496 18
ReLU() (64, 4, 4) 0 18
AdaptiveMaxPool2d(output_size=1) (64, 1, 1) 0 18
Flatten(start_dim=1, end_dim=-1) (64,) 0 18
Linear(in_features=64, out_featur (10,) 650 18
total 23946
The third convolution’s units see an 18×18 window: more than the whole 16×16 canvas. The 64 numbers after global pooling each say whether one learned feature appears anywhere in the image.
4. Looking Inside: Forward Hooks¶
We train the network with shifted copies of the training digits (Section 6 shows the transform), then register a forward hook on each convolution: a function PyTorch calls with the layer’s output whenever the layer runs.
augment = v2.RandomAffine(degrees=0, translate=(0.25, 0.25)) # up to 4 pixels on a 16-pixel canvas
def train(net, epochs=30, transform=None):
opt = torch.optim.Adam(net.parameters(), 1e-3); g = torch.Generator().manual_seed(0)
for ep in range(epochs):
net.train()
for idx in torch.randperm(len(Xtr_t), generator=g).split(64):
xb = Xtr_t[idx]
if transform is not None: xb = torch.stack([transform(im) for im in xb])
opt.zero_grad(); F.cross_entropy(net(xb), ytr_t[idx]).backward(); opt.step()
net.eval(); return net
torch.manual_seed(0); train(cnn, transform=augment)
with torch.no_grad(): print(f'test accuracy {float((cnn(Xte_t).argmax(1) == yte_t).float().mean()):.3f}')
maps = {}
hooks = [layer.register_forward_hook(lambda m, inp, out, i=i: maps.__setitem__(i, out.detach()))
for i, layer in enumerate(cnn) if isinstance(layer, nn.Conv2d)]
with torch.no_grad(): cnn(Xte_t[3:4])
for h in hooks: h.remove()
fig, axes = plt.subplots(3, 8, figsize=(12, 4.6))
for row, (i, m) in enumerate(maps.items()):
for c in range(8):
axes[row, c].imshow(F.relu(m[0, c]), cmap='magma'); axes[row, c].axis('off')
axes[row, 0].set_title(f'conv layer {row + 1}: {tuple(m.shape[1:])}', loc='left', fontsize=9)
plt.tight_layout(); plt.show()test accuracy 0.943

The first layer’s maps are still the digit’s strokes, in different directions; the second layer’s, at 8×8, combine them into larger pieces; the third layer’s 4×4 maps are coarse and abstract: they mark where higher-level features are, and their maxima are what the classifier reads.
5. Which Pixels Matter: a Saliency Map¶
The gradient of the winning class’s score with respect to the input pixels says which pixels would change the score most. It is the simplest explanation method for images (Simonyan et al., 2014); Chapter 12’s methods apply as well.
fig, axes = plt.subplots(2, 6, figsize=(11, 3.8))
for c, i in enumerate([0, 3, 5, 7, 11, 13]):
x = Xte_t[i:i + 1].clone().requires_grad_(True)
score = cnn(x); k = int(score.argmax()); score[0, k].backward()
axes[0, c].imshow(x[0, 0].detach(), cmap='gray_r'); axes[0, c].set_title(f'a {yte[i]}, predicted {k}', fontsize=9)
axes[1, c].imshow(x.grad[0, 0].abs(), cmap='hot')
axes[0, c].axis('off'); axes[1, c].axis('off')
plt.tight_layout(); plt.show()
The bright pixels lie on and around the strokes that distinguish the digit; the empty canvas gets little gradient.
6. Data Augmentation with torchvision.transforms¶
torchvision.transforms.v2 composes random transformations that are applied anew each time an image is drawn. A few, on the same digit:
aug = v2.Compose([v2.RandomAffine(degrees=15, translate=(0.2, 0.2), scale=(0.85, 1.15)), v2.RandomErasing(p=0.5, scale=(0.02, 0.08))])
torch.manual_seed(1)
fig, axes = plt.subplots(1, 8, figsize=(12, 1.8))
axes[0].imshow(Xte_t[3, 0], cmap='gray_r'); axes[0].set_title('original', fontsize=9)
for ax in axes[1:]: ax.imshow(aug(Xte_t[3])[0], cmap='gray_r')
for ax in axes: ax.axis('off')
plt.tight_layout(); plt.show()
How much does each kind of augmentation help? Trained for 30 epochs each, and tested on digits shifted and rotated at random (a harder test set than training):
hard = v2.RandomAffine(degrees=15, translate=(0.25, 0.25))
torch.manual_seed(2); Xhard = torch.stack([hard(im) for im in Xte_t])
def fresh():
return nn.Sequential(nn.Conv2d(1, 16, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2), nn.Conv2d(16, 32, 3, padding=1), nn.ReLU(),
nn.MaxPool2d(2), nn.Conv2d(32, 64, 3, padding=1), nn.ReLU(), nn.AdaptiveMaxPool2d(1), nn.Flatten(), nn.Linear(64, 10))
for name, tf in [('none', None), ('shifts', v2.RandomAffine(0, translate=(0.25, 0.25))), ('shifts + rotations', hard)]:
torch.manual_seed(0); net = train(fresh(), transform=tf)
with torch.no_grad():
a, b = (float((net(d).argmax(1) == yte_t).float().mean()) for d in (Xte_t, Xhard))
print(f'augmentation {name:<20} centred test {a:.3f} shifted and rotated test {b:.3f}')augmentation none centred test 0.976 shifted and rotated test 0.326
augmentation shifts centred test 0.959 shifted and rotated test 0.878
augmentation shifts + rotations centred test 0.943 shifted and rotated test 0.913
Each transformation the network sees in training is one it tolerates at test time. Augmentation does not replace data from the real conditions of use, but it encodes what we know about which changes do not alter the label.
Summary¶
im2col turns a convolution into one matrix product; the result matches
F.conv2dexactly.A summary with shapes, parameters and receptive fields is the first check of any architecture.
Forward hooks expose the feature maps; input gradients give a saliency map.
transforms.v2makes augmentation a one-line change, and each augmentation buys robustness to one kind of change.