Sub topic 3
Learning rates and schedules for fine-tuning
This chapter assumes you have the two-stage training loop from the previous chapter, with run_epoch, train_loader, val_loader, a frozen backbone, and an AdamW optimizer. You should be comfortable with PyTorch modules and basic classification metrics.
Learning rates and schedules for fine-tuning
The head is new, so it can take large steps. The unfrozen backbone already holds useful features, so it needs small steps. The stage 2 optimizer in the previous chapter uses 1e-3 for the head and 1e-4 for layer4. A cosine schedule then lowers both rates smoothly over the epochs.
from torch.optim.lr_scheduler import CosineAnnealingLR
scheduler = CosineAnnealingLR(optimizer, T_max=5)
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)
scheduler.step()
lr = optimizer.param_groups[0]["lr"]
print(f"epoch {epoch + 1}: lr {lr:.6f}, val acc {val_acc:.3f}")Evaluating on held-out data
Use the validation set to pick settings. Score the test set once, at the end, so the number you report is honest.
import torch
from sklearn.metrics import confusion_matrix, classification_report
model.eval()
preds, targets = [], []
with torch.inference_mode():
for images, labels in test_loader:
logits = model(images.to(device))
preds += logits.argmax(dim=1).cpu().tolist()
targets += labels.tolist()
print(confusion_matrix(targets, preds))
print(classification_report(targets, preds, target_names=test_ds.classes))The confusion matrix shows which classes get mixed up. The per-class report shows precision and recall for each one.
> Note: the test split must never guide training decisions. If you tune the learning rate while looking at test scores, the test score is no longer a fair estimate.
Recognizing and reducing overfitting
Overfitting means the model memorizes training images and fails on new ones.
| Symptom | Likely cause | Remedy |
|---|---|---|
| Training accuracy high, validation accuracy flat | Model memorizes training images | Add augmentation, raise weight decay, stop earlier |
| Validation loss rises while accuracy holds | Overconfident predictions | Lower the learning rate or train fewer epochs |
| Both accuracies low | Learning rate too low or too little training | Raise the head learning rate or train longer |
Dealing with imbalanced classes
If one class has many more images, the model can score well by favoring it. Weighting the loss by inverse class frequency gives rare classes more influence.
counts = torch.bincount(torch.tensor(train_ds.targets)).float()
weights = 1.0 / counts
weights = weights / weights.sum() * len(counts)
criterion = nn.CrossEntropyLoss(weight=weights.to(device))Analyzing errors and improving your data
Look at the misclassified validation images for each confused pair of classes. Check for mislabeled files, near-duplicate images that leak between train and validation, and blurry or cropped examples. Fixing the data often helps more than changing the model.
Saving the model and predicting on new images
Save the weights along with the class order, so predictions map to the correct names later.
import torch
from PIL import Image
from torchvision import transforms
torch.save(
{"state_dict": model.state_dict(), "classes": train_ds.classes},
"classifier.pt",
)
model.eval()
image = Image.open("photo.jpg").convert("RGB")
batch = val_tfms(image).unsqueeze(0).to(device)
with torch.inference_mode():
probs = model(batch).softmax(dim=1)[0]
top = probs.argmax().item()
print(train_ds.classes[top], f"{probs[top].item():.3f}")Exercise
Your validation accuracy stops improving after epoch 3 while training accuracy keeps rising. Which two changes from this chapter would you try first, and why?
Show answer
Add stronger augmentation and raise weight decay, because both reduce memorization of the training images. Stopping earlier or lowering the learning rate are also reasonable.