Concept Explanation
Training a ResNet-50 from scratch takes millions of images, days of GPU time, and money. You have 800 photos of machine parts and an afternoon.
Transfer learning is the answer, and it is not a compromise — it usually produces a better model than from-scratch training would, even with unlimited time on a small dataset.
The insight: a network trained on ImageNet's 1.2 million photos has already learned what edges, textures, corners, fur, metal, and wheels look like. Those early-layer features are not specific to ImageNet's 1,000 categories; they are general facts about images. Only the final classification layer is task-specific. So keep the features, replace the classifier, and train on your 800 photos.
The Two Strategies
| Strategy | What you train | Data needed | When |
|---|---|---|---|
| Feature extraction | Only the new head | A few hundred images | Small dataset, similar domain |
| Fine-tuning | New head, then some/all backbone layers | A few thousand | More data, or a distant domain |
The decision comes down to two questions:
Small data + similar domain -> freeze everything, train the head
Small data + different domain -> freeze early layers, train later ones
Large data + similar domain -> fine-tune the whole thing, low learning rate
Large data + different domain -> fine-tune everything, or train from scratch
"Different domain" means genuinely different statistics — X-rays, satellite imagery, and microscopy look nothing like ImageNet photos, so more of the backbone needs to adapt.
Loading a Pretrained Model
from torchvision import models
model = models.resnet18(weights=models.ResNet18_Weights.DEFAULT)
The old pretrained=True argument is deprecated; the weights= enum is the current API and it also carries the exact preprocessing the weights expect:
weights = models.ResNet18_Weights.DEFAULT
transform = weights.transforms() # correct resize, crop, and normalisation
Using that instead of hand-written transforms eliminates a whole class of silent bugs.
Freezing Parameters
for param in model.parameters():
param.requires_grad = False # freeze everything
model.fc = nn.Linear(model.fc.in_features, num_classes) # new head, trainable
A newly created layer has requires_grad=True by default, so replacing the head after freezing gives you exactly the right configuration. Frozen parameters get no gradients, which also makes the backward pass much faster.
Where the New Head Goes
Different architectures name their classifier differently, and this catches everyone once:
| Model | Attribute to replace |
|---|---|
| ResNet family | model.fc |
| VGG, AlexNet | model.classifier[6] |
| EfficientNet | model.classifier[1] |
| DenseNet | model.classifier |
| Vision Transformer | model.heads.head |
print(model) shows you the structure. Read the last few lines and you will see which one applies.
Preprocessing Must Match Training
The pretrained weights were learned on inputs normalised with ImageNet's statistics:
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
Skip this and the features are subtly wrong everywhere. The model still trains, converges, and produces mediocre accuracy you cannot explain — one of the harder bugs to spot because nothing errors.
Discriminative Learning Rates
When you do unfreeze the backbone, do not train it at the head's learning rate. The pretrained weights are already good; large updates destroy them. Give earlier layers a much smaller rate:
optimiser = torch.optim.Adam([
{"params": model.layer4.parameters(), "lr": 1e-4},
{"params": model.fc.parameters(), "lr": 1e-3},
])
The standard recipe: train the head to convergence with the backbone frozen, then unfreeze the last block or two and continue at a tenth of the learning rate.
Code Example #1 (Basic)
Feature extraction: freeze the backbone, swap the head, train.
import torch
import torch.nn as nn
from torchvision import models
torch.manual_seed(0)
device = "cuda" if torch.cuda.is_available() else "cpu"
NUM_CLASSES = 4 # our task: 4 kinds of machine part
# --- Load pretrained weights and their matching preprocessing ---
weights = models.ResNet18_Weights.DEFAULT
model = models.resnet18(weights=weights)
preprocess = weights.transforms() # exactly what these weights expect
print(preprocess)
total_before = sum(p.numel() for p in model.parameters())
# --- Freeze the entire backbone ---
for param in model.parameters():
param.requires_grad = False
# --- Replace the 1000-class head with our own (trainable by default) ---
in_features = model.fc.in_features # 512 for resnet18
model.fc = nn.Linear(in_features, NUM_CLASSES)
model = model.to(device)
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
frozen = sum(p.numel() for p in model.parameters() if not p.requires_grad)
print(f"\ntotal parameters: {total_before:>12,}")
print(f"frozen (pretrained): {frozen:>12,}")
print(f"trainable (new head): {trainable:>12,}")
print(f"training just {100 * trainable / (trainable + frozen):.2f}% of the network\n")
# --- Only pass trainable parameters to the optimiser ---
optimiser = torch.optim.Adam(
[p for p in model.parameters() if p.requires_grad], lr=1e-3
)
criterion = nn.CrossEntropyLoss()
# One synthetic step to prove the wiring
images = torch.randn(8, 3, 224, 224, device=device)
labels = torch.randint(0, NUM_CLASSES, (8,), device=device)
model.train()
optimiser.zero_grad()
loss = criterion(model(images), labels)
loss.backward()
optimiser.step()
print(f"one training step, loss {loss.item():.4f}")
print(f"model.fc.weight.grad is None: {model.fc.weight.grad is None}")
print(f"model.layer1[0].conv1.weight.grad is None: {model.layer1[0].conv1.weight.grad is None}")
print("^ the frozen backbone received no gradient, exactly as intended.")
Look at the parameter split: about 2,000 trainable weights against 11 million frozen ones. That is why this trains in minutes on a CPU and why it does not overfit 800 images.
Code Example #2 (Intermediate)
The full two-phase recipe: train the head, then unfreeze and fine-tune.
import copy
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, TensorDataset
from torchvision import models
torch.manual_seed(0)
device = "cuda" if torch.cuda.is_available() else "cpu"
NUM_CLASSES = 3
IMG = 64 # small so the example runs quickly; use 224 for real work
def build_model(num_classes):
weights = models.ResNet18_Weights.DEFAULT
m = models.resnet18(weights=weights)
for p in m.parameters():
p.requires_grad = False # phase 1: everything frozen
m.fc = nn.Sequential(
nn.Dropout(0.2),
nn.Linear(m.fc.in_features, num_classes),
)
return m.to(device)
def trainable_report(model, label):
t = sum(p.numel() for p in model.parameters() if p.requires_grad)
f = sum(p.numel() for p in model.parameters() if not p.requires_grad)
print(f"{label:<22} trainable {t:>10,} frozen {f:>10,}")
# ---------- A small synthetic dataset with real, learnable structure ----------
def make_dataset(n_per_class=120):
g = torch.Generator().manual_seed(2)
xs, ys = [], []
for cls in range(NUM_CLASSES):
for _ in range(n_per_class):
img = 0.25 * torch.rand(3, IMG, IMG, generator=g)
if cls == 0: # red vertical band
img[0, :, IMG // 3:2 * IMG // 3] += 0.7
elif cls == 1: # green horizontal band
img[1, IMG // 3:2 * IMG // 3, :] += 0.7
else: # blue centre block
img[2, IMG // 4:3 * IMG // 4, IMG // 4:3 * IMG // 4] += 0.7
# ImageNet normalisation -- must match the pretrained weights
mean = torch.tensor([0.485, 0.456, 0.406]).view(3, 1, 1)
std = torch.tensor([0.229, 0.224, 0.225]).view(3, 1, 1)
xs.append(((img.clamp(0, 1)) - mean) / std)
ys.append(cls)
X = torch.stack(xs)
y = torch.tensor(ys)
perm = torch.randperm(len(X), generator=g)
return X[perm], y[perm]
X, y = make_dataset()
split = int(0.8 * len(X))
train_loader = DataLoader(TensorDataset(X[:split], y[:split]), batch_size=32, shuffle=True)
val_loader = DataLoader(TensorDataset(X[split:], y[split:]), batch_size=64, shuffle=False)
n_val = len(X) - split
def run_epochs(model, optimiser, epochs, tag):
criterion = nn.CrossEntropyLoss()
best, best_state = 0.0, None
for epoch in range(1, epochs + 1):
model.train()
tl = 0.0
for xb, yb in train_loader:
xb, yb = xb.to(device), yb.to(device)
if torch.rand(1).item() > 0.5:
xb = torch.flip(xb, dims=[3])
optimiser.zero_grad()
loss = criterion(model(xb), yb)
loss.backward()
optimiser.step()
tl += loss.item() * len(xb)
model.eval()
correct = 0
with torch.no_grad():
for xb, yb in val_loader:
xb, yb = xb.to(device), yb.to(device)
correct += (model(xb).argmax(1) == yb).sum().item()
acc = correct / n_val
if acc > best:
best, best_state = acc, copy.deepcopy(model.state_dict())
print(f" {tag} epoch {epoch} train {tl / split:.4f} val acc {acc:.3f}")
model.load_state_dict(best_state)
return best
model = build_model(NUM_CLASSES)
# ---------- PHASE 1: head only ----------
print("PHASE 1 -- feature extraction")
trainable_report(model, " frozen backbone")
opt1 = torch.optim.Adam([p for p in model.parameters() if p.requires_grad], lr=1e-3)
acc1 = run_epochs(model, opt1, epochs=4, tag="p1")
print(f" best after phase 1: {acc1:.3f}\n")
# ---------- PHASE 2: unfreeze the last block, tiny learning rate ----------
print("PHASE 2 -- fine-tuning layer4")
for p in model.layer4.parameters():
p.requires_grad = True
trainable_report(model, " layer4 unfrozen")
# Discriminative learning rates: the pretrained block moves 10x slower
opt2 = torch.optim.Adam([
{"params": model.layer4.parameters(), "lr": 1e-4},
{"params": model.fc.parameters(), "lr": 1e-3},
])
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(opt2, T_max=4)
acc2 = run_epochs(model, opt2, epochs=4, tag="p2")
scheduler.step()
print(f" best after phase 2: {acc2:.3f}")
print(f"\nfeature extraction {acc1:.3f} -> fine-tuned {acc2:.3f} ({acc2 - acc1:+.3f})")
# ---------- Save only what you need to reload ----------
torch.save({"state_dict": model.state_dict(),
"num_classes": NUM_CLASSES,
"arch": "resnet18"}, "finetuned.pt")
print("\nsaved finetuned.pt (state_dict, not the whole object)")
The two-phase order matters, and skipping phase 1 is the classic error. A randomly-initialised head produces large, meaningless gradients on the first few batches; let those flow into an unfrozen backbone and they wreck the pretrained features before the head has learned anything. Train the head first, then unfreeze.
Common Mistakes
- Skipping the ImageNet normalisation: the model trains, converges, and quietly underperforms. Use
weights.transforms()and the problem disappears. - Unfreezing the backbone from epoch 1: an untrained head's huge gradients destroy the pretrained features. Two phases, always.
- Fine-tuning at the head's learning rate:
1e-3on pretrained weights is catastrophic forgetting. Use1e-4or lower for the backbone. - Replacing the wrong attribute:
model.classifierdoes not exist on a ResNet, andmodel.fcdoes not exist on a VGG.print(model)first. - Passing all parameters to the optimiser after freezing: harmless for correctness but wasteful, and it silently un-freezes if you later flip
requires_grad. Filter explicitly. - Forgetting the frozen model still needs
model.eval(): frozen BatchNorm layers keep updating their running statistics intrain()mode, which shifts your features. - Augmenting validation data: the metric becomes noise and you cannot compare epochs.
- Using an ImageNet backbone on a wildly different domain with everything frozen: for X-rays or spectrograms, the later layers need to adapt. Unfreeze more.
torch.save(model)instead ofmodel.state_dict(): pickling the whole object couples the file to your exact class definitions and breaks on refactor.- Input size mismatch: most ImageNet models expect 224×224. Smaller inputs work with modern architectures thanks to adaptive pooling, but accuracy drops.
- Choosing a giant backbone for 500 images: ResNet-152 will overfit where ResNet-18 would not. Match capacity to data.
Best Practices
- Always start from pretrained weights for images, audio spectrograms, and text. From-scratch training is the exception, not the default.
- Use
weights.transforms()so preprocessing is guaranteed to match what the weights were trained on. - Follow the two-phase recipe: freeze and train the head, then unfreeze the last block or two at a tenth of the learning rate.
- Print the trainable-versus-frozen parameter split to confirm freezing actually worked.
- Use discriminative learning rates via optimiser parameter groups when fine-tuning.
- Pick a backbone proportional to your data: ResNet-18 or EfficientNet-B0 for hundreds of images; go bigger only when a smaller model plateaus.
- Save
state_dict()plus the metadata needed to rebuild (architecture name, class count, class names). - Add
nn.Dropoutin the new head — it is the cheapest regularisation available on a small dataset. - Augment training data aggressively when the dataset is small; it is the highest-value intervention you have.
- Checkpoint the best validation accuracy and restore it before saving.
- Compare against a frozen-features baseline so you can prove fine-tuning actually helped rather than assuming it.
Practice Exercises
- The Freeze Audit: Load
resnet18pretrained, freeze the backbone, replacemodel.fc, and print the trainable and frozen parameter counts plus the percentage trainable. Then confirm with one backward pass that a backbone layer's.gradis stillNone. - The Head Hunt: Load three different architectures (
resnet18,vgg16,efficientnet_b0),printeach one, and write down the exact attribute path you would replace to change the number of output classes. Then do it for all three. - The Two Phases: Train a head-only model for 5 epochs and record validation accuracy. Then unfreeze the final block, continue for 5 more epochs at
lr=1e-4, and report the change. Repeat with the backbone unfrozen from epoch 1 and explain why that run is worse.