Deep Learning · Transfer Learning
Learn how to reuse a pretrained model, replace its old task-specific head, freeze or unfreeze layers deliberately, and fine-tune with learning rates that protect useful representations.
Why Reuse a Model?
A factory may have only 800 labelled product images—far too few to teach a large vision model every useful edge, texture and shape from scratch. A model pretrained on a much larger image collection already contains weights that respond to many visual structures. Transfer learning asks whether those representations can help the factory task.
The pretrained model is the source model; your new labelled problem is the target task. The reusable part is usually called a backbone or encoder. Its old classifier head is removed because its labels do not match yours.
Transfer learning keeps useful representations and replaces the old decision
source pretraining
many general images
old labels: 1,000 classes
pretrained backbone
block 1
edges
block 2
textures
block 3
parts
block 4
shapes
reusable weights
new task head
normal / scratch / crack
target factory data
Feature Extraction and Fine-Tuning Are Different
Train from scratch
Initialize backbone and head randomly; update everything.
Useful comparison when target data is large or unlike pretraining.
Fixed feature extractor
Freeze the backbone; train only the new head.
Fast, memory-efficient baseline for small similar datasets.
Fine-tuning
Start from pretrained weights; update some or all backbone layers.
Adapts features, but increases overfitting and forgetting risk.
Freezing means a parameter is excluded from gradient updates. It does not delete the parameter, and it does not necessarily control every layer's train/evaluation behavior. Dropout and normalization state still require deliberate mode handling.
Use a Staged Training Plan
First train the new random head while the backbone stays stable. Once the head maps pretrained features to target labels reasonably, unfreeze later blocks and continue at a smaller rate. This avoids sending large, noisy gradients from an untrained head through useful pretrained layers on the first update.
Fine-tuning is a controlled sequence, not one switch
Stage 1 · establish baseline
backbone: frozen
head: train
Learn the new head without disturbing pretrained features
Stage 2 · partial fine-tuning
backbone: early blocks frozen; later blocks train
head: train
Adapt higher-level features with a smaller learning rate
Stage 3 · optional full fine-tuning
backbone: all train, often at very small rates
head: train
Attempt deeper domain adaptation only if validation supports it
Target size and domain similarity guide the first experiment
Similar data · few labels
Freeze most layers; train a small head
Similar data · many labels
Fine-tune later blocks, then compare full fine-tuning
Different data · few labels
Transfer may be weak; use augmentation/self-supervision and cautious fine-tuning
Different data · many labels
Compare pretrained initialization with training from scratch
Why the Backbone Usually Needs a Smaller Learning Rate
Every trainable weight still follows the optimizer's update rule. For plain SGD, wnew=w−ηg. The gradient g is calculated by backpropagation from the current batch; learning rate η is chosen by the developer. Multiplying them gives the update size, and subtracting moves the weight in the direction that locally reduces loss. Different parameter groups can use different η values.
Same gradient, different movement
For comparison, manually use the same illustrative gradient g=0.2 for one pretrained backbone weight and one new head weight. The two learning rates are example hyperparameters, not prescriptions.
Backbone η=0.00001
change = ηg
= 0.00001×0.2
= 0.000002
New head η=0.001
change = ηg
= 0.001×0.2
= 0.0002
Interpretation: the new head moves 100 times farther in this example. The backbone can adapt gradually instead of immediately overwriting its features.
Discriminative learning rates protect general features
early backbone
η = 0 or 10⁻⁵
general features
late backbone
η = 10⁻⁴
adaptable task features
new head
η = 10⁻³
randomly initialized
Preprocessing Is Part of the Pretrained Model
Pretrained weights expect the channel order, resize/crop policy and normalization used during source training. A model may compile with incorrect preprocessing yet receive a distribution unlike anything it learned. Use the transform bundled with the weight object and save it with deployment code.
BatchNorm needs special attention
BatchNorm has learned affine parameters and running statistics. Freezing parameters does not make every framework's training/evaluation semantics identical. With small target batches, updating running statistics can damage predictions. Keep the intended mode explicit and verify running-stat behavior when unfreezing.
A Two-Stage PyTorch Workflow
This example adapts a pretrained ResNet-18 to three defect classes. The weight object supplies matching image transforms. Stage 1 trains only the replacement head. Stage 2 unfreezes the last residual block and rebuilds the optimizer with smaller backbone learning rate.
import torch
from torch import nn
from torchvision.models import resnet18, ResNet18_Weights
weights = ResNet18_Weights.DEFAULT
preprocess = weights.transforms() # use for train/validation input baseline
model = resnet18(weights=weights)
# Replace the 1,000-class ImageNet head with three target classes.
in_features = model.fc.in_features
model.fc = nn.Linear(in_features, 3)
# Stage 1: freeze backbone, train the new head.
for parameter in model.parameters():
parameter.requires_grad = False
for parameter in model.fc.parameters():
parameter.requires_grad = True
optimizer = torch.optim.AdamW(model.fc.parameters(), lr=1e-3)
# ... run training/validation epochs here ...
# Stage 2: adapt the final backbone block carefully.
for parameter in model.layer4.parameters():
parameter.requires_grad = True
# Rebuild optimizer so newly unfrozen parameters are included.
optimizer = torch.optim.AdamW([
{"params": model.layer4.parameters(), "lr": 1e-5},
{"params": model.fc.parameters(), "lr": 1e-4},
], weight_decay=1e-4)
# Confirm exactly what can update.
trainable = [name for name, p in model.named_parameters() if p.requires_grad]
print("trainable parameter tensors:", len(trainable))
print(trainable[:5])What is reused and what is new?
DEFAULT selects a versioned pretrained-weight recipe; weights.transforms() returns its expected resizing and normalization. in_features is read from ResNet's existing head, while output size 3 comes from the target labels. PyTorch randomly initializes that replacement head.
Why rebuild the optimizer?
requires_grad=False prevents backbone gradients and updates in stage 1. After layer4 is unfrozen, the old optimizer still contains only head parameters; rebuilding it includes the newly trainable tensors and gives backbone and head separate, chosen learning rates.
Training augmentation can be added around the required normalization while validation remains deterministic. Evaluate the frozen-head baseline before stage 2; continue only if target validation improves.
How Much Should You Unfreeze?
| Situation | First experiment | What to compare next |
|---|---|---|
| Very small target set, similar images | Freeze backbone; regularized linear head | Unfreeze only last block with early stopping |
| Moderate target set, noticeable domain shift | Head first, then later blocks | Gradual/full fine-tuning at smaller rates |
| Large target set, related domain | Pretrained full fine-tuning | Scratch baseline under equal compute |
| Medical/satellite/thermal data unlike source | Test transfer, but expect mismatch | Domain-specific/self-supervised pretraining |
| Latency-constrained deployment | Pretrained compact backbone | Distillation, pruning/quantization and device benchmarks |
| Text task with large language model | Head, adapters or low-rank updates | Full fine-tuning only with sufficient data/compute |
Negative Transfer: When Reuse Hurts
Negative transfer means pretrained initialization performs worse than a reasonable alternative because source features or biases do not match the target. Natural-image pretraining may still help medical images, but it is not guaranteed; text pretraining in one language or domain may tokenize and represent another poorly.
Run a scratch baseline
Use the same split, augmentation, budget and selection rule.
Inspect the domain gap
Compare channels, resolution, vocabulary, label meaning and data collection.
Try closer pretraining
In-domain supervised or self-supervised pretraining may transfer better than a famous generic checkpoint.
Common Transfer-Learning Mistakes
| Symptom | Likely mistake | Correction |
|---|---|---|
| Accuracy collapses when fine-tuning begins | Learning rate too high or random head destabilizes backbone | Train head first; reduce backbone rate; unfreeze gradually |
| Unfrozen layer never changes | Optimizer was created before unfreezing and excludes it | Rebuild optimizer or add a parameter group; compare weights before/after |
| Validation changes when batch size changes | Normalization statistics/mode are unstable | Control train/eval mode; inspect BatchNorm running statistics |
| Model compiles but performs poorly | Wrong resize, channel order or normalization | Use transforms paired with exact weight version |
| Great random-split score, poor production score | Duplicate/user/time leakage | Split by deployment unit and remove near duplicates |
| Large model overfits within a few epochs | Too much capacity for target labels | Freeze more, regularize head, augment and stop earlier |
| Checkpoint cannot be reproduced | Model, weights, tokenizer/transform and labels not versioned | Save exact identifiers, preprocessing, class map and configuration |
A Transfer Experiment Must Answer More Than Accuracy
Compare validation quality, per-class errors, calibration, training time, memory and inference latency. Record the best checkpoint by a target metric rather than the last epoch. If labels are scarce, repeat across seeds or folds where appropriate because a single split can make one strategy look better by chance.
Also review the source model's licence, training-data documentation and intended use. Transfer carries source biases and limitations along with useful features.
A Reliable Transfer-Learning Checklist
- Check whether source data and the target domain are related enough to make reuse plausible.
- Use the exact preprocessing paired with the selected checkpoint.
- Measure a frozen-backbone baseline before gradually unfreezing later blocks.
- Use a smaller learning rate for pretrained weights than for the new head.
- Compare against a fair scratch baseline and inspect negative transfer.
- Save the class map, preprocessing, weight version and best validation checkpoint.