Sub topic 7
Freezing the Backbone and Unfreezing Later Layers
Assume you know Python, PyTorch modules, loss, gradient descent, and epochs. You should also understand that a convolutional neural network learns image features in layers.
Why freeze layers first?
A pretrained model has already learned useful visual patterns from a large dataset. Early layers often detect general features such as edges, colors, and textures. Later layers combine those features into shapes and object parts.
Your dataset may contain only a few hundred or thousand images. If you update every layer immediately, the model can quickly memorize your examples. This is called overfitting. The pretrained features can also be damaged by large updates.
Freezing a layer means setting its parameters so that gradient descent does not change them. A common transfer-learning strategy is:
- Freeze the pretrained backbone.
- Train the new classification head.
- Unfreeze the later backbone layers.
- Fine-tune them with a smaller learning rate.
Stage 1: train only the new head
First, freeze every parameter in the pretrained model. Then replace its final layer. The replacement layer is newly created, so its parameters remain trainable.
import torch
import torch.nn as nn
from torchvision import models
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
num_classes = 3
model = models.resnet18(weights=models.ResNet18_Weights.DEFAULT)
for parameter in model.parameters():
parameter.requires_grad = False
model.fc = nn.Linear(model.fc.in_features, num_classes)
model = model.to(device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(model.fc.parameters(), lr=1e-3)The requires_grad flag controls whether PyTorch calculates gradients for a parameter. The optimizer also receives only model.fc.parameters(). This prevents frozen parameters from being updated.
Train the head until validation performance stops improving or reaches a useful level. The head learns how to map the existing visual features to your categories.
Stage 2: fine-tune later layers
The last residual stage of ResNet contains more task-specific features than the early stages. Unfreeze it after the head has learned a reasonable starting point.
for parameter in model.layer4.parameters():
parameter.requires_grad = True
optimizer = torch.optim.AdamW(
[
{"params": model.layer4.parameters(), "lr": 1e-4},
{"params": model.fc.parameters(), "lr": 1e-3},
],
weight_decay=1e-2,
)The head uses a learning rate of 1e-3. The newly unfrozen layer uses 1e-4, which is ten times smaller. The head starts from random weights and needs larger updates. The backbone already contains useful features and needs gentle adjustments.
You can unfreeze more layers if the new images differ greatly from the pretraining images. For a small dataset, unfreezing the entire model usually increases overfitting risk.
A BatchNorm warning
Some models contain Batch Normalization layers. These layers maintain running statistics during training. Setting requires_grad = False stops weight gradients, but it does not always stop those statistics from changing when you call model.train().
For a very small dataset, changing these statistics can hurt validation results. Consider keeping frozen BatchNorm layers in evaluation mode, or compare both approaches on a validation set.
Choosing when to unfreeze
Compare training and validation metrics after each stage.
| Observation | Likely action |
|---|---|
| Head and validation accuracy are both low | Unfreeze later layers or improve the data |
| Training accuracy rises but validation accuracy stalls | Use stronger augmentation or stop earlier |
| Validation improves after unfreezing | Keep selective fine-tuning |
| Validation becomes worse immediately | Lower the backbone learning rate or re-freeze layers |
The best number of unfrozen layers depends on dataset size, image similarity, and label quality. Make one change at a time so you can identify its effect.
Exercise
Why should the backbone usually use a lower learning rate than the new classification head?
Show answer
The backbone already contains useful features, so small updates can adapt them without overwriting what the model learned during pretraining.