Sub topic 8
Choosing a Loss and an Optimizer
Assume you know Python, PyTorch tensors and modules, and the basic training cycle of forward pass, loss, backpropagation, and gradient descent. This chapter uses a pretrained image classifier whose final layer has already been replaced for your classes.
The loss measures classification error
A loss function converts the model's predictions and the correct labels into one number. A lower number means the predictions better match the labels. Training minimizes this number by changing model parameters.
For a single-label classifier, each image belongs to exactly one class. Use CrossEntropyLoss:
criterion = nn.CrossEntropyLoss()The model must return logits, which are unnormalized scores with shape [batch_size, num_classes]. Do not apply softmax before passing logits to CrossEntropyLoss. The loss applies the needed normalization internally.
Labels must be integer class indexes with shape [batch_size]. If the classes are cat, dog, and bird, the labels might be 0, 1, and 2.
| Tensor | Shape | Meaning |
|---|---|---|
| Logits | `[32, 3]` | Scores for 32 images and 3 classes |
| Labels | `[32]` | Correct class index for each image |
| Loss | `[]` | One average error value |
The optimizer updates parameters
An optimizer uses gradients from the loss to update trainable parameters. With a frozen backbone, optimize only the replacement head:
import torch.nn as nn
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(
model.fc.parameters(),
lr=1e-3,
weight_decay=1e-2,
)lr is the learning rate, which controls the update size. A value that is too large can make training unstable. A value that is too small can make learning very slow. weight_decay adds a small penalty to large weights and can reduce overfitting.
AdamW adapts updates for each parameter and usually works well as a starting point for transfer learning. SGD with momentum can also work well, especially when you tune its learning rate and schedule carefully.
The update order matters
A training step follows this order:
import torch
import torch.nn as nn
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(model.fc.parameters(), lr=1e-3)
model.train()
for images, labels in train_loader:
images = images.to(device)
labels = labels.to(device)
optimizer.zero_grad()
logits = model(images)
loss = criterion(logits, labels)
loss.backward()
optimizer.step()zero_grad() removes gradients left from the previous batch. backward() computes new gradients. step() changes the parameters. Omitting zero_grad() accumulates gradients across batches and usually produces unintended updates.
Only parameters with requires_grad=True should be passed to the optimizer. After replacing the head, the new layer is trainable while the frozen backbone is not.
When you later unfreeze part of the backbone, use parameter groups so the new head can keep a larger learning rate than the pretrained layers.
Exercise
Your classifier returns logits with shape [16, 4], but CrossEntropyLoss reports a target-size error. What should you check first?
Show answer
Check that labels have shape [16] and contain integer class indexes from 0 through 3, rather than one-hot vectors or an extra dimension.