A colour photograph is 3,072 numbers. An MLP that flattens it into one long vector needs about 1.7 million weights for two hidden layers, and it has no idea that neighbouring pixels belong together. A convolutional network with 288,746 parameters, about a sixth as many, reads the same pictures with shared kernels and does far better: on the machine used for this lesson, after 20 epochs, its accuracy on 10,000 test images it never saw was about 87.6%, against about 52.9% for an untuned MLP (learning rate 0.01) trained for 20 epochs on the same data.
The notebook
Open the notebook in Colab (source on GitHub). Every run result on this page comes from it: one run with seed 0. Results vary with the hardware, the library versions and the seed, so yours will differ a little; the shape of the story should match. The whole notebook is six 20-epoch runs: the main run, three comparisons and two more seeds. On the machine used for this lesson (a laptop GPU, PyTorch 2.9.1, torchvision 0.24.1) one epoch took about 34 seconds and one run about 11 minutes, so the whole notebook takes about an hour. Running only the main run (sections 1 to 8) is enough to follow the lesson. Use a GPU runtime (in Colab: Runtime, Change runtime type). Without a GPU the training steps alone took about 46 seconds per epoch, about 15 minutes per run, on 8 CPU threads of this machine; a free Colab CPU has fewer cores and will be slower (not measured). The first data cell downloads CIFAR-10 (about 170 MB). No paid service is needed.
The official download was very slow on the day the page was made, so the training images of this run were read from a copy of CIFAR-10 on the Hugging Face hub. Its test set matches the official test batch image for image, and the training images that could be compared matched the official ones in a different order, so the validation split of your run holds other images.
The data: CIFAR-10
CIFAR-10 is a standard small dataset of colour photographs. It was collected by Alex Krizhevsky and colleagues and described in his 2009 technical report “Learning Multiple Layers of Features from Tiny Images”; the dataset page asks users to cite that report.
- 60,000 images, each pixels with 3 colour channels.
- 10 classes, with 6,000 images each: airplane, automobile, bird, cat, deer, dog, frog, horse, ship, truck. The classes are mutually exclusive: “automobile” means cars such as sedans and SUVs, “truck” means big trucks only, and pickup trucks are in neither.
- A fixed split: 50,000 training images (5,000 per class) and 10,000 test images (1,000 per class). Guessing gives 10% accuracy.
As a NumPy array the training set has shape with integer values – (uint8). A batch given to the network has shape with floats in – (P5.1).
Normalization
Every pixel value is standardized per channel (P4.12, P5.1). The statistics come from the 45,000 training images (the validation images are set aside first, see below), and every split is normalized with them, :
- mean (red, green, blue): , ,
- standard deviation: , ,
The model
A CNN for small images is a stack of blocks, and a block does the same thing three times over: look for patterns, keep the strong ones, shrink the map. Here is the one we build, from the layers of the earlier lessons.
- A block is a convolution, a BatchNorm and a ReLU, then a second convolution, BatchNorm and ReLU, then a max pool (P5.6) that halves the height and the width.
- Every convolution has a kernel and padding 1, so it keeps the height and the width (P5.4: ). Only the pool layers shrink the map.
- The three blocks have 32, 64 and 128 channels. Each block halves the height and width of the map. The first block turns the 3 colour channels into 32, and each later block doubles the channels. This is a habit, not a law; a common reason is that a layer that sees a smaller map can afford more kinds of detector.
- The last map, , goes through global average pooling: the average of each of the 128 maps, which gives a vector of 128 numbers. One linear layer turns it into 10 numbers, the logits, one per class.
Shapes are written , one image, in PyTorch order (a batch is ). After each block the map is , then , then ; global average pooling gives numbers and the linear layer gives .
The widget below builds the same network and lets you change it. The layer list shows the output shape and the parameter count of every layer; the numbers come from the formulas of P5.4 and P5.5, and they match what PyTorch gives for the same layers. Start with the preset Lesson model, then try flatten (the last layer grows from 1,290 to 20,490 parameters) or padding none (each convolution shrinks the map by 2 until one no longer fits).
Counting the parameters
A convolution from to channels with a kernel has weights, plus one bias per output channel unless something removes it (P5.5). Here a BatchNorm layer follows every convolution. BatchNorm subtracts the mean of each channel, so a bias added before it would be subtracted again, and BatchNorm has its own shift (P4.19). That is why the convolutions are built with bias=False. A BatchNorm layer has two learnable numbers per channel, a scale and a shift .
The widget lists the count of every layer. For example, the first convolution has weights and the linear layer .
The total is 288,746 parameters, and 77% of them are in the last block (its two convolutions and their BatchNorm layers). The number of pixels does not appear in any count: a kernel is shared across positions (P5.2).
The same input to an MLP
An MLP on the flattened image ( numbers, P5.1) with two hidden layers of 512 and 256 units (P4.10) has 1,707,274 parameters, 5.9 times as many as the CNN. Its first layer has a separate weight for every pixel and every unit, while a convolution reuses one small kernel everywhere (P5.2).
Parameters are not the same as work. The multiply-adds of one forward pass (P5.4: for each convolution) are about 38.6 million per image for the CNN and about 1.7 million for the MLP, about equal to its parameter count (each weight is used once). A convolution reuses each weight at every position, so it does many more operations with fewer weights. So fewer parameters does not mean less work, and the CNN trains more slowly per epoch.
Loading the data
The pipeline has four steps, and each is a place where a silent mistake can hide.
- Split. Take 5,000 of the 50,000 training images, chosen at random with a fixed seed, as a validation set. The model is trained on the other 45,000. The validation set is for reading curves and making choices. The 10,000 test images are kept for one measurement at the end (P1.G3).
- Statistics. The mean and the standard deviation come from the 45,000 training images only (see above).
- Augmentation, training images only. A random crop of the image padded by 4 pixels (81 possible crops) and a random flip (P4.18); the label does not change.
- Batches. A
DataLoadergroups the images into batches of 128 and shuffles the training set every epoch. The transform order matters: crop and flip, thenToTensor, thenNormalize.
The training loop
The loop is that of P2.7, with a CNN as the model. The settings:
- Loss: cross-entropy on the 10 logits (P4.6).
- Optimizer: SGD with momentum (P4.13), learning rate with a cosine decay (P4.14), weight decay (P4.17).
- Batch size 128, 20 epochs: 352 updates per epoch. These values are reasonable and not tuned (P4.23).
Two checks before the long run
A 20-epoch run takes minutes, and a wrong line of code wastes all of them, so run the two cheap checks of P4.22 first.
1. The first loss. With 10 classes the loss of a uniform guess is (P4.22). Before any update the first batch of this network had a loss of 2.354, close to it. A value of 20 or 200 would point to a bug in the labels, the loss, or the scale of the input or the last layer (P4.12).
2. Overfit one batch. Take 32 images, switch augmentation off, and train on that batch alone. A network with 288,746 parameters can memorize 32 pictures, so the loss should go to almost zero. It did: with SGD (learning rate 0.05, momentum 0.9, no weight decay), the loss was at step 0, at step 10, at step 20, at step 50 and at step 100. The accuracy on the 32 images was 6% at step 0 and 100% at every step printed from step 10. If this check fails, look at the data, the labels, the loss, the backward pass or the optimizer (P4.22). A pass says that the code can learn. It does not say that the model will do well on new images, which is what the validation set measures.
Training and reading the curves
The full run trains for 20 epochs and logs the loss and the accuracy on the training batches and on the validation set after every epoch. The widget shows the logged numbers; the other three buttons show runs from the next section.
What to read from the first run (Lesson CNN):
- Both losses fall and stay close. The training loss goes from 1.438 after epoch 1 to 0.232 after epoch 20, the validation loss from 1.441 to 0.360. At the end the gap is about 4.5 points of accuracy (92.2% against 87.7%).
- Single epochs can jump. The validation accuracy dips from 76.7% after epoch 5 to 74.2% after epoch 7, and from 84.2% after epoch 12 to 80.3% after epoch 13, while the training curve rises without a break. The learning rate is still well above its final value then (the cause was not investigated). Judge the trend and not one epoch (P4.22).
- The curves settle at the end. The cosine decay (stepped once per epoch) brings the learning rate to almost 0 in the last epoch, and the validation accuracy stays at 87.7% for the last three epochs. The validation loss was still falling slowly (0.367, 0.363, 0.360), so this run was not stopped by overfitting. Whether more epochs would help was not tested.
Changing one ingredient at a time
To see what each ingredient is worth, the notebook trains three more models with the same seed, split and 20 epochs: no augmentation and no BatchNorm (one change each), and an MLP (a different model, learning rate 0.01, untuned). Use their buttons in the curves widget above. Test accuracy after 20 epochs on the machine used for this lesson:
- Lesson CNN (288,746 parameters): test accuracy 87.59%; accuracy after epoch 20 was 92.2% on the training batches and 87.7% on validation.
- No augmentation: test accuracy 85.39%. The training accuracy reached 100.0% (loss 0.013) while the validation accuracy was 85.6% and the validation loss 0.519, against 0.360 with augmentation. This is overfitting. Augmentation cut the gap between training and validation accuracy from 14.4 points to 4.5 and raised the test accuracy by 2.2 points.
- No BatchNorm: test accuracy 84.65%. It learned much more slowly at first (validation accuracy 29.9% after epoch 1 against 53.4%, and 62.8% after epoch 5 against 76.7%) and caught up only partly by epoch 20 (85.3% against 87.7%). It took 587 seconds against 686.
- MLP (1,707,274 parameters, learning rate 0.01, not tuned): test accuracy 52.85%, with 56.5% on the training batches. Its training accuracy is low too, so it is not mainly overfitting; the MLP was not tuned.
Each number is one run. The three runs of the lesson CNN with seeds 0, 1 and 2 (the same recipe, only the random numbers differ) gave test accuracies of 87.59%, 87.40% and 87.93%. The spread between seeds is therefore about 0.5 percentage points, and a difference of a few tenths of a percent between two models cannot be read as one being better (P1.G3). The differences above are much larger than that spread, but each comparison is still one run, on one dataset, with settings that were not tuned for any of the variants.
The test set, and the mistakes
After the 20 epochs the model was evaluated on the 10,000 test images, once: test accuracy 87.59% (test loss 0.372; seed 0, 20 epochs, a laptop GPU, PyTorch 2.9.1). The validation accuracy was 87.7%; the two are close, as you hope when the validation set has only been used to look at curves. Results vary with the hardware and the seed, so a rerun gives different digits (P1.G3).
Accuracy is one number. The confusion matrix shows where the rest goes: the cell in row and column counts test images of class that were predicted as class . The diagonal sums to 8,759, so the accuracy is , and every row sums to 1,000.
From this one run:
- Best classes: ship (95.0% of its test images correct), automobile (94.1%) and truck (92.6%).
- Worst classes: cat (74.8%), dog (82.0%) and bird (84.0%).
- The most common mistakes are cat predicted as dog (95 images) and dog predicted as cat (91), then airplane predicted as ship (50), cat as bird (41), automobile as truck (40), and truck as automobile and airplane as bird (36 each).
Cat and dog are the most confused pair: 95 cats were called dogs and 91 dogs were called cats. Automobile and truck are also confused in both directions (40 and 36). Airplane to ship is 50, but ship to airplane is only 20. Why these pairs are hard, the matrix cannot say. Cats and dogs may share a body shape and pose, and cars and trucks may look alike at , but those are guesses and this run did not test them (P5.8 looks inside the network).
Try it in Python
PyTorch does not run in the browser, but a small forward pass can be written in NumPy. The cell takes an colour image of random numbers, applies a convolution with 4 kernels of size and padding 1, a ReLU, a max pool, global average pooling and a linear layer, and prints the shape after each step. Try p=0 and predict the first shape before you run it.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Running the cell gives the shapes , as the formulas of P5.4 predict: padding 1 keeps , the pool halves it, and global average pooling removes the map. The parameters are in the convolution and in the linear layer. The first three logits, , and , equal the output of PyTorch’s F.conv2d, F.max_pool2d and a matrix product on the same numbers. With small random logits the softmax is almost uniform, so the loss of a class is near : for class 3. This is the first-loss check in miniature.
Depth: three ways to see it
Intuition
Picture a photo-sorting line. At the first station small inspectors check every patch of the photo for simple features, an edge or a patch of one colour, and pass on one note-sheet per kind of feature. At the next station inspectors read the sheets and look for combinations, over a larger area, because the sheets were shrunk by half. By the last station each inspector effectively looks at the whole picture, and a final clerk adds up the evidence for each of the ten classes.
The picture holds the design rule: every pool halves the map, so later layers cover more of the original image. It breaks in two places. Nobody chooses the features: the kernels start random and become whatever helps the loss (P5.8). And the stations are not separate: all kernels are trained together by one gradient (P4.8).
Math
Shapes (one image, order). A convolution with kernel , padding , stride 1 and dilation 1 maps (P5.4); with , this is . A max pool with stride 2 maps . Global average pooling maps to numbers, .
The loss. Softmax turns the logits into probabilities, and one image with true class has loss (P4.6). With all ten probabilities equal to , .
Accuracy from the confusion matrix. With the number of test images of class predicted as class : accuracy ; the accuracy of class (its recall) is ; the share of correct answers among the images predicted as class (its precision) is .
Code
The model and the loop in PyTorch, shortened from the notebook. The printed count comes from running it (PyTorch 2.9.1).
import torch, torch.nn as nn
def conv_block(c_in, c_out):
layers = []
for i in range(2):
layers += [nn.Conv2d(c_in if i == 0 else c_out, c_out,
3, padding=1, bias=False),
nn.BatchNorm2d(c_out), nn.ReLU()]
return nn.Sequential(*layers, nn.MaxPool2d(2))
model = nn.Sequential(
conv_block(3, 32), conv_block(32, 64), conv_block(64, 128),
nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(128, 10))
print(sum(p.numel() for p in model.parameters()))
loss_fn = nn.CrossEntropyLoss()
opt = torch.optim.SGD(model.parameters(), lr=0.05,
momentum=0.9, weight_decay=5e-4)
for xb, yb in train_loader: # xb: (128, 3, 32, 32)
loss = loss_fn(model(xb.to(device)), yb.to(device))
opt.zero_grad()
loss.backward()
opt.step()288746The same parameter count as the table above. In the notebook the model is a class and the loop is a function that also measures accuracy and switches between model.train() and model.eval(), as in P2.7.
Go deeper BatchNorm in evaluation mode, and a classic bug
In training mode, BatchNorm normalizes with the mean and variance of the current batch and updates running averages of them. In evaluation mode it uses the running averages, so a prediction does not depend on the other images in the batch. If you forget model.eval() before measuring validation or test accuracy, the numbers depend on the other images in the batch and on its size; if you forget model.train() after validation, the next epoch trains with frozen statistics. The loop of this lesson sets the mode at the top of every pass. Very small batches make the batch statistics noisy, which is one reason GroupNorm and LayerNorm exist (P4.19).
Go deeper Why global average pooling accepts any image size
The linear layer after the pooling has 128 inputs, one per channel, whatever the size of the map before it. So the same weights run on a image (map ) or on a image (map ). The flatten head needs a weight for every position of the last map, inputs here, so it ties the network to one image size and has 20,490 parameters in its last layer instead of 1,290. The price of averaging is that the position of a feature in the last map is thrown away; at that point each position already depends on a large part of the image (the receptive field of P5.6), so the model has what it needs.
Go deeper Why the numbers differ between runs
The same code with the same seed on the same GPU can give slightly different numbers, because some GPU operations add numbers in an order that is not fixed and floating-point addition depends on the order. The overfit check was run twice for this lesson, and at step 10 the loss was in one run and in the other. PyTorch has switches for deterministic algorithms, which are slower and do not remove differences between different hardware (P1.G3). Report the seed, the epochs and the hardware, and treat a few tenths of a percent as noise.
Common mistakes
Quiz
Check your understanding
A convolution takes a map and has 128 output channels, a kernel, padding 1 and stride 1, and no bias (a BatchNorm follows it). What are its output shape and its number of weights?
Padding 1 with a kernel keeps (P5.4). Each output channel has a kernel of weights, one for each input channel, so (P5.5). The answer forgets the padding. The answer with 18,874,368 weights gives every position its own kernels, which is the opposite of weight sharing (P5.2). The answer with 1,152 weights gives each output channel one kernel for all input channels, but a kernel has a separate slice for each input channel.
A new classifier for 100 equally likely classes has a loss of 4.7 on its first batch, before any update. What should you conclude?
With classes and no knowledge the loss is , which is for 100 classes (P4.22). A value of 4.7 is close to it. The value belongs to 10 classes only. No update has happened yet, so the learning rate has not acted, and a memorized batch would have a loss near zero, not above 4.
The random crop and the flip are applied to the training images but not to the validation or test images. What is the reason?
A crop and a flip keep the class of a picture (a flipped horse is still a horse), so the labels are not the problem. The evaluation sets are there to measure the model on real, unchanged images, and a random change would make the measured score depend on chance. The sizes of the images are equal in all splits, and a loader accepts random transforms whether or not it shuffles.
In the confusion matrix, rows are true classes and columns are predicted classes. The cell in the row for cat and the column for dog holds 95. What does that mean?
The row of a cell names the true class and its column names the predicted class, so row cat, column dog counts cats that the model called dogs. The dogs predicted as cats are in the other cell (91 in the lesson run). The cells are counts and not percentages, and a row of the test set sums to 1,000, so 95 images is 9.5% of the cats. Correct predictions are on the diagonal.
Exercises
- The input is . A convolution with 16 kernels of size , padding 2 and a bias is followed by a max pool. What are the output shapes, and how many parameters does the convolution have?
Show answer
Padding 2 with a kernel keeps the size: , so , and the pool gives . Parameters: . - Replace the global average pooling and the linear layer of the lesson model with a flatten and a linear layer from the flattened map to 10. How many parameters does the new last layer have, and how many does the whole network have?
Show answer
The flattened map has numbers, so the layer has parameters. The total is . The last layer is about 16 times bigger, and it now works only for inputs. - Training accuracy is 99% and validation accuracy is 72% and has stopped improving. What is this called, and what are three things to try?
Show answer
It is overfitting: the model fits the training images and does not carry over to new ones. Three things to try: stronger augmentation (random crop, flip; P4.18), weight decay or another regularizer (P4.17), and more data or a smaller model. The comparison run without augmentation in this lesson shows the same pattern, with a larger gap between training and validation accuracy. - Use the matrix of the lesson run. The column of dog sums to 991 images and the diagonal cell of dog is 820. What fraction of the images predicted as dog really are dogs, and how is this different from the 82.0% of the dog row?
Show answer
, about 82.7%. This is the precision for dog, the share of correct answers among the images the model called dog, which is a column of the matrix. The 82.0% of the row is the recall, the share of the 1,000 true dogs that were found. Here the two are close but they answer different questions.
Next: P5.8 looks inside a trained network: the kernels of the first layer, the feature maps of each layer and what the prediction depends on. P5.9 tours the architectures that grew out of this design, from LeNet to ResNet and later, and P5.10 reuses a network trained on a large dataset instead of starting from random weights.