CNNs and Transfer Learning
The network you built in lesson 3 flattens each image into one long row of pixels. That throws away a useful fact: pixels that sit next to each other belong together. A convolutional neural network (CNN) keeps that structure, and it usually does better on images with fewer weights.
In the second half of this lesson you will do something even more useful in practice. You will take a model that was already trained on over a million photos, and teach it a new task in a few minutes. This is called transfer learning.
Keep your notebook from lessons 3 and 4 open. The code reuses train_loader, val_loader, test_loader, loss_fn, device, train_one_epoch and evaluate.
What You'll Learn
- What a convolution layer does and why it suits images
- How to build a small CNN with
nn.Conv2dandnn.MaxPool2d - What transfer learning is and when to use it
- How to load a pretrained ResNet18 from torchvision
- How to freeze its layers and train only a new final layer
How a Convolution Works
A convolution layer slides a small window, usually 3 by 3 pixels, across the image. At each spot it multiplies the pixels by a small grid of learned weights, called a filter, and adds them up. The result is a new image, called a feature map, that lights up wherever the filter's pattern appears.
- Early filters learn simple patterns: edges, corners, light and dark areas.
- Later filters combine those into bigger shapes: a collar, a sole, a strap.
Two things make this a good fit for pictures:
- The same filter is used everywhere. A filter that finds a vertical edge finds it anywhere in the image. So a CNN needs far fewer weights than a fully connected layer.
- Neighbors stay neighbors. The layer looks at small patches, so it keeps the 2D layout of the image.
A max pooling layer then shrinks each feature map, usually by half, by keeping only the largest value in each 2 by 2 block. This keeps the strongest signals and makes the next layers cheaper.
For a no-code tour of how computers see images, see Computer Vision Basics.
Part 1: A Small CNN for Fashion-MNIST
import torch
from torch import nn
class FashionCNN(nn.Module):
def __init__(self):
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(1, 32, kernel_size=3, padding=1), # [N, 1, 28, 28] -> [N, 32, 28, 28]
nn.ReLU(),
nn.MaxPool2d(2), # -> [N, 32, 14, 14]
nn.Conv2d(32, 64, kernel_size=3, padding=1), # -> [N, 64, 14, 14]
nn.ReLU(),
nn.MaxPool2d(2), # -> [N, 64, 7, 7]
)
self.classifier = nn.Sequential(
nn.Flatten(),
nn.Linear(64 * 7 * 7, 128),
nn.ReLU(),
nn.Dropout(0.3),
nn.Linear(128, 10),
)
def forward(self, x):
return self.classifier(self.features(x))
cnn = FashionCNN().to(device)
print(sum(p.numel() for p in cnn.parameters()), "parameters")
The comments show how the shape changes at each step. nn.Conv2d(1, 32, ...) means "1 input channel (grayscale), 32 filters". padding=1 adds a border of zeros so the image keeps its size after a 3 by 3 filter.
Train it with the same helper functions as before. Only the model changes. The optimizer gets its own name, cnn_optimizer, because lesson 6 saves it:
cnn_optimizer = torch.optim.Adam(cnn.parameters(), lr=1e-3)
for epoch in range(5):
train_loss = train_one_epoch(cnn, train_loader, loss_fn, cnn_optimizer)
val_loss, val_acc = evaluate(cnn, val_loader, loss_fn)
print(f"epoch {epoch+1} train {train_loss:.3f} val {val_loss:.3f} val acc {val_acc:.1%}")
test_loss, test_acc = evaluate(cnn, test_loader, loss_fn)
print(f"CNN test accuracy: {test_acc:.1%}")
Expect about 90% to 92% test accuracy, a few points better than the fully connected network from lesson 3. That gap is the value of keeping the image's 2D structure.
Part 2: Transfer Learning
Training a large image model from scratch takes millions of labeled images and a lot of GPU time. Most people never do it. Instead they start from a model that someone else already trained, and adjust it.
The idea works because the early layers of any image model learn general patterns, such as edges, textures and shapes. Those are useful for almost any picture. Only the last layer is specific to the original task. So you keep the trained layers and replace the last one.
| Approach | Data you need | Training time | Typical use |
|---|---|---|---|
| Train from scratch | A lot | Hours to weeks | New kinds of data, research |
| Transfer learning | A few hundred to a few thousand images | Minutes | Most real projects |
Load a Pretrained ResNet18
ResNet18 is a well-known CNN with 18 layers, trained on ImageNet, a dataset of over a million photos in 1,000 classes. torchvision can download it with its trained weights:
from torchvision import models
weights = models.ResNet18_Weights.DEFAULT
resnet = models.resnet18(weights=weights)
preprocess = weights.transforms()
print(preprocess)
print(resnet.fc) # Linear(in_features=512, out_features=1000, bias=True)
As of November 2026, this weights= form is the documented way. Older tutorials use pretrained=True, which is deprecated and prints a warning.
weights.transforms() gives you the exact preprocessing the model was trained with: resize, crop to 224 by 224 pixels, and adjust the colors the same way. The docs stress that using the right preprocessing is critical. A pretrained model fed differently prepared images gives poor results.
A New Task: CIFAR-10
ResNet18 expects color photos, so this part uses CIFAR-10: small color photos of 10 things such as airplanes, cats, ships and trucks. To keep training fast on a free GPU, take 10,000 training images and 2,000 test images:
from torch.utils.data import DataLoader, Subset
from torchvision import datasets
cifar_train = datasets.CIFAR10(root="data", train=True, download=True, transform=preprocess)
cifar_test = datasets.CIFAR10(root="data", train=False, download=True, transform=preprocess)
small_train = Subset(cifar_train, range(10_000))
small_test = Subset(cifar_test, range(2_000))
cifar_train_loader = DataLoader(small_train, batch_size=64, shuffle=True)
cifar_test_loader = DataLoader(small_test, batch_size=128)
print(cifar_train.classes)
Freeze the Body, Replace the Head
Freezing a layer means its weights will not change during training. You freeze all of ResNet18, then swap its last layer (fc) for a new one with 10 outputs. New layers are not frozen, so only this one learns:
for param in resnet.parameters():
param.requires_grad = False # freeze everything
resnet.fc = nn.Linear(resnet.fc.in_features, 10) # new head, trainable
resnet = resnet.to(device)
trainable = sum(p.numel() for p in resnet.parameters() if p.requires_grad)
total = sum(p.numel() for p in resnet.parameters())
print(f"Training {trainable:,} of {total:,} parameters")
You are training about 5,000 numbers out of about 11 million. That is why it is fast and why it works with little data.
Train Only the New Head
Give the optimizer only the new layer's parameters:
optimizer = torch.optim.Adam(resnet.fc.parameters(), lr=1e-3)
for epoch in range(3):
train_loss = train_one_epoch(resnet, cifar_train_loader, loss_fn, optimizer)
test_loss, test_acc = evaluate(resnet, cifar_test_loader, loss_fn)
print(f"epoch {epoch+1} train {train_loss:.3f} test acc {test_acc:.1%}")
On a free Colab GPU each epoch takes a minute or two. In our test run, accuracy reached about 74% after 3 epochs, from only 10,000 images and one trained layer of about 5,000 numbers. Random guessing on 10 classes would give 10%.
Going Further: Fine-Tuning
Once the new head works, you can unfreeze the last block of ResNet18 and train it too, with a smaller learning rate so you do not wreck what it already learned:
for param in resnet.layer4.parameters():
param.requires_grad = True
optimizer = torch.optim.Adam([
{"params": resnet.layer4.parameters(), "lr": 1e-4},
{"params": resnet.fc.parameters(), "lr": 1e-3},
])
Then train for a few more epochs with the same loop. This lets the model adjust its last block of features to the new photos, and usually adds several points of accuracy. It takes longer per epoch, so try it once the frozen version works.
Data Augmentation
To help with overfitting on small datasets, you can add random changes to the training images, such as a horizontal flip. Each epoch the model then sees slightly different versions of the same photos. With the v2 transforms it looks like this:
from torchvision.transforms import v2
train_transform = v2.Compose([
v2.RandomHorizontalFlip(),
preprocess,
])
Use augmentation on training data only. Validation and test data should use the plain preprocess.
Key Takeaways
- A CNN slides small learned filters across the image, so it keeps the 2D layout and needs fewer weights.
nn.Conv2dfinds patterns,nn.MaxPool2dshrinks feature maps, and a smallLinearhead makes the final call.- Transfer learning reuses a model trained on a huge dataset. It needs little data and little time.
- Load pretrained models with
weights=...and always use the matchingweights.transforms(). - Freeze the pretrained layers, replace the last layer, and train only the new one first.
Quiz
Up next · Lesson 6 of 6
Save, Load and Use Your Model
5 min read
5 of 6 lessons done

Ask Byte about this lesson
A private chat about this lesson. Byte has read the whole lesson, answers in seconds, and shows the section each answer comes from. Ask follow-ups in any language.
Questions & Answers
Public questions about this lesson. The AI Tutor answers right away in your language, the FreeAcademy team checks answers, and every learner can read them.

