Module 6
Convolutions
An edge is an edge wherever it appears in a picture. A convolutional layer takes that seriously: it learns one small pattern detector and slides it across every position.
Why it matters
A dense layer treats an image as a bag of unrelated numbers: it has to learn separately that a stroke in the top left and the same stroke in the bottom right are the same thing. Convolution builds two facts about images into the architecture instead, that useful features are local and that they can occur anywhere. The result needs far fewer parameters and far less data. The same idea of reusing weights across positions is behind models for sound and text, and reusing them across time steps is exactly what the recurrent networks in the next module do.
The idea
The operation
Take an image $x$ of height $H$ and width $W$, and a small array of weights $w$ of size $k \times k$, called a filter or kernel. Place the filter over the top-left corner of the image, multiply each weight by the pixel under it, and add up the products. Slide one pixel along and repeat:
$$\text{out}[i, j] = \sum_{a=0}^{k-1} \sum_{b=0}^{k-1} w[a, b]\; x[i + a,\, j + b] .$$The output, a feature map, has size $(H - k + 1) \times (W - k + 1)$: an $8 \times 8$ image and a $3 \times 3$ filter give $6 \times 6$. Its value at each position says how strongly the patch there matches the filter.
Mathematicians call this operation cross-correlation; a true convolution flips the filter first. Deep-learning libraries use the unflipped version and call it convolution anyway. Since the weights are learned, the flip would make no difference to what the layer can represent.
What the structure buys
- Few parameters. A filter has $k^2$ weights and a bias whatever the size of the image, because the same weights are used at every position.
- Locality. Each output looks at a small patch, which matches how images are built: edges make corners, corners make shapes.
- Equivariance to shifts. Move the input one pixel to the right and the feature map moves one pixel to the right. A detector learned in one place works everywhere.
A layer usually applies several filters, giving several feature maps (channels), followed by a non-linearity such as ReLU. Two common variations change the output size: padding the image with $p$ rings of zeros, and moving the filter in steps of $s$ pixels (the stride). The output side is then $\lfloor (H + 2p - k)/s \rfloor + 1$.
Pooling
Max pooling shrinks a feature map by keeping only the largest value in each $2 \times 2$ block. It halves the resolution and makes the result insensitive to small shifts: the feature is reported as present whichever of the four cells it fired in.
Gradients
Each output is a sum of products, and module 0 says what to do with those. Let $G[i, j] = \partial \mathcal{L} / \partial\, \text{out}[i, j]$ be the gradient arriving from above. The weight $w[a, b]$ was used once for every output position, each time multiplied by a different pixel, so its contributions add:
$$\frac{\partial \mathcal{L}}{\partial w[a, b]} = \sum_{i, j} G[i, j]\; x[i + a,\, j + b] .$$The pixel $x[p, q]$ was used by every output whose window covered it, each time multiplied by a different weight:
$$\frac{\partial \mathcal{L}}{\partial x[p, q]} = \sum_{a, b} w[a, b]\; G[p - a,\, q - b],$$where terms that fall outside $G$ are left out. For max pooling, the gradient of each block goes entirely to the cell that held the maximum and the other three get zero.
Many classes: softmax
The network in the demo chooses between ten digits, so its last layer produces ten scores $z_0, \dots, z_9$. The softmax turns scores into probabilities, and the loss is the cross-entropy of the correct class $y$:
$$p_c = \frac{e^{z_c}}{\sum_{c'} e^{z_{c'}}}, \qquad \mathcal{L} = -\log p_y .$$This is the multi-class version of module 1's logistic regression, and its gradient has the same form: $\partial \mathcal{L} / \partial z_c = p_c - [c = y]$, prediction minus target.
Live demos
One filter, sliding
Edit the filter; click a cell to see its sum
Input: an 8 × 8 handwritten digit
The 3 × 3 filter
Output: the 6 × 6 feature map
A tiny convolutional network
Six filters, learned from 600 digits
Accuracy during training
Top: the six filters. Bottom: each one's feature map for the first digit below.
Twelve unseen digits and what the network says they are
Try this
- With the Vertical edges filter, click output cells along the left and right sides of a stroke. The sign tells you whether the image gets brighter or darker from left to right. Then try Horizontal edges on the same digit.
- Choose Blur. Every weight is 1/9, so each output is a local average and nothing is negative.
- Design a filter for strokes running from top left to bottom right: positive weights on that diagonal, negative ones off it. Check it against a few digits.
- Train the network and look at its six filters. Nobody told it to find edges; compare what it learned with the hand-made filters above.
- Press New random weights and train again. The filters come out different and the accuracy about the same: many sets of filters solve the task.
Exercise
Write conv2d and its gradient
Implement the sliding-filter operation for one image and one filter (no padding, stride 1), and its backward pass: given the gradient of a loss with respect to the output, return the gradients with respect to the input and the filter. The tests compare the forward pass with the definition and the backward pass with finite differences.
Forward. Two loops over the output positions work: out[i, j] = np.sum(w * x[i:i+kh, j:j+kw]). Looping over the filter instead is faster: each weight w[a, b] multiplies the shifted slice x[a:a+oh, b:b+ow].
Backward. Use the same loop. w[a, b] was multiplied by that slice of x, so dw[a, b] = np.sum(dout * slice), and the slice receives w[a, b] * dout, added to whatever it already has: dx[a:a+oh, b:b+ow] += ….
Check yourself
A layer applies 16 filters of size 3 × 3 to a one-channel image. How many parameters does it have for an 8 × 8 image? For a 1,000 × 1,000 image?
$16 \times (9 + 1) = 160$ in both cases. The count depends on the filters, not on the image; a dense layer from a million pixels to 16 outputs would need sixteen million weights.
Why is the gradient of a filter weight a sum over every output position?
Because the same weight was used at every position. As with any value used more than once in module 0, the contributions from each use add.
In a 2 × 2 max-pooling block, which of the four inputs receive gradient?
Only the one that was the maximum; the output did not depend on the other three (for small changes), so their gradient is zero.
Where this leads
A convolution shares weights across space. Module 7 shares them across time: a recurrent network applies the same layer at every step of a sequence, which raises a new problem when the sequence is long.
Sources: Y. LeCun, L. Bottou, Y. Bengio and P. Haffner, “Gradient-based learning applied to document recognition”, Proceedings of the IEEE 86 (1998); I. Goodfellow, Y. Bengio and A. Courville, Deep Learning, MIT Press (2016), ch. 9; V. Dumoulin and F. Visin, “A guide to convolution arithmetic for deep learning”, arXiv:1603.07285 (2016). Digit images: E. Alpaydin and C. Kaynak, “Optical Recognition of Handwritten Digits”, UCI Machine Learning Repository (1998), doi:10.24432/C50P49, CC BY 4.0.