Transfer Learning: Train a New Final Layer

A network trained on a million photos already knows how to describe a picture: its layers turn pixels into edges, textures and parts of objects. Transfer learning keeps that knowledge and teaches the network only one new thing, how to name your own classes. You lock the pretrained layers, put a fresh final layer on top and train just that layer, which takes minutes on a laptop CPU and needs only a small labelled dataset. Because a training run is full of random draws, this page also shows how to make such a run give the same numbers every time you start it.

Why features learned on one dataset fit another

An image classifier has two jobs stacked on top of each other. Most of its layers turn a photo into a feature vector: a list of numbers that describes what is in the image. Only the last layer turns that vector into one score per class. A pretrained model learned both jobs on ImageNet, a collection of about 1.2 million labelled photos in 1,000 everyday categories.

The first job is the expensive one, and it is also the one that carries over. Early layers respond to edges and colour changes, and later layers combine those into textures, shapes and parts such as petals, fur or wheels. These patterns appear in almost any photograph, not only in the 1,000 categories the network was trained on. So when you want to tell apart three kinds of birds, or a handful of dog breeds, the features are already useful: photos of the same kind get feature vectors that lie close together, and photos of different kinds get vectors that lie apart.

  • Photo
  • Convolutional layers edges, textures, parts
  • Feature vector describes the image
  • Final layer one score per class
  • Photo to Convolutional layers
  • Convolutional layers to Feature vector
  • Feature vector to Final layer

Everything before the final layer is reused as it is. Only the final layer, which knows nothing but the 1,000 ImageNet names, has to be replaced. This is transfer learning: reusing what a network learned on a large dataset for a new task.

It is also why the new task needs only a few examples. Training a whole convolutional network from random weights needs a dataset of a size few people have. Training one layer on top of good features needs far less, because that layer only has to learn where the groups of feature vectors lie, not how to see.

True or false?

A pretrained ImageNet model is only useful for photos of the 1,000 ImageNet categories.

False. Its layers learned edges, textures and parts that appear in almost any photo. Only its final layer is tied to the 1,000 names, and that is the layer you replace.

Transfer learning needs fewer labelled examples because most of what the network has to learn is already learned.

True. The new layer only maps existing feature vectors to the new classes, which takes far fewer examples than learning to see from scratch.

A new final layer for the new classes

The final layer of a classifier is usually a linear layer (nn.Linear): it takes the feature vector and gives one score per class. A pretrained ImageNet model ends with a layer of 1,000 outputs. For a new task with three classes you need three outputs, so you build a new linear layer with the same number of inputs and one output per new class, and put it where the old one was.

Where that layer sits depends on the model. Take torchvision's MobileNetV3-Small, a small model that runs well on a CPU. Its last layers sit together in a Sequential called classifier, which holds four modules. The layer that gives the class scores is the last of them, classifier[3], and it has 1,024 inputs. (In a ResNet the same layer is called fc.) Print the model, or the layer, to see its name and its number of inputs before you replace it.

Swap the final layer
from torch import nn
from torchvision.models import mobilenet_v3_small, MobileNet_V3_Small_Weights

weights = MobileNet_V3_Small_Weights.DEFAULT
model = mobilenet_v3_small(weights=weights)

print(model.classifier[3])
# Linear(in_features=1024, out_features=1000, bias=True)

model.classifier[3] = nn.Linear(1024, 3)  # one output per new class

Only the last linear layer is replaced. The rest of classifier, including a pretrained linear layer from 576 to 1,024 numbers, stays in place, because it is part of what the network learned. Replacing the whole classifier would throw that away too.

The new layer starts from random weights: nn.Linear draws each weight and bias from a small uniform range, from \( -1/\sqrt{\text{inputs}} \) to \( 1/\sqrt{\text{inputs}} \), which is ±0.03125 for 1,024 inputs. Its first predictions are therefore guesses. Training is what turns them into answers.

Final layerWeight shapeBias shapeParameters
Pretrained, 1,000 ImageNet classes(1000, 1024)(1000)1,025,000
New, 3 classes(3, 1024)(3)3,075

True or false?

The new final layer starts with the pretrained weights of the layer it replaces.

False. It has a different number of outputs, so there is nothing to copy. It starts from random weights and learns everything from the new data.

The new layer must have as many inputs as the old final layer had.

True. It receives the same feature vector as before, here 1,024 numbers, so its number of inputs cannot change. Only the number of outputs does.

Freezing the pretrained layers

