Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 5: Computer Vision and CNNs

Build a CNN

P5.740 min●●○ IntermediateReviewed Dec 3, 2026

Why this matters for machine learning

Building and training one small CNN from data to test score is where the ideas of Parts 2, 4 and 5 become a working image classifier. The same pipeline, with a different model in the middle, trains every vision network that follows.

Before this: Padding, stride and dilation, Multi-channel convolutions and 1×1 convs, Pooling and receptive fields, The PyTorch training loop, The training recipe and debugging

After this lesson you can

  • Describe CIFAR-10 and say what one example looks like as an array and as a batch tensor, with the axis order each time
  • Compute per-channel mean and standard deviation from the training split only and apply them to every split
  • Give the output shape and the parameter count of every layer of a small CNN, and compare the total with an MLP on the same input
  • Write the training loop for a CNN in PyTorch and run the first-loss and overfit-one-batch checks before the full run
  • Read training and validation curves and a confusion matrix, and report a test accuracy with its seed and its limits

A 32×3232\times32 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 32×3232\times32 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 (N,H,W,C)=(50000,32,32,3)(N,H,W,C)=(50000,32,32,3) with integer values 00–255255 (uint8). A batch given to the network has shape (N,C,H,W)=(128,3,32,32)(N,C,H,W)=(128,3,32,32) with floats in 00–11 (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, x′=(x−μc)/σcx'=(x-\mu_c)/\sigma_c:

  • mean (red, green, blue): 0.49180.4918, 0.48260.4826, 0.44700.4470
  • standard deviation: 0.24710.2471, 0.24350.2435, 0.26170.2617

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 2×22\times2 max pool (P5.6) that halves the height and the width.
  • Every convolution has a 3×33\times3 kernel and padding 1, so it keeps the height and the width (P5.4: ⌊(H+2⋅1−2−1)/1⌋+1=H\lfloor(H+2\cdot1-2-1)/1\rfloor+1=H). 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, (128,4,4)(128,4,4), 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 (C,H,W)(C,H,W), one image, in PyTorch order (a batch is (N,C,H,W)(N,C,H,W)). After each block the map is (32,16,16)(32,16,16), then (64,8,8)(64,8,8), then (128,4,4)(128,4,4); global average pooling gives 128128 numbers and the linear layer gives 1010.

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 3×33\times3 convolution shrinks the map by 2 until one no longer fits).

Kernel Padding Head
input3×32×32block 132×16×16block 264×8×8block 3128×4×4

Each box is the output of a block: its height follows the height of the map, its width follows the number of channels (on a log scale).

  • LayerOutput (C,H,W)Params
  • Inputone image (3,32,32) 0
  • Conv 3→323×3, BN, ReLU (32,32,32) 928
  • Conv 32→323×3, BN, ReLU (32,32,32) 9,280
  • MaxPool 2×2stride 2 (32,16,16) 0
  • Conv 32→643×3, BN, ReLU (64,16,16) 18,560
  • Conv 64→643×3, BN, ReLU (64,16,16) 36,992
  • MaxPool 2×2stride 2 (64,8,8) 0
  • Conv 64→1283×3, BN, ReLU (128,8,8) 73,984
  • Conv 128→1283×3, BN, ReLU (128,8,8) 147,712
  • MaxPool 2×2stride 2 (128,4,4) 0
  • Global avg poolmean of each map (128,1,1) 0
  • Linear 128→10logits (10) 1,290

Total: 288,746 parameters and 38,634,752 multiply-adds per image. The MLP of the lesson (3072→512→256→10) has 1,707,274 parameters: 5.9 times as many.

The CNN shape builder. Choose the number of blocks, the convolutions per block, the channels of each block, the kernel size, the padding, BatchNorm and the head. The list shows the output shape (C,H,W) and the parameters of every layer (a convolution row includes its BatchNorm; the pink bar is relative to the largest layer), and the totals. When a layer does not fit, the widget shows the error PyTorch would raise.

Counting the parameters

A convolution from CinC_{\text{in}} to CoutC_{\text{out}} channels with a k×kk\times k kernel has k2CinCoutk^2C_{\text{in}}C_{\text{out}} 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 γ\gamma and a shift β\beta.

