Sub topic 6
Replacing the classification head
This chapter assumes you know basic PyTorch (tensors, nn.Module, state_dict), what a convolutional network does with an image, and the loop of loss, gradient and epoch. It also assumes you have a train_ds from ImageFolder, as built in the earlier chapters on data loading.
By the end you will be able to find the classification head of a torchvision model, replace it with a layer sized for your classes, and check that the swap worked before you train.
What the head is
A pretrained image classifier has two parts.
- The backbone (also called the feature extractor) is the stack of convolution layers. It turns an image into a vector of features.
- The head (also called the classifier) is the last layer or layers. It turns that feature vector into one score per class.
ImageNet models end with a head that produces 1000 scores, one for each ImageNet category. Your task has a different number of classes, so the 1000-way head is useless to you. The backbone is the valuable part. You discard the head and attach a new one.
A logit is a raw, unnormalized score from the final layer. CrossEntropyLoss applies softmax internally, so the new head should output logits and nothing else.
Finding the head
Torchvision does not name the head the same way in every architecture. Print the model and read the last lines of the output.
from torchvision import models
model = models.resnet18(weights=models.ResNet18_Weights.DEFAULT)
print(model.fc)
print(model.fc.in_features, model.fc.out_features)For ResNet-18 this prints Linear(in_features=512, out_features=1000, bias=True). The head is a single linear layer called fc, and it receives a 512-dimensional vector from global average pooling.
Other families put the head somewhere else:
| Architecture | Head location | How to read the input size |
|---|---|---|
| ResNet (`resnet18`, `resnet50`) | `model.fc` (a `Linear`) | `model.fc.in_features` |
| VGG, AlexNet | `model.classifier[6]` (last `Linear` in a `Sequential`) | `model.classifier[6].in_features` |
| MobileNetV2 | `model.classifier[1]` | `model.classifier[1].in_features` |
| EfficientNet | `model.classifier[1]` | `model.classifier[1].in_features` |
| DenseNet | `model.classifier` (a `Linear`) | `model.classifier.in_features` |
| ViT (`vit_b_16`) | `model.heads.head` | `model.heads.head.in_features` |
Do not hard-code 512. Read the size from the existing layer so the same code survives a change of architecture. If you are unsure where the head is, print(model) and look at the final module, or run list(model.named_children())[-1].
Replacing the head
The replacement is an ordinary assignment. For ResNet-18:
import torch
import torch.nn as nn
from torchvision import models
num_classes = 5 # in your project: len(train_ds.classes)
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)
print(model.fc)Two details matter here.
- Order. The freeze loop runs before the assignment. Parameters of a newly created layer have
requires_grad=Trueby default, so the new head is trainable while everything created earlier stays frozen. If you reversed the order, the loop would freeze your new head too, and the model would never learn. - Device. Call
.to(device)after the replacement. The new layer is created on the CPU. If you moved the model to the GPU first and then assigned a new layer, you would get a device mismatch error on the first forward pass.
The new layer is initialized randomly, so before training the model predicts close to randomly. That is expected.
Other architectures
For architectures where the head sits inside a Sequential, replace the specific element and keep the rest, such as dropout, as is.
import torch.nn as nn
from torchvision import models
num_classes = 5
model = models.efficientnet_b0(weights=models.EfficientNet_B0_Weights.DEFAULT)
for param in model.parameters():
param.requires_grad = False
in_features = model.classifier[1].in_features
model.classifier[1] = nn.Linear(in_features, num_classes)
print(model.classifier)The Dropout layer at model.classifier[0] stays in place. It was pretrained with the model, has no weights, and gives you some regularization for free.
Checking the swap
Verify the change before you spend time training. A short check catches most mistakes.
import torch
trainable = [name for name, p in model.named_parameters() if p.requires_grad]
print("trainable parameters:", trainable)
total = sum(p.numel() for p in model.parameters())
learnable = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f"{learnable:,} of {total:,} parameters will be trained")
model.eval()
with torch.no_grad():
dummy = torch.randn(2, 3, 224, 224).to(device)
out = model(dummy)
print(out.shape) # expect torch.Size([2, num_classes])For the ResNet-18 example with five classes, the trainable list is ['fc.weight', 'fc.bias']. The count is 512 × 5 + 5 = 2,565 parameters out of about 11.2 million. The output shape must be (batch, num_classes). If the shape is (2, 1000), the replacement did not take effect on the layer that the forward pass uses.
How the pieces connect
Gradients flow back from the loss through the head. With the backbone frozen they stop there, which makes each step cheaper than full training.
Design choices for the head
A single linear layer is the default
A single Linear layer on pooled features is a good starting point. It has few parameters, so it is hard to overfit with a small dataset. Start here and change it only if validation results show the head is the limit.
Adding a hidden layer or dropout
If a single layer underfits, or you want more regularization on a small dataset, use a small multi-layer head.
import torch.nn as nn
in_features = model.fc.in_features
model.fc = nn.Sequential(
nn.Dropout(p=0.3),
nn.Linear(in_features, 256),
nn.ReLU(),
nn.Dropout(p=0.3),
nn.Linear(256, num_classes),
)The extra layer adds capacity but also adds parameters that must be learned from your data. On a few hundred images, the plain linear head often performs as well or better. Treat the larger head as an experiment and compare validation accuracy.
No softmax in the head
Do not add nn.Softmax at the end. nn.CrossEntropyLoss expects raw logits and combines log-softmax with the negative log-likelihood. Adding softmax before it applies the operation twice, which squeezes the scores and slows learning without raising an error. Apply softmax only at inference time, when you want probabilities.
Binary and multi-label problems
- Two classes, one label per image: you can still use
nn.Linear(in_features, 2)withCrossEntropyLoss. This keeps the code identical to the multi-class case. - Multi-label problems (an image can have several tags at once): output one logit per tag and use
nn.BCEWithLogitsLossinstead. This chapter's examples are single-label.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Output shape is `(batch, 1000)` | Assigned to the wrong attribute (for example `model.classifier` on a ResNet, which adds an unused attribute) | Print the model and replace the module that the forward pass uses |
| `mat1 and mat2 shapes cannot be multiplied` | Hard-coded `in_features` that does not match the backbone | Read `in_features` from the old layer |
| Loss never decreases, no error | Head was created before the freeze loop and froze with the rest | Freeze first, then assign the new head |
| `RuntimeError: element 0 of tensors does not require grad` | Everything is frozen, so the loss has no graph | Check that the new head's parameters have `requires_grad=True` |
| `Expected all tensors to be on the same device` | Head replaced after `.to(device)` | Call `.to(device)` after the replacement |
| `Target out of bounds` or CUDA assert on labels | `num_classes` smaller than the largest label | Use `len(train_ds.classes)` |
| Optimizer raises `optimizer got an empty parameter list` | Built the optimizer from parameters that are all frozen | Pass `model.fc.parameters()` |
Create the optimizer after you replace the head. An optimizer holds references to specific parameter objects. If you build it from the old model.fc and then assign a new layer, the optimizer still points at the discarded layer, and the new head never updates.
Keeping class order consistent
The head's output index i means whatever class your dataset assigned index i. ImageFolder sorts class folder names alphabetically, so train_ds.classes might be ['daisy', 'rose', 'tulip'], and logit 0 is daisy. The validation set must use the same mapping. Because it comes from folders with the same names, it does, but only if both folders contain every class. A missing class folder in val shifts the indices. Check this:
assert train_ds.classes == val_ds.classes, "class folders differ between train and val"Save train_ds.classes with the weights, as a later chapter shows. Without it, a saved head is just numbers with no names.
Exercise
You load a ResNet-50, then run model.fc = nn.Linear(2048, 10), then for p in model.parameters(): p.requires_grad = False, then build AdamW(model.fc.parameters()). Training runs without an error, but loss stays flat. What went wrong, and what is the correct order? Also, why is hard-coding 2048 a risk?
Show answer
The freeze loop ran after the new head was created, so it froze the new head too. No parameter has requires_grad=True, so nothing updates (the optimizer holds frozen parameters, and the loss has no gradient path through the head). Correct order: load the model, freeze all parameters, then assign the new head (which is trainable by default), move the model to the device, and then create the optimizer from model.fc.parameters(). Hard-coding 2048 ties the code to ResNet-50. If you switch to ResNet-18 the feature size is 512 and the forward pass fails with a shape mismatch. Reading model.fc.in_features avoids this.
Exercise
A colleague replaces the head of a pretrained EfficientNet-B0 with nn.Sequential(nn.Linear(1280, 5), nn.Softmax(dim=1)) and trains with CrossEntropyLoss. Training works but converges slowly. Why, and how do you fix it?
Show answer
CrossEntropyLoss already applies log-softmax, so the extra Softmax applies it twice. The scores are squashed into the range 0 to 1, which shrinks the gradients and weakens the training signal. Remove the Softmax and output raw logits. Apply softmax only at inference time to get probabilities. The head should also replace model.classifier[1] rather than the whole model.classifier, so the pretrained dropout layer is kept.