Training updates a weight by following its gradient: the backward pass computes how the loss changes with that weight, and the optimizer takes a step. To keep the pretrained layers exactly as they are, you stop both. Every parameter in PyTorch has a flag, requires_grad. When it is False, the operations on that parameter are not recorded for the backward pass, no gradient is computed for it, and its .grad stays empty. This is called freezing a layer.

model.requires_grad_(False) sets the flag to False on every parameter of the model at once. Then the order of the next step matters. A newly built module's parameters have requires_grad=True by default, so if you freeze first and replace the final layer second, exactly the new layer is trainable, with nothing to unfreeze.

Freeze, then replace
import torch
from torch import nn
from torchvision.models import mobilenet_v3_small, MobileNet_V3_Small_Weights

model = mobilenet_v3_small(weights=MobileNet_V3_Small_Weights.DEFAULT)
model.requires_grad_(False)                # freeze every pretrained parameter
model.classifier[3] = nn.Linear(1024, 3)   # new layer: trainable by default

trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
total = sum(p.numel() for p in model.parameters())
print(trainable, total)
# 3075 1520931

optimizer = torch.optim.SGD(model.classifier[3].parameters(), lr=0.01, momentum=0.9)

The optimizer is given only the new layer's parameters. Passing all of them would also work, because a frozen parameter gets no gradient and an optimizer skips a parameter whose gradient is empty. Passing just the trainable ones says plainly what is being trained, and it keeps the optimizer from holding state for a million and a half weights it will never change.

True or false?

After `model.requires_grad_(False)` and then replacing the final layer, you must set `requires_grad=True` on the new layer yourself.

False. A newly built layer is trainable by default. Freezing came before it was created, so it never touched the new layer.

A frozen parameter has no gradient computed for it during the backward pass.

True. Operations on it are not recorded for the backward pass, so autograd never reaches it and its `.grad` stays empty.

Training only the new layer

With the pretrained layers frozen and a new final layer on top, the network works as a fixed feature extractor: it turns each photo into the same feature vector it always would, and only the new layer learns from the labels. The training loop is the usual one: a batch goes forward, the cross-entropy loss compares the scores with the labels, the backward pass computes gradients, and the optimizer takes a step. What changes is how far each pass reaches: the forward pass runs through every layer, and the backward pass stops at the new one.

  • Batch of photos
  • Frozen layers forward only
  • New final layer forward and backward
  • Loss gradients start here
  • Batch of photos to Frozen layers
  • Frozen layers to New final layer
  • New final layer to Loss

This gives feature extraction its three advantages. It is fast, because the backward pass stops at the new layer, so gradients are computed for a few thousand weights instead of all of them. The forward pass still runs through the whole network for every image in every epoch, so it is not free, but on a CPU it takes roughly half the time of training everything. It needs little data, because a few thousand weights can be fitted from a small dataset without simply memorising it. And it changes nothing the network already knew: the frozen weights end the run exactly as they started, so the features stay the ones that were learned on a million photos.

The same fixed features also set the limit. They cannot adapt to your images, so if your photos look very different from ImageNet, a single new layer can only do as well as the fixed features allow.

True or false?

In feature extraction the frozen layers are skipped, which is why training is fast.

False. Every image still goes forward through the whole network. The time saved comes from the backward pass, which only computes gradients for the new layer.

Frozen layers stay in evaluation mode

There is one way a frozen network can still change. Most convolutional networks contain batch normalisation layers, which rescale the values passing through them using a mean and a variance. Which mean and variance they use depends on the mode of the model. In training mode, such a layer uses the mean and variance of the current batch, and it also updates a stored running average of them. In evaluation mode, it uses that stored average and leaves it as it is.

The running average is not a parameter, so the optimizer never steps it and requires_grad has no say over it. It is updated by every forward pass in training mode, frozen or not.

So if the frozen layers run in training mode, their stored averages slowly drift towards the statistics of your small dataset, and the network you meant to keep fixed is no longer the one that was pretrained. The fix is to keep the frozen layers in evaluation mode with .eval(). A common slip is calling model.train() at the start of every epoch, which switches every layer back to training mode; put the frozen part back in evaluation mode right after it.

Many classifiers also have a dropout layer, often right before the final layer. In training mode it sets each value passing through it to zero with a fixed probability, drawn anew for every batch (one in five in MobileNetV3-Small), and scales the remaining values up to make up for the missing ones, so the next layer cannot lean on just a few of its inputs. In evaluation mode it passes every value through unchanged. The new final layer is trained with that dropout in training mode, so only the convolutional layers, where the batch normalisation sits, go back to evaluation mode.

