Convolutional neural networks
Test tile 349, 32 by 32 pixels: a motorway through forest
Three models in this deck will read this tile. All three get it wrong. By the end you will know why, and what it takes to get it right.
By the end you can
About 90 minutes over three sittings.
It helps to know a neural network, overfitting and softmax and cross-entropy.
Before you start: a quick check
So you know where to go quickly. Nothing is scored.
Each tile is 640 metres across, from one of 34 European countries (Helber and colleagues, 2019). Point at any tile.
We use 3,000 of them, halved to 32 by 32 pixels so everything runs in this page.
The 32 by 32 tile the network sees
Forests, water and towns come at once; the kinds of field are hard. Keep your score in mind: at the end you play the network on its hardest case.
Remember this 3 by 3 window. In part 4 a detector will look at exactly this much at a time.
200 per kind to train on, 100 per kind to test, never seen while learning
| \(x\) | a tile, 3,072 numbers |
| \(x_{ij}\) | the pixel in row \(i\), column \(j\) |
| \(y\) | its kind of land, one of 10 |
| \(p\) | a model's 10 probabilities; its answer is the largest |
| \(n\) | training tiles per kind |
| \(f\) | six colour numbers of a tile (part 2) |
| \(W, b\) | a layer's weights and biases (part 2) |
| \(K\) | a 3 by 3 kernel of weights (part 4) |
| \(C\) | input channels: 3 colours for a tile (part 4) |
| \(h\) | the feature map a kernel makes (part 4) |
| \(S\) | a shift of the tile by one pixel (part 4) |
Test tile 349, a motorway through forest. A line through green: river or highway?
Part 2 of 5
How far does colour alone go?
Highways and rivers lie on top of each other, and our motorway (the star) sits among the rivers.
\(f\): mean and spread of red, green and blue
\(p = \operatorname{softmax}(W f + b)\)
\(W\) is 10 by 6 and \(b\) has 10 entries: 70 weights. On the 1,000 test tiles it is right 60% of the time; guessing gives 10%. Every model from here on must beat this.
Industrial areas and forests have colours of their own. A highway is a thin grey line in a field: its colours are mostly the field's, and colour gets it right a quarter of the time.
To tell a highway, you have to see a shape. Averages throw away where everything is.
Part 3 of 5
Why does a network that sees every pixel do worse?
It gets 91% of the tiles it trained on, and 51% of new ones: worse than six colour numbers. It has memorised.
our motorway, by this network
Each unit has its own weight for every pixel. A road in the top left corner and the same road in the bottom right are, to a unit, two unrelated patterns, each to be learned from examples.
From 200 examples of each kind, what it finds looks like noise: whatever happened to fit those tiles.
1. What matters is nearby. Whether the boxed pixel is road depends on its neighbours, not on the dashed corner 300 metres away.
2. A road is a road anywhere. The same pattern, in three tiles, at three different places.
Build both facts into the network, and it no longer has to learn them. That is the whole idea of the next part.
Part 4 of 5
What if the same nine weights look at every place?
the tile \(x\)
\(K\), edit me. On brightness, nine weights; the network's own have one grid per colour.
the feature map \(h\)
With \(C\) input channels (3 colours here), one value of a 3 by 3 layer is
\[ h_{ij} = \operatorname{ReLU}\Big(b + \sum_{c=1}^{C} \sum_{a=-1}^{1} \sum_{d=-1}^{1} K^{(c)}_{ad}\, x^{(c)}_{i+a,\, j+d}\Big). \]
Strictly a cross-correlation (a convolution flips \(K\)); for weights that are learned it makes no difference, and every library calls it convolution.
Flatten each channel to a vector of 1,024 numbers. The layer is then a matrix with 1,024 rows, each with only 9 nonzero entries per channel, and the same 9 values in every row, shifted along: a fully connected layer forced to be local and to repeat itself.
a hidden unit
3,072 weights
a detector
27 weights
the tile, shifted right
its feature map
the original map, shifted
Let \(S\) shift a tile by one pixel. Every value of a convolution uses the same \(K\) on its own neighbourhood, so convolving a shifted tile gives the shifted map:
\[ \begin{gathered} K \star (S x) = S\,(K \star x), \\ \operatorname{ReLU}(S h) = S \operatorname{ReLU}(h). \end{gathered} \]
The operation commutes with the shift: it is equivariant. Exactly so with wrap-around borders; with zero padding it fails within one pixel of the edge.
Pooling by 2 keeps it only for shifts by 2, and the average over the whole map at the end throws position away: the answer no longer depends on where the road is. Equivariant layers, then an invariant summary.
feature map, 32 by 32
pooled, 16 by 16
Each 2 by 2 block becomes its largest value. A detector that fired anywhere in the block still fires; exactly where, within 40 metres, is forgotten.
The next 3 by 3 layer then covers twice as much of the tile.
\(\text{out} = \left\lfloor \dfrac{n + 2p - k}{s} \right\rfloor + 1\)
Your turn: size a stack
The rim on many maps is the zero padding: past the edge of the tile, a detector reads zeros instead of land. How padding and stride set a map's size: the layer calculator.
Go deeper: counting the 6,362 weights| layer | weights | sees |
|---|---|---|
| 3 × 3, 3 to 8 | 3·9·8 + 8 = 224 | 3 |
| pool | 0 | 4 |
| 3 × 3, 8 to 16 | 8·9·16 + 16 = 1,168 | 8 |
| pool | 0 | 10 |
| 3 × 3, 16 to 32 | 16·9·32 + 32 = 4,640 | 18 |
| average, 32 to 10 | 32·10 + 10 = 330 | all |
| total | 6,362 |
A layer with kernel \(k\) adds \((k-1)\,s\) pixels to the receptive field, where \(s\) is the product of the strides before it: \(3,\; 3+1,\; 4+2\cdot 2,\; 8+1\cdot 2,\; 10+2\cdot 4 = 18\).
None of these counts depends on the size of the tile: the same 6,362 weights run on a 64 by 64 tile, or on all of Lebanon.
Part 5 of 5
What did it learn, and what does it still miss?
our motorway, after each pass
Solid lines: test tiles; dotted: the tiles it trains on. Width scales every layer's detectors; flips and turns show each tile in one of eight orientations, a new one each pass. Runs start from new random weights and differ by a few points. 20 passes reach about 68%; the network on the other slides trained for 80: 78.5%, the best of three starting points (the others gave 76.8% and 76.0%).
Colour creeps from 55.8% at \(n = 10\) to 62.3% at \(n = 200\). The network that weighs every pixel never catches up with it.
The convolutional network starts level with colour and keeps climbing: 71.3% at \(n = 50\), 74.4% at \(n = 200\). Knowledge built in is worth a great many examples.
The 78.5% on the other slides is one network trained longer, 80 passes on all 200 tiles per kind: the best of three runs, whose mean is 77.1%.
Nobody told it about edges. Several detectors light up along the road's two edges, others on the dark forest or the bright field: the parts the later layers combine.
78.5% of the 1,000 test tiles right: the best of three training runs (their mean is 77.1%).
The largest mistake: 27 of 100 highways read as rivers (46 read right). It has learned to see a line through green; which kind of line, not yet.
The 32 by 32 tile the networks see
Colour 70 weights
Every pixel 197,322 weights
Convolutional 6,362 weights
What did you use? Rivers meander and widen; motorways run straight and meet at junctions. That is shape at the scale of the whole tile, more than the 18 pixels one number of the network sees.
Thirteen times more tiles leave the small network where it was: 6,362 weights hold all they can. With four times as many detectors in every layer, the same data reads our motorway, at last, as a highway. Telling which kind of line takes more detectors, and the data to train them.
All 27,000 tiles are from 34 European countries. Terraced hillsides, the Bekaa's fields and Beirut's density are not among them: whether it reads them is an experiment, not a promise.
We halved the tiles. A car, a bridge, the ripples on water are now smaller than a pixel.
A tile with a river beside a road has to be one or the other.
A river meanders and a motorway runs straight with junctions; at 18 pixels of view the network barely sees that far.
Gradients. Backpropagation through a convolution is again a convolution: the gradient for \(K\) is the input correlated with the gradient of \(h\). Training costs about three forward passes.
Fourier. A convolution is a multiplication of Fourier transforms: \(\widehat{K \star x} = \hat K \cdot \hat x\) (with wrap-around borders). Fourier neural operators learn the multiplier \(\hat K\) directly, on the lowest frequencies, which is why they run on any grid.
Physics. The finite-difference step for the heat equation, \(u^{t+1}_{ij} = u_{ij} + \alpha\,(u_{i+1,j} + u_{i-1,j} + u_{i,j+1} + u_{i,j-1} - 4u_{ij})\), is a 3 by 3 convolution whose weights you chose. A CNN trained on simulations learns its own.
import numpy as np, torch, torch.nn as nn, torch.nn.functional as F
from PIL import Image
S = np.asarray(Image.open('data/eurosat_32.png'), dtype=np.float32) / 255 # 60 rows of 50 tiles
X = torch.tensor(S.reshape(60, 32, 50, 32, 3).transpose(0, 2, 4, 1, 3).reshape(3000, 3, 32, 32))
y = torch.tensor(__import__('json').load(open('data/eurosat_meta.json'))['labels'])
mu, sd = X[:2000].mean((0, 2, 3), keepdim=True), X[:2000].std((0, 2, 3), keepdim=True)
X = (X - mu) / sd # tiles 0-1999 train, 2000-2999 test
net = nn.Sequential(
nn.Conv2d(3, 8, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(8, 16, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(16, 32, 3, padding=1), nn.ReLU(), nn.AdaptiveAvgPool2d(1),
nn.Flatten(), nn.Linear(32, 10))
print(sum(p.numel() for p in net.parameters()), 'weights') # 6362
torch.manual_seed(0); opt = torch.optim.Adam(net.parameters(), 3e-3, weight_decay=1e-4)
for epoch in range(80): # on the CPU: the Mac GPU backend trains this badly
for b in torch.randperm(2000).split(64):
opt.zero_grad(); F.cross_entropy(net(X[b]), y[b]).backward(); opt.step()
net.eval(); right = (net(X[2000:]).argmax(1) == y[2000:]).float().mean()
print(f'{right:.1%} of the 1,000 test tiles right') # about 77 to 79%
Open in Colab The same network on all 27,000 EuroSAT tiles at 64 by 64, on a free GPU, with three tasks of your own.
Keep the one-page formula sheet, and come back tomorrow for eight review questions. Want to build? Build has kernels to design, the loop to write and a network of your own.
Optional, after the five parts
Can you build what the network learned?
\(K\), weights from −9 to 9
the map
import numpy as np
def conv2d(x, K, b):
# x: the tile, C by H by W (one grid per colour)
# K: the kernel, C by 3 by 3. b: one number, the bias
# Return the H by W map. Past the edge, pixels count as zero.
C, H, W = x.shape
h = np.zeros((H, W))
# your loops here
return himport numpy as np
def maxpool(h):
# h: a map, H by W, both even
# Return the H/2 by W/2 map: keep the largest value in each 2 by 2 block
H, W = h.shape
out = np.zeros((H // 2, W // 2))
# your loops here
return out# the deck's network, layer by layer
NET = [("conv", 3, 8, 3), ("pool", 2),
("conv", 8, 16, 3), ("pool", 2),
("conv", 16, 32, 3), ("average",),
("linear", 32, 10)]
def count_weights(net):
# layers: ("conv", c_in, c_out, k), ("pool", size),
# ("average",), ("linear", n_in, n_out)
# Return every number training adjusts: weights and biases
total = 0
# your loop here
return totalOne way to write it. Read it, then write your own: the tests run on the editor's code.
Each layer: k by k convolutions and ReLU, then 2 by 2 max pooling (not after the last); then an average over positions and ten outputs. Adam at 0.003, the last quarter of the passes at 0.0003.
\(C_{\text{in}} \cdot k^2 \cdot C_{\text{out}} + C_{\text{out}}\)
one \(k\) by \(k\) grid per map coming in, for every detector, and one bias each. A linear layer: \(n_{\text{in}} n_{\text{out}} + n_{\text{out}}\). Pooling and averaging have none.
The deck's network: 224 + 1,168 + 4,640 + 330 = 6,362, for a tile of any size.
\(\text{out} = \left\lfloor \dfrac{n + 2p - k}{s} \right\rfloor + 1\)
input \(n\), kernel \(k\), padding \(p\) on each side, stride \(s\). With \(k = 3, p = 1, s = 1\) the size stays; 2 by 2 pooling with stride 2 halves it.
The deck's network: 32, then 16, then 8 across.
\(r_{\ell} = r_{\ell-1} + (k_{\ell} - 1)\, j_{\ell-1}, \quad j_{\ell} = s_{\ell}\, j_{\ell-1}\)
start with \(r_0 = 1\) pixel and \(j_0 = 1\), the pixels one step spans; each layer adds \(k - 1\) steps, and its stride \(s\) multiplies the step (2 by 2 pooling: \(k = 2, s = 2\)).
The deck's network: 3, 4, 8, 10, then 18 pixels: 360 metres of a 640-metre tile.
\(\text{conv}(\text{shift}(x)) = \text{shift}(\text{conv}(x))\)
the same weights at every place, so a shifted tile gives a shifted map, the same away from the border. An average over positions then makes the answer almost independent of where things are.
One value: \(h_{ij} = \mathrm{ReLU}\big(b + \sum_{c}\sum_{a,d} K_{c,a,d}\, x_{c,\,i+a,\,j+d}\big)\)
Missed items come back the next day. Bookmark this page with ?review=1 at the end of its address to open straight here.