Convolutional neural networks

Can a Computer Tell a River from a Highway?

Test tile 349, 32 by 32 pixels

Test tile 349, 32 by 32 pixels: a motorway through forest

  • Colourriver, 49%
  • Every pixelsea or lake, 82%
  • A small CNNriver, 84%

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

  • design a detector that finds roads
  • work out shapes and weight counts by hand
  • train a network and read its mistakes
  • write the convolution loop

About 90 minutes over three sittings.

It helps to know a neural network, overfitting and softmax and cross-entropy.

Five questionsThree sittings of about half an hour: parts 1 to 3, then part 4, then part 5

  1. 1Ten kinds of landWhat is in a 640-metre square of Europe?
  2. 2Colour firstHow far does colour alone go?
  3. 3Every pixel, separatelyWhy does a network that sees every pixel do worse?
  4. 4One small detector, everywhereWhat if the same nine weights look at every place?
  5. 5River or highway?What did it learn, and what does it still miss?

You firstA tile none of us has seen. Which kind of land is it?

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.

To a computer, a tile is 3,072 numbers32 rows, 32 columns, three brightnesses per pixel from 0 to 255. Point at the tile.

Remember this 3 by 3 window. In part 4 a detector will look at exactly this much at a time.

2,000 tiles to learn from, 1,000 to judgeThe same split for every model in this deck, and one tile we follow to the end

200 per kind to train on, 100 per kind to test, never seen while learning

Notation, used throughout
\(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

Test tile 349, a motorway through forest. A line through green: river or highway?

Part 2 of 5

Colour first

How far does colour alone go?

Colour sorts the land, partlyOne marker per training tile, at its average colour; big markers are the averages of each kind. Point at a marker.

Highways and rivers lie on top of each other, and our motorway (the star) sits among the rivers.

Six numbers per tileThe honest baseline: keep the colours, forget where anything is. Pick a tile.

\(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.

What colour can tell, and what it cannotThe colour model on the test tiles, right per kind of land

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

Every pixel, separately

Why does a network that sees every pixel do worse?

A network that weighs every pixelA plain neural network: 3,072 numbers in, 64 hidden units, 10 out. 197,322 weights.

It gets 91% of the tiles it trained on, and 51% of new ones: worse than six colour numbers. It has memorised.

Test tile 349

our motorway, by this network

What its hidden units look forTwelve of its 64 hidden units, each one's 3,072 weights drawn as a tile

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.

Two things we know about picturesand that the network has to find out for itself, from 2,000 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

One small detector, everywhere

What if the same nine weights look at every place?

From a hidden unit to a detectorBuild the two facts into one hidden unit, in two steps

Slide nine weights across the tileA 3 by 3 kernel \(K\) on the brightness of the tile. Point at either image, edit \(K\), or sweep.

the tile \(x\)

\(K\), edit me. On brightness, nine weights; the network's own have one grid per colour.

the feature map \(h\)

The formula, and the matrix it hidesDeep dive

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.

Sharing weightsThe first layer, counted, as the image grows. A detector on a colour tile has one kernel-sized grid of weights per colour.

a hidden unit
3,072 weights

a detector
27 weights

Shift the tile, and the map shifts with itThe road detector the network learned, on our motorway. Drag the slider to shift the tile to the right.

the tile, shifted right

its feature map

the original map, shifted

Why the map shifts: equivarianceDeep dive

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.

Keep the strongest, halve the sizeMax pooling, on the road detector's map of our motorway. Point at either map.

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.

How much of the tile one number seesIts receptive field. Pick a layer, then point at the tile.

How big is the next map?A \(k\) by \(k\) kernel slides over an \(n\) by \(n\) input with padding \(p\) and stride \(s\). Then size a whole stack yourself.

\(\text{out} = \left\lfloor \dfrac{n + 2p - k}{s} \right\rfloor + 1\)

Your turn: size a stack

Our motorway, through the whole networkThree detector layers, with pooling after the first two, an average, a classifier: a convolutional neural network, 6,362 weights.

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.

Counting the 6,362 weights, and the receptive fieldDeep dive

layerweightssees
3 × 3, 3 to 83·9·8 + 8 = 2243
pool04
3 × 3, 8 to 168·9·16 + 16 = 1,1688
pool010
3 × 3, 16 to 3216·9·32 + 32 = 4,64018
average, 32 to 1032·10 + 10 = 330all
total6,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

River or highway?

What did it learn, and what does it still miss?

Train it yourselfThe network you just walked through, from random weights, with cross-entropy and gradient descent, here in the page

Width
Passes

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%).

More tiles: the seeing improves, the colour does notTest tiles right, against tiles per kind. Trained in Python: each point averages three runs of 60 passes.

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%.

What the first layer learnedIts 8 detectors (3 by 3, in colour), and what each one sees in our motorway

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.

Where it goes wrongTrue kind down the side, the network's answer across the bottom, on the 1,000 test tiles. Point at a red cell.

78.5% of the 1,000 test tiles right: the best of three training runs (their mean is 77.1%).

Our motorway, three waysEach model's top three answers for test tile 349

The 32 by 32 tile the networks see

Colour 70 weights

Every pixel 197,322 weights

Convolutional 6,362 weights

River or highway? Your turnSix test tiles. Answer each, then compare with the network.

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.

With all of EuroSATTrained in Python on the other 26,000 tiles, tested on the same 1,000

our CNN, 2,000 tiles
6,362 weights
78.5%27 highways as rivers
motorway: river
our CNN, 26,000 tiles
6,362 weights
77.9%34 highways as rivers
motorway: river (62%)
four times the detectors, 26,000 tiles
94,538 weights
86.7%11 highways as rivers
motorway: highway (95.5%)

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.

What this network cannot knowBefore you trust a map it draws

Only Europe

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.

Only 32 by 32

We halved the tiles. A car, a bridge, the ripples on water are now smaller than a pixel.

One label per tile

A tile with a river beside a road has to be one or the other.

Nearby shapes, not context

A river meanders and a motorway runs straight with junctions; at 18 pixels of view the network barely sees that far.

Convolutions in the rest of scienceDeep dive

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.

The same network in PyTorchCode: prints the numbers these slides quote

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.

What to take away

  1. Start with an honest baseline. Six colour numbers got 60% and set the bar.
  2. Weighing every pixel separately means learning every pattern at every place. From 2,000 tiles, that network memorised.
  3. A convolution slides one small kernel everywhere: nearby only, and the same weights at every place. Its maps shift with the image.
  4. Stack detectors and pool, and each number sees more of the tile; an average at the end makes the answer independent of position.
  5. Knowledge built in is worth many examples: 6,362 weights beat 197,322. It sees a line through green; telling a river from a highway takes more detectors and more data.

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

Build

Can you build what the network learned?

Design your own kernelsFour challenges. The map is your kernel slid over the tile's brightness, then ReLU: below zero becomes 0.

\(K\), weights from −9 to 9

the map

Write the loopYour words first, then Python, checked against the deck's own map of tile 349

    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 h

    Capstone: a network of your ownAt most 10,000 weights, trained here on the 2,000 tiles, scored once on 500 tiles it has never seen

    Layers
    Kernel
    Passes

    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.

    A formula sheetThe deck's four formulas, each with its own example

    Weights of a layer

    \(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.

    Output 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.

    Receptive field

    \(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.

    Equivariance

    \(\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)\)

    ReviewEight questions from what you have done, each due a day and a week after you first met the idea

      The formula sheet

      Missed items come back the next day. Bookmark this page with ?review=1 at the end of its address to open straight here.