Sub topic 1
Why Start from a Pretrained Model
Prerequisites
This chapter assumes basic Python, familiarity with PyTorch tensors and modules, and a high-level understanding of loss, gradient descent, and epochs. You should also know that a convolutional neural network extracts patterns from images through learned layers.
The central idea
A pretrained model is a neural network whose parameters were learned from a large, already labeled dataset. For image classification, a common starting point is a model trained on ImageNet, which contains millions of images across many categories.
Training a new image classifier from random parameters asks the network to learn everything at once:
- How to detect edges and color changes.
- How to combine edges into textures and shapes.
- How to recognize useful object parts.
- How to map those features to your categories.
A small personal dataset usually does not contain enough images for this process. The model can memorize the training images instead of learning patterns that generalize to new images.
Transfer learning reuses the representations learned by the pretrained model. Early layers often detect general visual features, such as edges, corners, textures, and simple shapes. Later layers combine those features into more task-specific patterns. Your task may use different classes, but the early visual building blocks are still useful.
Why it usually works better
A pretrained network starts near a useful solution. Optimization, the process of changing parameters to reduce the loss, has less work to do. Instead of discovering basic vision from scratch, training can focus on the differences between the original task and your task.
This gives transfer learning several practical benefits:
- It needs fewer labeled images.
- It usually reaches useful accuracy faster.
- It reduces the chance of overfitting a small dataset.
- It uses less compute than full training from random initialization.
- It often produces better results when labels are expensive to collect.
The benefit is strongest when your images share visual structure with the pretraining data. A model trained on ordinary photographs may transfer well to plants, tools, animals, or household objects. It may transfer less directly to specialized medical scans, satellite images, or low-resolution sensor data. Even then, early features can still provide a useful starting point.
What changes for your task
The pretrained model's original final layer predicts its original categories. Those categories probably do not match yours. You keep most of the network and replace its final classification head with a new layer whose output count equals your number of classes.
At first, freeze the reused layers. Freezing means preventing their parameters from changing during training. Train only the new head so it learns how to interpret the existing features. Later, if validation results justify it, unfreeze selected later layers and fine-tune them with a smaller learning rate.
import torch
from torchvision import models
num_classes = 3
model = models.resnet18(weights=models.ResNet18_Weights.DEFAULT)
for parameter in model.parameters():
parameter.requires_grad = False
model.fc = torch.nn.Linear(model.fc.in_features, num_classes)
trainable = [name for name, p in model.named_parameters() if p.requires_grad]
print(trainable)The new head starts with random parameters, while the backbone retains its learned visual knowledge. The next chapters will prepare images and labels so this distinction remains valid during training.
Exercise
Why is replacing only the final layer a reasonable first step when your dataset has three classes but the pretrained model has 1,000 output classes?
Show answer
The earlier layers extract reusable visual features, while the final layer maps those features to the original labels. Replacing it creates an output for each of your three classes without discarding the learned features.