Sub topic 9
Training and Validating an Image Classifier
Assume you know basic Python, PyTorch tensors and modules, and the ideas of loss, gradient descent, and epochs. The dataset, transforms, DataLoader objects, model, loss function, and optimizer are already prepared.
Training changes model weights. Validation measures the current model on images that do not update its weights. Keeping these phases separate helps you detect whether the model generalizes beyond its training images.
What happens in one epoch
An epoch is one complete pass through the training dataset. A data loader divides the images into batches. For each training batch, the model produces logits, which are its unnormalized class scores. The loss compares those scores with the correct labels. Backpropagation calculates gradients, and the optimizer updates the weights.
During validation, the model still produces logits and a loss, but no gradients or weight updates are needed.
Use one function for both phases
The optimizer argument distinguishes training from validation. When it is present, the function enables gradients and updates weights. When it is absent, it switches the model to evaluation mode.
import torch
def run_epoch(model, loader, criterion, device, optimizer=None):
training = optimizer is not None
model.train(training)
total_loss = 0.0
correct = 0
count = 0
with torch.set_grad_enabled(training):
for images, labels in loader:
images = images.to(device)
labels = labels.to(device)
logits = model(images)
loss = criterion(logits, labels)
if training:
optimizer.zero_grad(set_to_none=True)
loss.backward()
optimizer.step()
batch_size = images.size(0)
total_loss += loss.item() * batch_size
correct += (logits.argmax(dim=1) == labels).sum().item()
count += batch_size
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}: "
f"train loss {train_loss:.3f}, train acc {train_acc:.3f}, "
f"val loss {val_loss:.3f}, val acc {val_acc:.3f}"
)The function multiplies each batch loss by its batch size before adding it. This produces a correct average even when the final batch is smaller than the others. Accuracy counts correct predictions and divides by the total number of images.
Read the learning curves
Training accuracy usually rises first. Validation accuracy should also improve if the model learns useful visual patterns. If training accuracy keeps rising while validation accuracy stops improving or falls, the model is likely overfitting. Save the checkpoint with the best validation result instead of automatically using the final epoch.
A small gap between training and validation metrics is not automatically a problem. Check the size of the gap, its trend across epochs, and the number of validation images before changing the model.
Exercise
Why must validation run without calling optimizer.step()?
Show answer
Validation should measure the current model on unseen data. Updating weights during validation would make the measurement influence the model and could hide overfitting.