Lesson 8 · The primitives toolbox
Why a network's shape matters
The problem
The pizza kitchen has a camera over the counter. It takes a small greyscale photo of every slice, 12 pixels by 12 pixels. You want a network that answers one question: is there a pepperoni on this slice?
Each photo is a grid of 144 numbers, grey levels from 0 to 9. Melted cheese is about 3 or 4. A few herbs are 1. A pepperoni is a round blob of 9s, three pixels across, and it can be anywhere on the slice.
There's a catch. When the training photos were taken, the slices were always put down the same way round, so every pepperoni sits on the left. Later the kitchen stops putting the slices down the same way. Now a pepperoni can be anywhere, including on the right, where no training pepperoni ever was.
Training: the pepperoni is always on the left
Test: the pepperoni has moved right
A person would not be fooled for a moment. A pepperoni is a pepperoni wherever it is. Whether a network is fooled depends on its shape.
An MLP sees a list of 144 numbers
To give an image to an MLP, you first flatten it: write the 12 rows one after another as a list of 144 numbers. Each hidden unit then has 144 weights, one for each pixel position.
Nothing in that list says that pixel 5 sits next to pixel 6, or that row 2 sits above row 3. A pepperoni on the left and a pepperoni on the right use different pixels, so they reach the MLP through different weights. As far as the MLP can tell, they are unrelated patterns.
Predict first
An MLP has learned to spot pepperoni on the left of the slice. You move the pepperoni to the right. Does it still spot it?
Try it. The figure trains two networks on the same 200 training slices, all with the pepperoni on the left.
One is an MLP with 16 hidden units. The other is a tiny convolutional network, which slides four small 3 × 3 detectors over every position of the image. It has 50 weights in all. (The next lesson builds it properly. For now, think of each detector as one small pattern-finder, used everywhere.) Press play, then compare the test results.
Step 0 · of 300
Test slices each model gets right
2,354 weights0 / 134 / 2150 / 50
50 weights13 / 1320 / 210 / 50
One pepperoni moved across a plain slice: each model’s P(pepperoni), from column 2 (left) to column 9 (right)
Things to notice after 300 steps:
- Both networks get every training slice right, and all 13 test slices with the pepperoni on the left.
- The MLP finds none of the 21 pepperoni that moved right. It calls those slices plain.
- The tiny network finds all 21.
- The test set has 50 pepperoni. The other 16 sit in columns 5 and 6, between the two groups, so these counts leave them out.
- In the strips, the MLP's probability is 1.00 while the pepperoni is in columns 2 to 4, where it trained. From column 6 on, it's 0.03. The tiny network stays at about 0.99 everywhere.
The MLP has not failed to learn. It learned exactly what its training data showed: bright pixels in the left-hand columns mean pepperoni. It had no reason to expect anything about the right-hand columns.
More data would fix the MLP, slowly
An MLP with enough units can represent the right answer (that's universal approximation). The trouble is the data it needs to find it. It has to see a pepperoni in every part of the slice, because each part has its own weights.
Here both networks train on slices with the pepperoni anywhere, using the first 10, 20, 50, 100 or 200 training slices. Each number is the test accuracy, averaged over 3 runs.
| Training slices | MLP | Tiny CNN |
|---|---|---|
| 10 | 69% | 100% |
| 20 | 68% | 100% |
| 50 | 86% | 100% |
| 100 | 82% | 100% |
| 200 | 99% | 100% |
The tiny network is perfect after 10 slices. The MLP needs about 200 to catch up. Its runs vary a lot on the way: at 100 slices, one of its three runs got stuck at 50%, which pulls that average down.
Inductive bias
The tiny network won because of what it assumes before it sees any data. The assumptions built into a model's shape are called its inductive bias. Training can only choose among the functions that the shape allows. The shape decides which answers are easy to reach.
The tiny network builds in two assumptions about images:
- Nearby pixels matter together. Each detector looks at a 3 × 3 patch, not at all 144 pixels at once.
- A pattern means the same thing wherever it appears. Each detector uses the same 9 weights at every position.
Using the same weights at many positions is called weight sharing. Whatever the detector learns from a pepperoni on the left, it already applies on the right. The MLP makes a much weaker assumption: any pixel might matter, together with any other pixel. That freedom costs weights, and weights cost data.
Counting weights
Count the weights in each network's first layer. Take a 28 × 28 image, a common size for small handwritten-digit images.
Worked example
A 28 × 28 image: a fully connected layer against a convolution
MLP with 100 hidden units. Each unit has one weight per pixel, and there are pixels. That's weights, plus 100 biases: 78,500 numbers to learn.
Change the sizes below. The convolution's count never depends on the image size, because the same filter covers the whole image. At 224 × 224, a common input size for photo models, the MLP's first layer has over 5 million weights.
28 × 28 pixels × 100 units + 100 biases
8 filters × 9 weights + 8 biases (the same for any image size)
The convolution has about 981 times fewer weights.
Bars use a log scale: each step of 10× adds the same length.
Fewer weights also leave less room to memorise the training set, so overfitting is less of a risk. In the language of ML fundamentals, the convolution has a lower capacity, aimed at the right functions. That is why it generalises from 10 examples.
Shifting the input: equivariance and invariance
Here is the tiny network's trick in slow motion. Its detector is a hand-set 3 × 3 filter shaped like a plus, which fires on a pepperoni and stays silent on cheese. Sliding it over the slice gives a 10 × 10 grid of scores, one per position. Move the pepperoni and watch the grid.
Slice
box: where the detector fires most
Detector’s feature map
green: the detector fires
Peak of the map: row 5, column 3 (moves with the pepperoni)
Biggest value: 2 (stays the same)
Two things happen, and each has a name.
- The grid of scores moves with the pepperoni. Shift the input one column right, and the scores shift one column right. When shifting the input shifts the output in the same way, the layer has equivariance to shifts.
- The biggest score stays the same. It's 2 wherever the pepperoni is. When shifting the input leaves the output unchanged, the output has invariance to shifts.
In symbols, write for "shift the image one column" and for the layer. Equivariance says : shifting first or afterwards gives the same result. For , the whole network's yes/no answer, invariance says : the shift makes no difference to .
The tiny CNN uses both. Its detector layer is equivariant, so a pepperoni anywhere makes a peak somewhere. Then it keeps only the biggest score in the grid, which is invariant, so the answer doesn't depend on where the peak was. The MLP has neither. Its answer depends on which pixels are bright.
DeeperHow exact is the invariance?In this lesson it's exact. In real networks it's only roughly true, and the reason is the image's edges. · 2 min
In the figure, the biggest score is exactly 2 at every column. That's because the whole pepperoni always fits inside the slice, and the detector visits every position.
Real networks bend the rule in two places.
- Edges. Move the pepperoni half off the slice, and the detector sees only part of it. The score drops.
- Skipping positions. Big networks often move their filters two pixels at a time, or shrink their grids as they go, to save work. Then a one-pixel shift can land the pattern between two positions the filter visits, and the output changes a little.
So a trained image network is roughly shift-invariant, not exactly. The Convolutional networks course covers these steps and their side effects.
Every shape of data has an assumption
An inductive bias helps only when it's true of your data. The tiny CNN keeps the biggest score and throws away where it was. That's right when the question is whether there's a pepperoni. It would be wrong if the question were which half of the slice the pepperoni is on. The network can no longer tell left from right.
So you choose a network's shape by asking what's true of your data. Each shape of data has a natural assumption, and each building block in this level of the course builds one in. Tap the cards.
The rest of this level takes them in turn: convolutions for grids, recurrence and attention for sequences, and graph networks for graphs.
DigressionEvery model has an inductive biasLinear models, nearest neighbours and decision trees, seen as assumptions about the data. · 2 min
Networks aren't special here. Every learning method assumes something, or it could never guess beyond its training data.
- A linear model assumes the output changes in a straight line with each feature. Its boundary between classes is a straight line.
- k-nearest neighbours assumes that points close together have the same label. Its answer for a new point copies its neighbours.
- A decision tree assumes the answer changes in steps, one feature at a time. Its boundaries are made of horizontal and vertical lines.
When the assumption fits the data, the method learns from few examples. When it doesn't, no amount of tuning fully makes up for it.
In PyTorch
The two models from the figure, as PyTorch code. nn.Flatten() turns each image into a list of 144 numbers. nn.Conv2d is the convolution layer, taught properly in the next lesson (`nn.Conv2d`). nn.AdaptiveMaxPool2d(1) keeps the biggest value in each grid of scores.
def make_mlp() -> nn.Sequential:
"""Every pixel gets its own weight in every hidden unit: 144 × 16 + 16 + 16 × 2 + 2 = 2,354 weights."""
return nn.Sequential(
nn.Flatten(), # (n, 1, 12, 12) → (n, 144): the grid becomes one long list
nn.Linear(144, 16),
nn.ReLU(),
nn.Linear(16, 2),
)
def make_cnn(filters: int = 4) -> nn.Sequential:
"""Four 3×3 filters used at every position: 4 × 9 + 4 + 4 × 2 + 2 = 50 weights."""
return nn.Sequential(
nn.Conv2d(1, filters, kernel_size=3), # (n, 1, 12, 12) → (n, 4, 10, 10)
nn.ReLU(),
nn.AdaptiveMaxPool2d(1), # the biggest value in each map: (n, 4, 1, 1)
nn.Flatten(), # (n, 4)
nn.Linear(filters, 2),
)Training reuses the Lesson 4 template's train_one_epoch and evaluate; the loader and the step count are new. The data are images instead of two numbers, so each batch has shape (32, 1, 12, 12): 32 images, 1 grey channel, 12 rows, 12 columns.
def train(model: nn.Module, x: torch.Tensor, y: torch.Tensor, steps: int = 300, seed: int = 0) -> nn.Module:
"""About `steps` AdamW steps (learning rate 0.01, batches of 32), using the Lesson 4 loop."""
device = get_device()
model.to(device)
loader = DataLoader(TensorDataset(x, y), batch_size=32, shuffle=True, generator=torch.Generator().manual_seed(seed))
optimizer = torch.optim.AdamW(model.parameters(), lr=0.01)
loss_fn = nn.CrossEntropyLoss()
for _ in range(math.ceil(steps / len(loader))):
train_one_epoch(model, loader, loss_fn, optimizer, device)
return model
@torch.inference_mode()
def found(model: nn.Module, x: torch.Tensor, y: torch.Tensor, centres: list) -> dict[str, int]:
"""How many test slices in each group the model gets right."""
model.eval()
device = next(model.parameters()).device
correct = (model(x.to(device)).argmax(dim=1).cpu() == y).tolist()
counts = {"left": 0, "right": 0, "plain": 0}
for ok, centre in zip(correct, centres, strict=True):
group = group_of(centre)
if group and ok:
counts[group] += 1
return counts
def shifted_test(seed: int = 0) -> dict[str, dict[str, int]]:
x_train, y_train, _ = image_tensors("leftOnlyTrain") # pepperoni only ever on the left
x_test, y_test, centres = image_tensors("test") # pepperoni anywhere
results = {}
for name, make in [("mlp", make_mlp), ("cnn", make_cnn)]:
seed_everything(seed)
model = train(make(), x_train, y_train, seed=seed)
results[name] = found(model, x_test, y_test, centres)
return resultsRunning the file prints the same counts as the figure. The MLP finds 0 of the 21 moved pepperoni, and the tiny CNN finds all 21. The two versions start from different random weights. The figure uses seed 1, because with seed 0 the browser MLP's ReLUs all switch off in the first few steps and it never learns.
The headline result held for every seed we tried. The MLP never found a moved pepperoni. The CNN found all 21 whenever it learned at all. (With PyTorch seed 3, it didn't learn, and called every slice plain.)
Common misconceptions
"Inductive bias is a flaw, like bias in the bias–variance trade-off." They are different ideas that share a word. The bias–variance bias is a systematic error. An inductive bias is an assumption. A good one is what lets a model learn from little data.
"An MLP can't learn images." It can. With 200 slices showing the pepperoni everywhere, it reached 99%. It needs far more data than a network whose shape fits images, because it has to learn the same pattern separately at every position.
"Convolutions don't care where things are." The convolution layer keeps position: its grid of scores shows where each pattern is. Only the step that keeps the biggest score throws position away. You choose that step when position doesn't matter.
"Fewer weights means a weaker model." Not when the weights are in the right place. The tiny CNN has 50 weights to the MLP's 2,354, and it does better on this task.
Recap
- A network's shape builds in assumptions about the data, called its inductive bias. When they fit, it needs far fewer weights and examples.
- An MLP treats an image as a list of pixels with no neighbours. A pattern learned in one place tells it nothing about another place.
- Weight sharing uses the same small filter at every position, so a pattern learned anywhere is found everywhere. For a 28 × 28 image, it cuts the first layer from 78,500 weights to 80.
- A convolution is equivariant: shift the image, and its output shifts the same way. Keeping only the biggest value makes the answer invariant.
- An assumption helps only when it's true of your data. Each shape of data (table, grid, sequence, graph) has its own building block.
- PyTorch names used:
nn.Flatten,nn.Conv2d,nn.AdaptiveMaxPool2d. - Next: the convolution itself. The Convolutional networks course builds full image networks from it.