Fine-Tune and Keep the Best Weights

Training only a new final layer on top of a frozen pretrained network leaves every feature the network learned exactly as it was. Those features were learned on other photos, so they fit new images well but not perfectly. Fine-tuning lets the pretrained layers themselves learn a little from the new images. Done carelessly, it spoils what they already know. Doing it well comes down to a few decisions: in which order to train, how large the steps should be, how many layers to open up, and which epoch's weights to keep. The validation accuracy of those kept weights then tells whether fine-tuning helped at all.

What fine-tuning changes

A pretrained image classifier is a stack of layers. The early layers respond to edges and colours, the middle ones to textures, the late ones to parts of objects, and a final layer turns the resulting feature vector into class scores. In feature extraction, the network is frozen (its parameters have requires_grad set to False, so no gradients are computed for them) and only a new final layer with one output per new class is trained.

Fine-tuning goes one step further: it unfreezes some or all of the pretrained layers and continues training them on the new data, with the usual loop of batches, loss and optimizer steps. The gradients of the loss now reach those layers too, so their filters shift slightly towards the patterns that matter for the new classes. A network pretrained on everyday objects, fine-tuned on photos of plant leaves, can learn to respond more to leaf veins and spots than to the fur and wheels it saw before.

Feature extraction
  • Early layers edges, colours
  • Middle layers textures
  • Late layers object parts
  • New final layer trained
  • Early layers to Middle layers
  • Middle layers to Late layers
  • Late layers to New final layer
Fine-tuning
  • Early layers edges, colours
  • Middle layers textures
  • Late layers object parts
  • Final layer already trained
  • Early layers to Middle layers
  • Middle layers to Late layers
  • Late layers to Final layer

The cost is that far more weights now change. A small dataset that was plenty for one final layer is little for millions of pretrained weights, so fine-tuning can overfit quickly. That is why the guides describe it as an optional last step, and why the rest of this page is about doing it carefully.

Train the final layer first

A new final layer starts from random weights, so its first class scores are close to random. The cross-entropy loss is then large, and so are its gradients. If the pretrained layers were unfrozen at that moment, those large gradients would flow back into them and push their weights far away from the values that made them useful. The good features would be damaged in the first few batches, by corrections whose only purpose was to fix a layer that had not learned anything yet.

The safe order has two stages. First, train only the new final layer on top of the frozen network until its validation accuracy stops improving. Now its scores are sensible and the loss is small, so the gradients are small too. Only then unfreeze pretrained layers and continue training them, together with the final layer.

  • Pretrained network new final layer, random
  • Stage 1: final layer until the loss is small
  • Unfreeze layers requires_grad = True
  • Stage 2 small learning rate
  • Pretrained network to Stage 1: final layer
  • Stage 1: final layer to Unfreeze layers
  • Unfreeze layers to Stage 2

Two details make the first stage do what it promises. The first is batch normalisation. A batch normalisation layer keeps a running mean and variance of its inputs, and it updates them from every batch whenever it is in training mode. Freezing with requires_grad = False only stops gradient updates, so it does not stop this. That is why, while only the final layer trains, the frozen layers are kept in evaluation mode with .eval(): their statistics then stay the ones learned in pretraining. Unfreezing does not change this. requires_grad and the mode are separate switches, so the pretrained layers can be trainable and still be in evaluation mode. The Keras transfer learning guide keeps them there in the second stage too, so that the batches of a small dataset do not overwrite statistics measured on millions of images.

The second detail is the optimizer, which updates only the parameters it was given. An optimizer built for the final layer alone never touches the layers unfrozen later. So the second stage needs the unfrozen parameters in an optimizer, either a new one or one extended with add_param_group.

True or false?

Setting requires_grad to False on every pretrained parameter keeps the network exactly as it was, even in training mode.

False. The weights stay fixed, but batch normalisation layers in training mode still update their running mean and variance from each batch. Evaluation mode is what stops that.

