Sub topic 6
Replacing the Classification Head
This chapter assumes that you understand PyTorch modules, tensors, and the basic training loop. It also assumes that your images are already loaded in batches and that you have chosen a pretrained convolutional neural network, such as ResNet-18.
A pretrained model was originally trained to classify ImageNet images into 1,000 categories. Its final layer, called the classification head, converts the features produced by the backbone into one score for each of those categories. Your dataset has different categories, so you replace that final layer.
What the head does
The backbone detects useful visual patterns such as edges, textures, shapes, and object parts. The head maps those learned features to your labels.
A classification head usually contains a linear layer. A linear layer is a function that multiplies its input by learned weights and adds a bias. During training, its output values are called logits. A logit is an unnormalized score for one class.
For example, if your dataset contains three classes, the new head must return three logits for every image.
flowchart TD
A[Input image] --> B[Pretrained backbone]
B --> C[Feature vector]
C --> D[New linear classification head]
D --> E[One logit per custom class]The backbone's output size determines the input size of the new head. The number of classes determines its output size.
| Dataset property | Used by |
|---|---|
| Number of backbone features | `nn.Linear` input size |
| Number of custom classes | `nn.Linear` output size |
Freeze the backbone and replace the head
Start by freezing the pretrained parameters. A frozen parameter does not receive gradient updates. This lets the new head learn your label mapping without immediately changing the useful visual features.
import torch
import torch.nn as nn
from torchvision import models
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
num_classes = 3
model = models.resnet18(weights=models.ResNet18_Weights.DEFAULT)
# Keep the pretrained feature extractor fixed.
for parameter in model.parameters():
parameter.requires_grad = False
# ResNet-18's original head is model.fc.
in_features = model.fc.in_features
model.fc = nn.Linear(in_features, num_classes)
model = model.to(device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(
model.fc.parameters(),
lr=1e-3,
weight_decay=1e-2,
)
print(model.fc)Assigning a new nn.Linear layer creates fresh weights. These weights have requires_grad=True by default, so the optimizer can train them. The optimizer receives only model.fc.parameters(), which makes the intended training scope explicit.
The model returns a tensor with shape [batch_size, num_classes]. Do not apply softmax before passing these logits to CrossEntropyLoss. That loss function applies the required normalization internally.
Keep class indices consistent
ImageFolder assigns an integer index to each class name in alphabetical order. The model's output index must keep that same meaning during training, evaluation, and inference.
For example:
- output index
0meanscat - output index
1meansdog - output index
2meansrabbit
Save the class-name list with the model. Never recreate the list manually in a different order.
Common mistakes
- Setting
num_classesto 1 for a two-class problem while still using multiclassCrossEntropyLoss. Use two outputs for two classes. - Freezing the model after replacing the head. That can accidentally freeze the new head too.
- Passing
model.parameters()to the optimizer during the frozen stage. It may work, but selectingmodel.fc.parameters()documents the intended behavior. - Applying
softmaxbeforeCrossEntropyLoss. - Forgetting to move the replacement head to the same device as the backbone.
Exercise
A dataset has four classes, and model.fc.in_features is 512. What replacement head should you create, and how many logits should one image produce?
Show answer
Create nn.Linear(512, 4). Each image produces four logits, one for each class.