Lesson 12 of 187 min
Architecture families
Each family of networks assumes something about its data, where to look for what matters, and that assumption helps when it is true and costs when it is false.
After this lesson you can say what MLPs, CNNs, RNNs and transformers each assume about the data.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Move the digits up or down
The course's digits have eight rows of pixels. Shift them with blank rows at the edge that opens up. Moving up cut the MLP's accuracy to 51.7% and the CNN's to 66.7%. Moving down gave 43.3% and 55.8%. Those numbers are for the same 360 held-out digits as in the video.
import torch
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
images, labels = load_digits(return_X_y=True)
train, held, y_train, y_held = train_test_split(
images, labels, test_size=0.2, stratify=labels, random_state=0
)
train = torch.tensor(train.reshape(-1, 1, 8, 8) / 16, dtype=torch.float32)
held = torch.tensor(held.reshape(-1, 1, 8, 8) / 16, dtype=torch.float32)import torch.nn.functional as F
def up(images):
return F.pad(images[..., 1:, :], (0, 0, 0, 1))
def down(images):
return F.pad(images[..., :-1, :], (0, 0, 1, 0))
print(up(held).shape, down(held).shape)torch.Size([360, 1, 8, 8]) torch.Size([360, 1, 8, 8])
Teach the MLP about moved digits
Give the same label to the original digit and its moved copies. This is data augmentation. Train the MLP from the earlier lesson on the combined data, then score it on the held-out digits. Keep that split fixed so none of the copies come from the test set.
y_train, y_held = torch.as_tensor(y_train), torch.as_tensor(y_held)
augmented = torch.cat((train, up(train), down(train))).flatten(1)
augmented_labels = y_train.repeat(3)
print(augmented.shape, augmented_labels.shape)torch.Size([4311, 64]) torch.Size([4311])
Keep the strongest match from each map
The CNN makes 16 maps in its last convolution. AdaptiveMaxPool2d(1) keeps the strongest answer from each whole map. The final layer reads those 16 numbers. Count all the weights and biases and you get 3,738 parameters, compared with 2,410 in the full digits MLP.
from torch import nn
maps = nn.Sequential(
nn.Conv2d(1, 8, 3, padding=1), nn.ReLU(),
nn.Conv2d(8, 16, 3, padding=1), nn.ReLU(),
nn.Conv2d(16, 16, 3, padding=1), nn.ReLU(),
)
pool = nn.AdaptiveMaxPool2d(1)
cnn = nn.Sequential(maps, pool, nn.Flatten(), nn.Linear(16, 10))sample = maps(held[:1])
print(sample.shape, pool(sample).shape)
print(sum(p.numel() for p in cnn.parameters()))torch.Size([1, 16, 8, 8]) torch.Size([1, 16, 1, 1]) 3738
Try padding and stride
Padding adds a border of zeros so the window can sit over edge pixels. Stride sets how far the window moves at each step. With an eight-by-eight input, a three-by-three window and one pixel of padding, stepping by one gives an eight-by-eight map. Stepping by two gives a four-by-four map.
for stride in (1, 2):
layer = nn.Conv2d(1, 8, kernel_size=3, padding=1, stride=stride)
print(stride, tuple(layer(held[:1]).shape))1 (1, 8, 8, 8) 2 (1, 8, 4, 4)
Find the windows in ResNet-18
Print the model to see how a larger CNN is put together. The first window is seven by seven, and it moves two pixels at a time. Look for the smaller convolutions inside the blocks further down. weights=None builds the architecture locally, with no download.
from torchvision.models import resnet18
model = resnet18(weights=None)
print(model)ResNet( (conv1): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, bias=True, track_running_stats=True) (relu): ReLU(inplace=True) …
Run on Python 3.13.3, PyTorch 2.15.0, torchvision 0.29.2, and scikit-learn 1.9.1. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Layers and networks
A smaller digits network: nn.Sequential(nn.Linear(64, 16), nn.ReLU(), nn.Linear(16, 10)). Its hidden layer is 16 wide. How many weights does it have, with the biases too?
2 of 3
You scramble the pixels of every picture, the same way in every picture. Then you train an MLP and a CNN on them again. Which one now does worse, and why?
3 of 3
A CNN layer slides 16 windows over a photo of a million pixels. Each window is 3 by 3 pixels, with a bias of its own. How many weights does the layer hold?
The ideas in this lesson
- MLP
- Layers where every input joins every neuron through its own weight; it ignores where an input sits.
- Convolutional network (CNN)
- One small window of weights slides over every place of a picture, so a pattern is found wherever it is.
- What a family assumes
- Each family assumes something about its data: true, it helps; false, it costs. Assuming less needs more data.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
What does it look at?
Here's a question. Networks come in four big families. The names sound hard, but one question tells them apart. What does one part of each network look at?
Move it one pixel
Here's the network you've trained all through this course. It reads about ninety-five percent of the digits set aside. Now move every one of those digits one pixel to the right. How many will it still read? About the same, a little fewer, or less than half?
Every pixel, its own weight
First, what does this network look at? Each of its thirty-two neurons in between reads all sixty-four pixels. Each pixel comes in through a weight of its own. Together, a neuron's weights draw the pattern it looks for. A network made only of layers like this, with every input connected to every neuron, is called an MLP.
Scrambled pixels
But does it know which pixels sit next to each other? Let's find out.
Scramble the pixels of every picture, the same way in every picture. To us, the digits now look like noise. Can it still learn them?
Train it again, and it still reads about ninety-five percent. As good as before. To an MLP, the pixels are just a list. Where a pixel sits means nothing to it.
A moved digit
So, back to your guess. Move every digit one pixel to the right... and it only reads about forty-two percent. Less than half. It read this three as a three, ninety-seven percent sure. Now it calls it a nine. Why?
Each weight was learned for the ink in one place. Move the digit, and the stroke lands on weights that were learned for other pixels. To read a stroke in a new place, the MLP would have to learn it all over again.
A window that slides
An MLP's neurons read every pixel, each through its own weight. So it fails on a moved digit. How could a network find a stroke, wherever it is?
Think of finding a friend in a photo of a crowd. You look at one small patch at a time, and you recognize their face wherever it is.
A CNN does that. It slides one small window, three pixels by three, over every place in the picture. Its nine weights are learned. And the same nine weights are used at every place.
At each place, the CNN writes down how well the pixels there match the window's pattern. That's its map.
The map moves
Now move the digit one pixel. The map moves with it.
A CNN trained on the same digits, with the same loop, has three layers of windows.
Then it keeps each window's strongest answer, wherever it was, so it doesn't matter where the stroke sits.
Moved one pixel, it still reads over ninety-two percent. Not moved, almost ninety-seven. The three is still a three.
What a family assumes
A CNN slides one small window over every place in a picture. So what did it assume? Two things. Pixels next to each other belong together. And a stroke means the same thing, wherever it is. That's the CNN's assumption, built into its design. So scramble the pixels again. Which network does worse now?
The CNN. Its window's nine pixels are strangers now. It drops from almost ninety-seven to about ninety-three percent. That's now below the MLP.
And the MLP lost nothing.
When an assumption is true, it helps. When it's false, it costs you.
One token at a time
And text, where the order of the words matters?
A sentence reaches a network as tokens, small pieces of words. An RNN reads one token at a time. It carries a state from each step to the next: a short list of numbers, its memory so far.
At the last token, the RNN reads two things: that token, and what its state kept from the tokens before. It assumes that order matters, and that the last few tokens matter most.
Every token at once
A transformer lets every token look back at every token before it, and at itself. It gives each one a share of its attention. It assumes almost nothing. It learns which tokens matter from the data.
Which one?
So which family should you use?
In general, the less a family assumes, the more data it needs to learn well.
A transformer can read a photo too.
Cut the photo into small squares, and read each square like a token.
Learning from over a million pictures, it did a few points worse than CNNs.
Learning from tens of millions or more, it did better.
Today's language models are built on attention, with an MLP in every layer.
So choose based on the shape of your data, and on how much of it you have.
In code
In code, take a Linear layer from sixty-four pixels to thirty-two neurons. With each neuron's bias, it holds about two thousand weights. A layer of eight windows, three by three, holds eighty. Now take a photo of a million pixels. How many weights does the Linear layer need?
Thirty-two million. The windows still need eighty.
Real models mix the families. Print a real, recent language model, and you can see them. Its first layers have a part called linear attention. Despite its name, it carries a state from token to token, like an RNN. Inside it is a Conv1d: a window, sliding along the tokens.
Every fourth layer has full attention, the transformer's part. And every layer has an MLP.
All four families, in one model.
Four assumptions
So, the MLP assumes nothing about where a pixel is.
The CNN assumes that neighbors belong together. The RNN, that order matters.
And the transformer assumes almost nothing, so it needs the most data.
Where to look
Each family assumes something about its data. Now try it on this lesson's page, and take the quiz. Move the pictures further, and see which family still reads them.
You use this lesson in Lab 5: Who reads a moved digit, after What hidden layers learn.
Facts last checked on .
