Sub topic 1
Why start from a pretrained model
Prerequisites
This chapter assumes you know the following:
- Basic Python, including functions and loops.
- The training vocabulary of loss, gradient descent, and epochs.
- What a convolutional neural network (CNN) does with an image, at a high level.
- Some PyTorch: tensors,
nn.Module, and parameters withrequires_grad.
You need torch and torchvision installed to run the code. The first run downloads about 45 MB of weights.
The problem with a small dataset
Suppose you have 600 photos sorted into five kinds of plant disease. You want a classifier that labels new photos. A modern CNN has millions of parameters, so training one from random initialization on 600 images goes badly in a predictable way. The network memorizes the training set. It reaches high training accuracy, and its accuracy on photos it has never seen stays low. This failure is called overfitting, and a later chapter covers it in detail.
Collecting more data is the direct fix, but it is slow and expensive. Transfer learning is the usual alternative. You start from a network that already learned to see on a very large dataset, and you adapt it to your categories.
What transfer learning is
Transfer learning means reusing what a model learned on one task as the starting point for another. In image classification the standard recipe has three parts:
- Take a model pretrained on a large dataset. For torchvision's models this is ImageNet, which has about 1.28 million training images in 1,000 classes.
- Keep the part that turns an image into features. This part is the backbone.
- Replace the final layer, the classification head, with a new one that outputs your classes, then train.
Fine-tuning is the broader practice of continuing to train pretrained weights on your data. You can adjust only the new head, or the head plus some backbone layers. The later chapters cover both options.
Why the features transfer
A CNN builds its understanding in layers. Early layers respond to simple patterns such as edges, color gradients, and small textures. Middle layers combine those into corners, repeated textures, and parts of shapes. Later layers respond to larger structures that depend more on the training task, such as a wheel, a face, or a dog's ear.
The early and middle layers are general. An edge detector learned on ImageNet works equally well on leaf photos, X-rays, or product shots. The last stages are more specialized, and the final layer is fully tied to the 1,000 ImageNet labels. This gradient from general to specific explains the whole workflow:
- The early layers are almost always worth keeping unchanged.
- The final layer must be replaced, because your classes differ from ImageNet's.
- The later backbone layers sit in between. Whether to adapt them depends on how different your images are and how much data you have.
Another way to see it: a pretrained backbone is a feature extractor already tuned on over a million images. Your small dataset only has to teach a simple mapping from those features to your labels, and that is a much easier job than learning the features as well.
What you gain
The advantages over training from scratch are concrete:
| Aspect | From scratch | From pretrained weights |
|---|---|---|
| Images needed | Often tens of thousands or more | Often hundreds per class can work |
| Training time | Many epochs | Often a few epochs to a good result |
| Compute | Substantial | A single consumer GPU, or a CPU for small cases |
| Starting point | Random weights | Weights that already detect useful features |
| Overfitting risk | High on small data | Lower, especially with a frozen backbone |
The numbers in the second column are rules of thumb, not guarantees. The right amount of data depends on how hard the distinction is. Telling cats from dogs needs far fewer examples than telling two similar fungal infections apart.
A frozen backbone also reduces the number of values you train. That shrinks the space the optimizer can overfit in, and it makes each epoch cheaper because gradients are not needed for the frozen layers.
A first look in code
The snippet below loads a pretrained ResNet-18 and measures how small the head is compared with the whole model. It also prints the preprocessing the weights were trained with.
from torchvision import models
weights = models.ResNet18_Weights.DEFAULT
model = models.resnet18(weights=weights)
total = sum(p.numel() for p in model.parameters())
head = sum(p.numel() for p in model.fc.parameters())
print(f"total parameters: {total:,}")
print(f"classification head: {head:,} ({head / total:.1%} of the model)")
print("first categories:", weights.meta["categories"][:3])
print(weights.transforms())On a standard torchvision install this reports about 11.7 million parameters, of which the 1000-class head holds about 513,000, roughly 4%. The remaining 96% is the backbone, and it carries the learned visual knowledge.
Now see what the trainable part looks like once the model is adapted to five classes. This preview uses ideas that later chapters explain properly.
import torch.nn as nn
from torchvision import models
model = models.resnet18(weights=models.ResNet18_Weights.DEFAULT)
for param in model.parameters():
param.requires_grad = False
model.fc = nn.Linear(model.fc.in_features, 5)
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f"trainable parameters: {trainable:,}")This prints trainable parameters: 2,565, which is 512 inputs times 5 outputs plus 5 biases. Training roughly two thousand five hundred numbers on 600 images is a well-posed problem. Training 11.7 million numbers on the same images is not.
Pretrained weights come with conditions
The pretrained model was trained on images processed in a specific way. It expects a fixed input size, pixel values scaled to the 0 to 1 range, and per-channel normalization with the ImageNet mean and standard deviation. If your pipeline feeds it differently scaled or normalized images, the features it computes are distorted and results suffer, even though no error is raised. The weights.transforms() output in the snippet above shows the exact recipe. The preprocessing chapter returns to this point.
The weights also come with a license and a data history. Check the terms of the weights you use if you plan to ship a product.
When transfer learning helps less
Transfer learning is the right default, but it is not magic. Three situations weaken it.
- Very different image domains. ImageNet is mostly everyday photographs. Medical scans, satellite imagery, and microscope images look different, and the late-layer features transfer less well. Pretraining still usually beats random initialization, because edges and textures are universal. You will often need to unfreeze more layers and use more data.
- Very large datasets. With millions of in-domain images, training from scratch can match or exceed fine-tuning. Pretraining then mainly saves time.
- Unusual inputs. Pretrained models expect three-channel color images at a fixed scale. Single-channel or multispectral data needs adaptation of the first layer, and some of the pretrained value is lost.
A related limit is inherited bias. The backbone carries the strengths and gaps of its pretraining data. If a feature is rare in ImageNet, the model may represent it poorly, and your small dataset may not be enough to fix that.
Common errors at this stage
- Expecting the 1000-class head to work. Without replacing the head, the model predicts ImageNet labels. It cannot output your classes.
- Skipping the matching preprocessing. Training with different normalization than the weights expect often lowers accuracy without any warning.
- Assuming pretrained means done. The new head starts with random weights. It must be trained, and its quality must be measured on held-out images.
- Judging success on training images. A high training score says little with a small dataset. Always hold images back for validation.
The workflow ahead
Every later chapter fills in one step of the same pipeline: organize and split the images, preprocess and augment them, load them in batches, choose and adapt a pretrained model, train the head with the backbone frozen, fine-tune later layers at a lower learning rate, evaluate honestly, diagnose problems, and save the model for inference. Keeping the general-to-specific picture of the layers in mind will make each decision easier to justify.
Exercise
A ResNet-18 has about 11.7 million parameters. You replace its head with a layer for 8 classes and freeze the whole backbone. How many parameters are trainable, and why is this setup less prone to overfitting on 400 images than training the whole network from random weights?
Show answer
The new head is a linear layer from 512 features to 8 outputs: 512 x 8 weights plus 8 biases, which is 4,104 trainable parameters. Only these are updated, so the optimizer has far fewer values to adjust than the roughly 11.7 million in the full network. Training everything from random weights on 400 images lets the network memorize the images. With a frozen backbone, the features were learned from over a million ImageNet images, and the head only learns a small mapping from those features to your classes.
Exercise
Your task is classifying chest X-ray images, which look very different from ImageNet photos. Should you still start from pretrained weights? What would you expect to do differently from the plant-photo case?
Show answer
Yes, usually. Early layers detect edges and textures that are useful in any image, so pretrained weights typically beat random initialization even across domains. Because late-layer features transfer less well, you would expect to unfreeze more of the backbone, fine-tune with a low learning rate, and use more data than in a case close to ImageNet. You would also need to handle the input format, for example converting single-channel scans to three channels or adapting the first layer.