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 — Implementation

Open in Colab
  1. A convolutional layer as one matrix product (im2col), checked against PyTorch

  2. Max pooling in NumPy

  3. A layer-by-layer summary: shapes, parameters, receptive fields

  4. Looking inside: feature maps with forward hooks

  5. Which pixels matter: a saliency map

  6. Data augmentation with torchvision.transforms

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 Cin×k×kC_{\text{in}} \times k \times k patch of the input into one row of a matrix; the layer is then a single matrix product with the filters, flattened into a (Cink2)×Cout(C_{\text{in}} k^2) \times C_{\text{out}} matrix. Libraries use this idea (or a fast Fourier or Winograd variant) on GPUs.

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

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 (k−1)(k-1) times the product of the strides so far).

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.

test accuracy 0.943
<Figure size 1200x460 with 24 Axes>

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.

<Figure size 1100x380 with 12 Axes>

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:

<Figure size 1200x180 with 8 Axes>

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):

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.conv2d exactly.

  • 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.v2 makes augmentation a one-line change, and each augmentation buys robustness to one kind of change.