You have 500 photos of your own, labelled with 10 kinds of object, and you want a classifier. A ResNet-18 has about 11 million weights. Trained from random weights on 500 images it can memorize them and still fail on a new photo. Yet someone has already trained that same network on about 1.28 million photos in 1000 classes (the ImageNet-1k training set) and put the weights online. Can you use their work instead of starting from nothing?
Yes, and it is a very common way to build an image model. This lesson shows how it works, the choices you make, and the traps: wrong preprocessing, BatchNorm, learning rates and overfitting a small set.
Why features transfer
P5.8 shows what a trained CNN learns. The first layers respond to edges, colour blobs and simple textures. Middle layers combine them into corners, patterns and parts. The last layers respond to things that help with the training labels, such as a particular dog breed. Edges and textures are useful for almost any photo task. A detector of “Siberian husky fur” is useful for a few.
So a network trained on a large, varied dataset is a feature extractor you can reuse. The early layers need the least change, the middle layers are often reusable but depend on each other (Yosinski and co-authors found this co-adaptation), and the last layers are the ones to replace or retrain. Yosinski and co-authors measured this on ImageNet in 2014: features from the first layers were general, features from the last layers became more specific to the original task, transferred features still beat random ones even when the new task was less similar, and fine-tuning after the transfer helped.
An analogy: someone who can read English already knows letter shapes, which they reuse to learn French, so they only have to learn the new words. The analogy breaks in one place: network features are not neatly named. Which layers are “general enough” for your images is something you test.
The three options
Call the pretrained part the backbone and the final classification layer the head. You can use them in three ways.
- Feature extraction. Freeze the whole backbone (its weights never change) and train a new head. The backbone turns each image into a fixed feature vector. With a linear head this is also called a linear probe.
- Fine-tuning. Start from the pretrained weights and let some or all of the backbone train too, with a small learning rate. You can also fine-tune in stages: head first, then unfreeze later blocks.
- Training from scratch. Ignore the pretrained weights and start from random ones (P4.12).
Feature extraction trains the fewest numbers, so it is the cheapest and the least likely to overfit a small set. It cannot adapt the features, so if the frozen features do not fit your images it hits a ceiling. Fine-tuning can adapt them, at the price of more compute and more risk of overfitting and of damaging the pretrained weights. Scratch needs the most data.
Scratch makes sense with a very large dataset of your own, inputs unlike photos (for example a different number of channels), or a tiny custom architecture. Otherwise try a pretrained start first.
Replacing the head
The pretrained model ends in a linear layer with one output per ImageNet class. Your task has its own classes, so you build a new linear layer with the same input width and your number of outputs. For a torchvision ResNet-18, the features before the head are a vector of 512 numbers (P5.6 showed the global average pooling that makes it), and the old head maps .
import torch
import torch.nn as nn
from torchvision.models import resnet18, ResNet18_Weights
weights = ResNet18_Weights.IMAGENET1K_V1
model = resnet18(weights=weights)
print(model.fc.in_features, model.fc.out_features)
model.fc = nn.Linear(model.fc.in_features, 10) # new head
x = torch.zeros(4, 3, 224, 224) # (N, C, H, W)
n = sum(p.numel() for p in model.fc.parameters())
print(model(x).shape, n)
512 1000
torch.Size([4, 10]) 5130
The new head has parameters, against for the old one. Its weights are random (P4.12), because nothing pretrained knows your classes. Your labels are to in your own order, not ImageNet’s order.
The head is not always called fc. In torchvision 0.24.1: ResNet-18 model.fc, VGG-16 model.classifier[6], MobileNetV3-small model.classifier[3], EfficientNet-B0 model.classifier[1], DenseNet-121 model.classifier, ConvNeXt-tiny model.classifier[2]. Print the model, read the last lines, and take the input width from the old layer’s in_features. P5.9 helps you choose a backbone by its parameters, multiply-adds and speed.
Use the preprocessing that goes with the weights
The weights were trained on images that were resized, cropped, scaled to to and normalized per channel with a fixed mean and standard deviation (P5.1). Your images must go through the same steps, or the first layers see inputs on a scale they were never trained on. torchvision stores the recipe with the weights:
print(weights.transforms())
ImageClassification(
crop_size=[224]
resize_size=[256]
mean=[0.485, 0.456, 0.406]
std=[0.229, 0.224, 0.225]
interpolation=InterpolationMode.BILINEAR
)
The sizes differ per model (EfficientNet-B1 crops to 240, Inception V3 resizes to 342 and crops to 299, same mean and standard deviation), so take the transform from the weights you use. The name DEFAULT can point to different weights in different library versions, so name them explicitly for repeatable results. A greyscale image needs three channels: convert it to RGB.
In training, put augmentation (P4.18, P5.7: random crop, flip) before the normalization step and apply it to training images only. On a small set it gives the model more different views.
See it: freeze blocks and watch the cost
A torchvision ResNet-18 has a stem and four stages (layer1 to layer4), then the head. Slide the number of frozen blocks from 0 (fine-tune everything) to 5 (feature extraction).
Things to try:
- Press Feature extraction. Only 5,130 of 11,181,642 parameters train (0.05%), and the backward pass has almost nothing to do: it stops at the head. The forward pass still runs through every block, which is why a whole step still costs about a third of full fine-tuning in this model.
- Press Train layer4 and the head. The trainable share jumps to 75% because
layer4holds 8.4 million of the 11.2 million weights, but the backward pass is only about 12% of the full one, because the gradient stops at the start oflayer4. - Set the dataset to small and different. The rule of thumb suggests freezing 3 blocks. Slide to 0 and read the warning.
The cost model is rough: a block the gradient passes through costs about twice its forward cost (one product for the weight gradient, one for the gradient sent back), the first trained block about once. Frozen blocks before it need no backward pass and store no activations, which is why freezing saves time and memory.
Which setting? A rule of thumb
Two things matter most: how much data you have and how close it is to the pretraining data. A common rule of thumb, which the widget uses:
- Small data, similar images: freeze everything and train the head (feature extraction). A deeper change would overfit.
- Small data, different images: freeze the early blocks, which are generic, and consider training some later blocks with a small learning rate. A head on frozen features is the safe baseline to compare against.
- More data (medium or large): unfreeze more blocks as the data grows, starting with the later ones. With similar images keep the early blocks frozen longer, and with different images unfreeze sooner.
- Large data, different images: fine-tune everything, and consider scratch if the data is very large.
The widget turns this into 5, 3, 4, 2, 1 and 0 frozen blocks for its six cells. It is a heuristic, and “small”, “large” and “similar” are fuzzy: roughly, 100 to 1,000 images is small, a few thousand is medium, and tens of thousands or more is large. The rule says where to start, not what wins: compare its setting and a neighbour on a validation set (P4.22).
Fine-tuning: learning rates
A new head is random, so its first gradients are large and noisy. A pretrained backbone is already good, so large updates can only damage it. The usual practice follows from this:
- Use a smaller learning rate for pretrained layers than for the new head. A factor of 10 to 100 smaller is a common starting point.
- With discriminative learning rates, give earlier layers a smaller rate than later ones: they are the most general and need the least change.
- Optionally train the head first, then unfreeze the backbone, so the random head has settled before it sends gradients into the pretrained weights.
- Use the schedules of P4.14 and a validation set to stop early (P4.17).
In PyTorch the rates are set with parameter groups, and frozen parameters get no gradient:
for p in model.parameters(): # freeze all,
p.requires_grad = False
for p in model.fc.parameters(): # train the head
p.requires_grad = True
for p in model.layer4.parameters(): # and layer4
p.requires_grad = True
print(sum(p.numel() for p in model.parameters()
if p.requires_grad)) # 8398858
opt = torch.optim.SGD([
{"params": model.fc.parameters(), "lr": 1e-2},
{"params": model.layer4.parameters(), "lr": 3e-4},
], momentum=0.9)
BatchNorm: a trap
A BatchNorm layer (P4.19) has two kinds of numbers. Its scale and shift are parameters, trained by gradient descent. Its running mean and variance are not parameters: in train mode they are updated from every batch in the forward pass, and in eval mode they are fixed and used for normalization.
So requires_grad = False is not enough to freeze a BatchNorm layer. Freeze a ResNet-18’s parameters and call model.train(), and the running statistics still move to match your new data:
train: change 0.2918, batches 1
eval : change 0.0000, batches 0
Those lines come from feeding one batch of 8 random 224-pixel images (values around 1, spread 0.5) to a pretrained ResNet-18 with all parameters frozen, and reading the first BatchNorm layer’s running mean. The size of the change depends on the batch; what matters is that it is not zero. To freeze a part properly, put it in eval mode too (model.eval() on the part, and call it again after every model.train()).
For fine-tuning there is a second reason to care: with a small batch (say 8 to 32 images) the batch statistics are noisy, and some people keep BatchNorm in eval mode even for layers whose other weights train. Whether it helps depends on the data, so it is another setting to compare on a validation set.
Overfitting, forgetting and small data
A ResNet-18 has 11 million trainable numbers and your set has 500 images. The more of them you train, the easier it is to memorize the training set (P4.17, P3.A5). Feature extraction, small learning rates, augmentation, early stopping on a validation set and a smaller backbone all fight this. Choose on the validation set and look at the test set once.
Catastrophic forgetting is the other side: when you fine-tune with a large learning rate, the weights move far from the pretrained ones, and the model loses much of what it knew, so it is worse at the old task and often a worse starting point for the new one. You do not need the old task to see it happen: measure how far the weights moved, block by block, as the relative change (the Math tab writes it out). The experiment below does.
A real experiment: scratch, frozen and fine-tuned
Words are cheap, so here is a run. The Colab notebook for this lesson (notebooks/P5.10-transfer-learning-and-fine-tuning.ipynb) trains a torchvision ResNet-18 on small subsets of CIFAR-10 (the 60,000-image set of 32 by 32 colour pictures in 10 classes from P5.7), in seven settings. Each setting was run with 3 seeds, and a seed changes which training images are drawn, the random head and the batch order. The setup, exactly:
- Data: 100 and 500 training images (10 and 50 per class) from the CIFAR-10 training set, the same subset for every setting of a seed; the same 2,000 test images (200 per class) for every run, read once at the end. No augmentation.
- Images: resized to to keep it fast, with the ImageNet mean and standard deviation. The weights were trained on larger images.
- Training: 20 epochs, batch size 32, SGD with momentum 0.9, cosine schedule. Learning rates were chosen once, on a validation split of 100 training images (never on the test set), and reused for every setting and both sizes; the settings were not tuned separately. Values: scratch 0.01; frozen backbone, head 0.01; fine-tuning, backbone 0.0003 and head 0.01.
- Settings: scratch; feature extraction; fine-tune
layer4and the head; fine-tune everything; and three variants that test traps above: one large rate (0.01) for the backbone too, BatchNorm kept in eval mode, and feature extraction without the mean and standard deviation. - Machine: CPU only, PyTorch 2.9.1; about 27 minutes on a shared 16-core machine.
What the numbers show, for this setup only:
- Pretraining helped a lot. At 500 images scratch reached 34.5% and feature extraction 73.2% (spreads 0.1 and 1.2 points); at 100 images 22.6% and 59.7%. A longer, tuned scratch run could do better.
- More trainable layers did not mean more accuracy. Feature extraction beat fine-tuning
layer4(70.3%) and everything (68.9%) at 500 images, and in the same order at 100 (59.7%, 54.2%, 49.8%). - Among the fine-tuning variants, BatchNorm mode made the biggest difference. The only difference between “fine-tune all” (68.9% at 500 images) and the BatchNorm-eval variant (79.0%) is that the second freezes the BatchNorm statistics. It was the best setting at 500 images (spreads 0.8 and 0.5). At 100 images (60.4%) it was within the spread of feature extraction (59.7%). We did not test why. Batches of 32 images are small for estimating statistics, and these images are blown up from 32 pixels, which may make their statistics differ from the pretraining images.
- One large rate hurt. At the head’s rate for everything, 64.8% at 500 images and 32.2% at 100, against 68.9% and 49.8%. The relative change of each block averaged 0.10 to 0.18 over the 3 seeds, against 0.004 to 0.008 with the small rate (500 images).
- The wrong preprocessing cost accuracy. Without the mean and standard deviation, feature extraction scored 58.5% instead of 73.2% at 500 images, and 45.7% instead of 59.7% at 100, with the same frozen weights.
- Freezing was faster. Mean time per run at 500 images: 19.9 s for feature extraction, 37.5 s for
layer4, 78.0 s for everything. The measured shares were 26%, 48% and 100%, against 34%, 42% and 100% from the widget’s cost model, so the rough model is within about 10 points and gets the order right.
This does not contradict the rule of thumb: it is a starting point, and here the frozen baseline was already strong. It shows why the baseline and one neighbour setting should be compared on a validation set.
The notebook prints this summary for the 500-image runs (shortened):
--- 500 training images ---
scratch 34.5 +- 0.1 %
feature 73.2 +- 1.2 %
layer4 70.3 +- 1.1 %
all 68.9 +- 0.8 %
all_hilr 64.8 +- 1.3 %
allbneval 79.0 +- 0.5 %
feature_noscale 58.5 +- 0.9 %
These are 3 seeds on one dataset, one network and one image size. Another dataset, resolution, augmentation or batch size could change the order of the middle settings, and 3 seeds cannot show small differences. What carries over is the method: change one thing at a time, compare on held-out data, report the spread.
Licences and inherited bias
Pretrained weights are not free of strings. The code, the weights and the training data can have three different licences, and a licence for one does not cover the others. Read the model card or the weights page (P2.8) for what you may do with the weights, for example in a commercial product.
A pretrained model also inherits what its training data contains and misses. If the data had few photos of some places, people or objects, or labels that reflect the views of the people who made them, the features and the head you build on them carry that along. So test the model on your own kind of images, split by the groups that matter to your users, before you trust it.
Three ways to see it
Intuition
Think of hiring someone with related experience. A short briefing is feature extraction, some gentle retraining is fine-tuning, and for a job unlike anything they did you may as well train a beginner (scratch). The picture breaks where a person can say which skills carry over, while for a network you find out by testing, and a person has no hidden state like BatchNorm statistics that drifts to the new workplace on its own.
Math
Write the backbone as and the head as , with loss . The gradients are
With the backbone frozen, only the head gradients are computed, and the backbone gradient, which needs the whole backward pass through the backbone, is skipped. If the features are computed once and stored, training the head is logistic regression on fixed vectors (the multi-class version of P3.A7), a convex problem, and each epoch costs only the head.
Fine-tuning with a learning rate per group updates . With a small the weights stay near , which is what a pretrained start is for. The distance moved is measured by the relative drift
Cost. One training step is a forward pass over every block plus a backward pass back to the first trained block. A convolution’s backward pass needs about two products for each of the forward pass (weight gradient and input gradient), which gives the rough model of the widget. For the ResNet-18 at the forward pass is billion multiply-adds, and with the first four blocks frozen the step costs about of full fine-tuning.
Head size. A linear head with inputs and classes has parameters.
Code
Training with a frozen backbone and a new head in PyTorch, on a DataLoader (P2.7) of images already passed through weights.transforms(). Shapes are .
model = resnet18(weights=weights)
model.fc = nn.Linear(512, 10)
for name, p in model.named_parameters():
p.requires_grad = name.startswith("fc.")
opt = torch.optim.SGD(
[p for p in model.parameters() if p.requires_grad],
lr=1e-2, momentum=0.9)
for epoch in range(epochs):
model.eval() # frozen BatchNorm statistics
model.fc.train() # (a linear layer: same either way)
for x, y in loader:
loss = nn.functional.cross_entropy(model(x), y)
opt.zero_grad()
loss.backward()
opt.step()To fine-tune the last stage as well, set requires_grad = True for layer4, add it to the optimizer with a smaller rate as in the parameter-group example above, and call model.layer4.train() after model.eval().
Try it in Python
The first cell counts the trainable parameters of a ResNet-18 from its layer shapes, for each number of frozen blocks.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The totals are 11,181,642 and 11,689,512 (torchvision lists 11,689,512 for the pretrained model), and the last line says 5,130 trainable and 0.05% with five blocks frozen.
Common mistakes
Quiz
Check your understanding
You have 600 labelled photos of plant leaves taken with an ordinary camera, and a ResNet-18 pretrained on ImageNet. What is the best first experiment?
Frozen features with a new head train few numbers, so a small set is unlikely to overfit them, and photos are close to the pretraining data. Training from random weights throws the features away, and features transfer to classes that were not in the pretraining set. Training everything at the scratch rate risks damaging the weights, and more trainable weights make memorizing a small set easier. Freezing the head and training the backbone reverses the roles: the new head is the part that must be trained.
All parameters of a pretrained ResNet-18 have
requires_grad = False, and you callmodel.train()before feeding a batch. What happens to the BatchNorm running statistics?In train mode a BatchNorm layer updates its running mean and variance from every batch in the forward pass, and that does not use gradients, so freezing the parameters does not stop it. The option saying they stay unchanged confuses the parameters with the running statistics, which are buffers. Train mode does not reset anything. The option about layers after the first trained one ties the update to gradients, which it does not use.
A torchvision ResNet-18 ends in
Linear(512, 1000). You replace it with a head for 7 classes. How many parameters does the new head have?The count is . The count without biases ignores that
nn.Linearhas a bias by default. Keeping the old weights is not what replacing a layer does: the new layer is smaller and random. Padding to a power of two does not happen in a linear layer.You feed a pretrained ImageNet model pixel values scaled to to but without subtracting the mean and dividing by the standard deviation it was trained with. What is the most likely result?
Shapes are the same, so nothing raises an error, but the first layers were tuned to normalized inputs, so their outputs shift. Normalization does not change the number of channels. In eval mode BatchNorm uses fixed running statistics from training, so it does not remove a changed input scale. Nothing makes unnormalized inputs better for a model trained on normalized ones.
You fine-tune all layers of a pretrained network with a new random head. Which learning rate setup is the usual starting point?
Pretrained layers start from useful values, so small steps keep them useful, and the random head can take larger steps. Optimizers accept parameter groups with their own rates, so one rate is not forced. The number of parameters is not a reason for a larger step. Giving the new head the smaller rate gets the reason the wrong way round: it is the part that has everything to learn.
Exercises
- A ResNet-18 with a 10-class head has its stem,
layer1,layer2andlayer3frozen. How many parameters train, and what share of the total is that?Show answer
Onlylayer4and the head train: , which is . It matches the widget at 4 frozen blocks and the second PyTorch check above. - A MobileNetV3-small has its head at
classifier[3], aLinear(1024, 1000). You need 20 classes. Write the replacement line and count the new head’s parameters.Show answer
Assign a newnn.Lineartomodel.classifier[3]with input width 1024 (read from the old layer’sin_features) and 20 outputs. It has parameters. - You have 40,000 labelled images of a kind unlike ordinary photos (single-channel sensor readings), and a ResNet-18 pretrained on ImageNet. Which setting would you try first, and why would you not rely on the rule of thumb alone?
Show answer
The data is large and different, so the rule of thumb points to fine-tuning everything (the first layer must be changed to accept one channel, or the channel repeated three times), with a smaller learning rate for the pretrained layers, and to training from scratch as the comparison. The rule is a heuristic: compare these on a validation set before choosing.
Next: P5.11 moves from “what is in this image” to “where are the objects”, and P5.12 and P5.13 build detection and segmentation models on the same pretrained backbones.