One epoch of training the new layer
model.train()           # new layer (and the dropout before it) in training mode
model.features.eval()   # frozen convolutional layers: batch norm averages stay fixed

for images, labels in train_loader:
    optimizer.zero_grad()
    loss = loss_fn(model(images), labels)
    loss.backward()
    optimizer.step()

Three switches are easy to confuse, because each one stops something different. Freezing decides which weights learn, evaluation mode decides how layers such as batch normalisation and dropout behave, and torch.no_grad() skips the gradient bookkeeping altogether when you only want predictions, as during validation.

SwitchWhat it controlsWhat it leaves alone
requires_grad set to FalseNo gradients, so the optimizer never changes these weightsBatch normalisation averages, dropout
.eval()Batch normalisation uses its stored averages, dropout is offGradients, which are still computed
torch.no_grad()No gradient bookkeeping at all inside its blockLayer behaviour, train or eval mode as set

True or false?

With every pretrained parameter frozen, the batch normalisation layers cannot change during training.

False. Their running mean and variance are updated by the forward pass in training mode, not by the optimizer. Only evaluation mode keeps them fixed.

Calling `model.eval()` does not stop gradients from being computed.

True. Evaluation mode only changes how layers such as batch normalisation and dropout behave. Gradients are controlled by `requires_grad` and `torch.no_grad()`.

A run that repeats exactly

Run the same training twice and, by default, you get slightly different losses and accuracies. That makes it hard to tell whether a change you made helped, or whether you only got a luckier run. The differences come from random draws, and a training run makes several of them.

Random drawWhat fixes it
Starting weights of the new layertorch.manual_seed(seed) before the layer is built
Order of the batches in each epochA seeded torch.Generator passed to the DataLoader
Which values dropout zeroestorch.manual_seed(seed)
Draws made with Python or NumPyrandom.seed(seed) and np.random.seed(seed)
Seeds of worker processes that load dataLoading in the main process, num_workers=0

Every random draw comes from a generator, a small machine that produces a fixed sequence of numbers from a starting value, the seed. Set the same seed and the generator produces the same sequence. PyTorch, Python's random module and NumPy each have their own generator, so each is seeded.

The shuffling gets a generator of its own. Without one, the DataLoader draws its order from PyTorch's main generator, which every other PyTorch draw also uses. Then any extra draw before the shuffling, such as building one more layer, would change every batch. Loading data in the main process means there are no worker processes whose generators would need seeding as well.

Seeds fix the inputs to every calculation. Two more settings fix the calculations themselves. Some operations have fast versions that can add numbers up in a different order from one run to the next. torch.use_deterministic_algorithms(True) makes PyTorch use versions that always produce the same output from the same input on the same software and hardware. For an operation that has no such version, it raises an error. And the number of CPU threads is set to a small fixed number with torch.set_num_threads, called before any other PyTorch work, so that work is split the same way on every run.

Seeds and settings at the start of the script
import random

import numpy as np
import torch
from torch.utils.data import DataLoader

SEED = 0
torch.set_num_threads(2)
torch.use_deterministic_algorithms(True)
random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)

# ... build the model and the new final layer here ...

train_loader = DataLoader(
    train_set,
    batch_size=32,
    shuffle=True,
    num_workers=0,
    generator=torch.Generator().manual_seed(SEED),
)

Why does the order of additions matter at all? Computers store numbers with a limited number of digits, so each addition rounds its result, and adding the same numbers in a different order can round differently. In Python's ordinary floats:

$$(0.1 + 0.2) + 0.3 = 0.6000000000000001$$
$$0.1 + (0.2 + 0.3) = 0.6$$

A training run performs billions of such additions, and a tiny difference in one epoch feeds into the next. This is also why a seeded, deterministic run repeats its numbers exactly on one machine with one version of the libraries, but not from one machine to another. A different processor, a different number of threads or a newer PyTorch release can use other instructions or another order of operations, and PyTorch's own documentation does not promise identical results across releases or platforms, nor between a CPU and a GPU. Expect the same digits when you rerun on your own computer, and similar but not identical digits on anyone else's.

True or false?

Calling `torch.manual_seed` once is enough to make a training run repeat exactly.

False. Python and NumPy have their own generators, worker processes need their own seeds, and operations with nondeterministic algorithms need `torch.use_deterministic_algorithms(True)`.

A seeded, deterministic run can still print different numbers on another laptop.

True. Seeds and deterministic algorithms make a run repeat on the same hardware and library version. Another processor or PyTorch release can round differently.