Unfreezing a layer by setting requires_grad back to True is not enough if the optimizer was built from the final layer's parameters only.

True. The unfrozen layer now gets gradients, but an optimizer only steps the parameters it holds. Its parameters must be added to an optimizer before they change.

Training the final layer first is about saving time: the result would be the same if everything were unfrozen from the start.

False. The order protects the pretrained features. A random final layer causes large gradients, and with everything unfrozen they would overwrite the pretrained weights.

Small steps for pretrained weights

Each optimizer step moves a weight against its gradient by an amount scaled by the learning rate. For plain gradient descent the step is:

$$w \leftarrow w - \eta \, \frac{\partial L}{\partial w}$$

w is one weight, L the loss, and the learning rate eta sets the size of every step

A pretrained weight already sits at a good value. A large learning rate would move it far in a single step, based on a few batches of a small dataset, and overwrite what millions of images taught it. A small learning rate moves it a little at a time, so the feature it computes bends towards the new images instead of being replaced. Small steps also slow down how fast the larger model can memorise the training photos.

There is no single correct value. The Keras transfer learning guide trains the final layer with the Adam optimizer at its default learning rate of 0.001 and fine-tunes with 0.00001, a hundred times smaller. The usual rule is a learning rate for the pretrained layers clearly smaller than the one the final layer trained with, then checked against the validation accuracy. PyTorch lets one optimizer hold several parameter groups, each with its own learning rate, which fits this rule directly:

import torch
from torchvision.models import resnet18, ResNet18_Weights

model = resnet18(weights=ResNet18_Weights.DEFAULT)
model.fc = torch.nn.Linear(model.fc.in_features, 5)  # new final layer, 5 classes

# ... stage 1: everything frozen except model.fc, trained until it levels off ...

model.layer4.requires_grad_(True)  # unfreeze the last block

optimizer = torch.optim.Adam([
    {"params": model.layer4.parameters(), "lr": 1e-5},  # pretrained: tiny steps
    {"params": model.fc.parameters()},  # uses the default lr below
], lr=1e-4)

In this example, layer4 is the last block of convolution layers in a ResNet-18 and fc its final layer. The group without its own lr takes the lr=1e-4 given after the list, so the final layer keeps moving a little faster than the pretrained block it sits on. The exact numbers are a starting point to adjust, not a recipe.

How much of the network to unfreeze

Unfreezing is not all or nothing. The early layers hold generic features, edges and colour blobs that are useful for almost any photo, while each later layer is more specific to the classes of the original dataset. So the later layers are the ones that gain most from adapting, and a common choice is to unfreeze only the last block or two and keep the early layers frozen. The decision trades three things against each other:

What is trainedWhat can adaptTraining timeRisk of overfitting
Final layer onlyonly how features are combined into scoresshortestlowest
Last blocks and final layerobject-level featureslongermoderate
All layersevery feature, down to edgeslongesthighest on a small dataset

Training time grows because gradients must be computed for every unfrozen layer, while the forward pass through the whole network is needed in any case. In the official PyTorch transfer learning tutorial, training only the final layer took about half the time of fine-tuning the whole network on a CPU. On a laptop, that difference decides how many experiments are possible in an afternoon.

The size of the dataset and how much it resembles the original photos guide the choice. With a small dataset of everyday photos, the frozen features already fit and fine-tuning risks overfitting, so training the final layer alone may be best. With many images, or images that look very different from the original ones, such as X-rays or satellite pictures, more layers have something to learn and enough data to learn it.

True or false?

When only some layers are unfrozen, the usual choice is the last ones, because they hold the features most specific to the original classes.

True. Early layers detect edges and colours that suit almost any photo. The late layers are tuned to the old classes, so they have the most to gain from adapting.

Unfreezing more layers always gives a higher validation accuracy, because the model can adapt more.

False. More trainable weights on a small dataset also means more room to memorise the training photos. Whether it helps shows only on the validation set.

Keeping the weights of the best epoch

