Sub topic 2
Replacing the classification head
This chapter assumes you have train_ds, val_ds, and num_classes from the dataset chapter, and that you know PyTorch modules, tensors, and the basic loop of loss, backward pass, and optimizer step.
Replacing the classification head
A pretrained ResNet-18 ends with a linear layer that outputs 1000 ImageNet scores. Your task has num_classes outputs, so you swap that final layer. model.fc.in_features reads the width of the feature vector (512 for ResNet-18), so the new layer fits the backbone's output.
Freezing the backbone and unfreezing later layers
Stage 1 trains only the new head. Freeze every parameter first, then replace the head. The new layer's parameters start with requires_grad=True, so they stay trainable.
import torch
import torch.nn as nn
from torchvision import models
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
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, num_classes)
model = model.to(device)Stage 2 unfreezes the last residual block, layer4, and trains it with a smaller learning rate than the head.
Choosing a loss and an optimizer
nn.CrossEntropyLoss expects raw logits. Do not apply softmax to the model output first, because the loss applies it internally. Pass only the trainable parameters to the optimizer.
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(model.fc.parameters(), lr=1e-3)Training and validating
One function runs both phases. It calls model.train() or model.eval(), and it computes gradients only when an optimizer is passed.
def run_epoch(model, loader, criterion, device, optimizer=None):
training = optimizer is not None
model.train(training)
total_loss, correct, count = 0.0, 0, 0
with torch.set_grad_enabled(training):
for images, labels in loader:
images, labels = images.to(device), labels.to(device)
logits = model(images)
loss = criterion(logits, labels)
if training:
optimizer.zero_grad()
loss.backward()
optimizer.step()
total_loss += loss.item() * images.size(0)
correct += (logits.argmax(dim=1) == labels).sum().item()
count += images.size(0)
return total_loss / count, correct / count
for epoch in range(5):
train_loss, train_acc = run_epoch(model, train_loader, criterion, device, optimizer)
val_loss, val_acc = run_epoch(model, val_loader, criterion, device)
print(f"epoch {epoch + 1}: train acc {train_acc:.3f}, val acc {val_acc:.3f}")For stage 2, unfreeze layer4, then rebuild the optimizer with two parameter groups:
for param in model.layer4.parameters():
param.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,
)Exercise
Why does the code set requires_grad to False on the backbone before replacing model.fc?
Show answer
The new layer is created with requires_grad enabled by default. Freezing first means the loop touches only the original backbone parameters, so the new head stays trainable.