The widget lists the count of every layer. For example, the first convolution has 3⋅3⋅3⋅32=8643\cdot3\cdot3\cdot32=864 weights and the linear layer 128⋅10+10=1,290128\cdot10+10=1{,}290.

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 (3⋅32⋅32=30723\cdot32\cdot32=3072 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: HoutWoutk2CinCoutH_{\text{out}}W_{\text{out}}k^2C_{\text{in}}C_{\text{out}} 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.

  1. 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).
  2. Statistics. The mean and the standard deviation come from the 45,000 training images only (see above).
  3. Augmentation, training images only. A random 32×3232\times32 crop of the image padded by 4 pixels (81 possible crops) and a random flip (P4.18); the label does not change.
  4. Batches. A DataLoader groups the images into batches of 128 and shuffles the training set every epoch. The transform order matters: crop and flip, then ToTensor, then Normalize.

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 0.90.9 (P4.13), learning rate η=0.05\eta=0.05 with a cosine decay (P4.14), weight decay 5×10−45\times10^{-4} (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 ln⁡10=2.303\ln10=2.303 (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 2.3172.317 at step 0, 0.0990.099 at step 10, 0.0060.006 at step 20, 0.00060.0006 at step 50 and 0.00030.0003 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.

The CNN of this lesson: random crop and flip, BatchNorm, SGD with a cosine decay, 20 epochs.

Loss (cross-entropy) per epoch
510152000.511.5epoch
Accuracy (%) per epoch
5101520020406080100epoch
  • training batches
  • validation set

After 20 epochs: training accuracy 92.2%, validation accuracy 87.7% (best epoch 20), a gap of 4.5 points. Test accuracy 87.6%. Parameters: 288,746.

Loss and accuracy per epoch for four runs of the notebook (logged numbers; nothing is trained in the browser). Solid blue with a circle: the training batches. Dashed pink with a square: the validation set. Choose a run with the buttons.

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 ii and column jj counts test images of class ii that were predicted as class jj. The diagonal sums to 8,759, so the accuracy is 8759/100008759/10000, and every row sums to 1,000.

predicted classtrueplaneautobirdcatdeerdogfroghorseshiptruckplaneautobirdcatdeerdogfroghorseshiptruck8721036951225013894111100264027084026332432774804174828953423111271283486316261942322491178201026435226348109083221021326202418914920122601409505153603201116926

Blue: correct predictions on the diagonal, darker for more. Pink: mistakes, darker for more.

Of the 1,000 test images of class cat, 748 were predicted correctly. Most common mistakes: dog (95), bird (41), frog (34), deer (28).

Confusion matrix of the lesson run on the 10,000 test images (axis labels are shortened: plane is airplane, auto is automobile). Blue on the diagonal: correct. Pink: mistakes, darker for more. Choose a true class below to list what it was most often mistaken for.

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 32×3232\times32, 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 8×88\times8 colour image of random numbers, applies a convolution with 4 kernels of size 3×3×33\times3\times3 and padding 1, a ReLU, a 2×22\times2 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.

One conv layer, pool and head on a tiny image

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Running the cell gives the shapes (4,8,8)→(4,8,8)→(4,4,4)→(4)→(10)(4,8,8)\to(4,8,8)\to(4,4,4)\to(4)\to(10), as the formulas of P5.4 predict: padding 1 keeps 8×88\times8, the pool halves it, and global average pooling removes the map. The parameters are 4⋅3⋅3⋅3+4=1124\cdot3\cdot3\cdot3+4=112 in the convolution and 10⋅4+10=5010\cdot4+10=50 in the linear layer. The first three logits, 0.1980.198, −0.607-0.607 and −0.117-0.117, 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 ln⁡10\ln10: 2.242.24 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, (C,H,W)(C,H,W) order). A convolution with kernel kk, padding pp, stride 1 and dilation 1 maps H→H+2p−k+1H\to H+2p-k+1 (P5.4); with k=3k=3, p=1p=1 this is HH. A 2×22\times2 max pool with stride 2 maps H→⌊H/2⌋H\to\lfloor H/2\rfloor. Global average pooling maps (C,H,W)(C,H,W) to CC numbers, xˉc=1HW∑i,jxc,i,j\bar x_c=\frac1{HW}\sum_{i,j}x_{c,i,j}.

The loss. Softmax turns the logits z∈R10\mathbf{z}\in\mathbb{R}^{10} into probabilities, and one image with true class yy has loss L=−ln⁡pyL=-\ln p_y (P4.6). With all ten probabilities equal to 110\frac1{10}, L=ln⁡10=2.303L=\ln10=2.303.

Accuracy from the confusion matrix. With MijM_{ij} the number of test images of class ii predicted as class jj: accuracy =∑iMii/∑ijMij=\sum_iM_{ii}/\sum_{ij}M_{ij}; the accuracy of class ii (its recall) is Mii/∑jMijM_{ii}/\sum_jM_{ij}; the share of correct answers among the images predicted as class jj (its precision) is Mjj/∑iMijM_{jj}/\sum_iM_{ij}.

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

The 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 32×3232\times32 image (map 4×44\times4) or on a 64×6464\times64 image (map 8×88\times8). The flatten head needs a weight for every position of the last map, 128⋅4⋅4=2048128\cdot4\cdot4=2048 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 0.09880.0988 in one run and 0.09910.0991 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

  1. A convolution takes a (64,16,16)(64,16,16) map and has 128 output channels, a 3×33\times3 kernel, padding 1 and stride 1, and no bias (a BatchNorm follows it). What are its output shape and its number of weights?

  2. 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?

  3. The random crop and the flip are applied to the training images but not to the validation or test images. What is the reason?

  4. 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?

Exercises

  1. The input is (3,32,32)(3,32,32). A convolution with 16 kernels of size 5×55\times5, padding 2 and a bias is followed by a 2×22\times2 max pool. What are the output shapes, and how many parameters does the convolution have?
    Show answerPadding 2 with a 5×55\times5 kernel keeps the size: ⌊(32+4−5)/1⌋+1=32\lfloor(32+4-5)/1\rfloor+1=32, so (16,32,32)(16,32,32), and the pool gives (16,16,16)(16,16,16). Parameters: 5⋅5⋅3⋅16+16=1,2165\cdot5\cdot3\cdot16+16=1{,}216.
  2. Replace the global average pooling and the linear layer 128→10128\to10 of the lesson model with a flatten and a linear layer from the flattened (128,4,4)(128,4,4) map to 10. How many parameters does the new last layer have, and how many does the whole network have?
    Show answerThe flattened map has 128⋅4⋅4=2048128\cdot4\cdot4=2048 numbers, so the layer has 2048⋅10+10=20,4902048\cdot10+10=20{,}490 parameters. The total is 288,746−1,290+20,490=307,946288{,}746-1{,}290+20{,}490=307{,}946. The last layer is about 16 times bigger, and it now works only for 32×3232\times32 inputs.
  3. 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 answerIt 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.
  4. 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 answer820/991=0.827820/991=0.827, 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.

Key takeaways

  • CIFAR-10 has 60,000 colour images of 32×3232\times32 pixels in 10 mutually exclusive classes, split into 50,000 training and 10,000 test images. A batch is a float tensor of shape (N,C,H,W)(N,C,H,W); the mean and standard deviation of each colour channel come from the training split only.
  • The model is three blocks of two (convolution, BatchNorm, ReLU) layers and a max pool, with 32, 64 and 128 channels, then global average pooling and one linear layer. Padding 1 keeps the size, each pool halves it, so the shapes are (3,32,32)→(32,16,16)→(64,8,8)→(128,4,4)→128→10(3,32,32)\to(32,16,16)\to(64,8,8)\to(128,4,4)\to128\to10, and the total is 288,746 parameters.
  • An MLP on the flattened image, 3072 to 512 to 256 to 10, has 1,707,274 parameters, 5.9 times as many, yet the CNN does about 38.6 million multiply-adds per image against about 1.7 million. Fewer parameters is not less work.
  • Run the recipe checks before the long run: the first loss should be near ln⁡10=2.303\ln10=2.303 (2.354 here) and a batch of 32 images should be memorized (loss 0.0003 after 100 steps).
  • Augmentation (random crop, flip) is applied to the training images only. Read the validation curve, not the training curve, and use the test set once, at the end. Results vary with hardware and seed, so differences of a few tenths of a percent are not evidence.
Found a mistake? Tell us