During fine-tuning, the validation accuracy usually rises for a few epochs and then levels off or falls as the model starts to overfit. The weights after the last epoch are therefore often not the best ones. The fix is to measure the validation accuracy after every epoch and save the weights each time it beats the best value so far. When training ends, those saved weights, not the last ones, are the result.

Validation accuracy per epoch (illustration, made-up numbers)

validation accuracy against epoch

  • validation accuracy

A model's state_dict() holds all its learned tensors by layer name: the weights, and also buffers such as the running statistics of batch normalisation. Saving it with torch.save is the recommended way to keep a model for later use. To make the file usable on its own, it is saved together with what the weights need: above all the class names in the order of the outputs, since output 3 means nothing without knowing which class is number 3. A dictionary holds them all in one file:

best_accuracy = 0.0

for epoch in range(num_epochs):
    train_one_epoch(model, train_loader, optimizer)
    accuracy = evaluate(model, val_loader)  # a Python float

    if accuracy > best_accuracy:
        best_accuracy = accuracy
        torch.save({
            "model_state_dict": model.state_dict(),
            "class_names": class_names,
            "epoch": epoch,
            "val_accuracy": accuracy,
        }, "best_model.pt")

checkpoint = torch.load("best_model.pt", weights_only=True)
model.load_state_dict(checkpoint["model_state_dict"])

Here train_one_epoch and evaluate stand for the usual training loop and validation loop, and class_names is the list of class names in label order. The file holds only tensors and plain Python data, so torch.load reads it with weights_only=True, which has been its default since PyTorch 2.6. The .pt extension is the common convention.

One trap is keeping the best weights in memory with best = model.state_dict(). That returns references to the model's own tensors, not a copy, so the next epochs change best along with the model, and the "best" weights end up being the last ones. Saving to a file at that moment, as above, or taking copy.deepcopy(model.state_dict()) keeps a real snapshot.

True or false?

After best = model.state_dict(), the variable best keeps the weights of that epoch while training continues.

False. state_dict() returns references to the live tensors. Every later update changes them too, so best ends up holding the last weights.

A saved state_dict without the class names cannot say which class a prediction is.

True. The weights give one score per output position. Only the list of class names in the same order turns position 3 into a name.

Judging whether fine-tuning helped

Fine-tuning is a bet, and the validation accuracy settles it. The comparison is between the best validation accuracy at the end of the first stage, with only the final layer trained, and the best validation accuracy of the second stage. Both are measured on the same validation images with the same fixed preparation, so the difference comes from the training, not from the measurement. If the second stage beats the first, keep the fine-tuned weights; if not, keep the weights from the first stage.

Losing is a real outcome, not a sign of a mistake. In the sample output of the official PyTorch tutorial, the network fine-tuned in full reached a best validation accuracy of 0.934641, while the frozen network with only its final layer trained reached 0.954248. In the Keras guide, the validation accuracy went from 0.9705 after training the final layer to 0.9494 after one epoch of fine-tuning. A small dataset gives the extra weights little to learn from and much to memorise.

Small differences need care. On a validation set of a few hundred images, one image classified right instead of wrong moves the accuracy by a fraction of a percent. To compare two runs, each must repeat exactly, with fixed seeds and deterministic algorithms. Then rerunning gives the same number, so a difference is not just another roll of the dice. It is still measured on one particular set of random draws (the new layer's starting weights, the order of the batches, the augmentations), so a gap of one or two images can reverse with another seed. Trust a clear gap, or one that holds across a few seeds. Such a run repeats on one machine and one library version; another machine may give slightly different digits.

True or false?

If the fine-tuned model scores slightly lower on the validation set than the model with only a trained final layer, the right result to keep is the first-stage model.

True. The validation accuracy is the judge. Fine-tuning that does not beat the first stage added cost and overfitting risk for nothing.

Fine-tuning always improves on training only the final layer, as long as the learning rate is small enough.

False. A small learning rate makes damage less likely, but a small dataset can still be overfitted. Official examples show fine-tuning ending below the head-only result.