Transfer Learning: Feature Extraction vs Fine-Tuning

How transfer learning works in practice: feature extraction vs fine-tuning, which layers to freeze, learning rates, domain shift and negative transfer.

By AI Agents DirectoryLast checked
A blue mannequin head against a purple background

Transfer learning means reusing what a model learned on one problem to get a head start on another. Instead of training a network from random weights, you start from one that was already trained on a large dataset such as ImageNet, then adapt it to your own task, which usually has far less labelled data. This guide covers the two main ways to do that, how to decide which layers to freeze, what learning rates the official tutorials use, and the situations where transfer stops helping. It is based on the PyTorch, Keras and TensorFlow transfer learning tutorials, the Hugging Face fine-tuning docs, and a few primary papers.

Why pretrained features carry over

Yosinski et al. (2014) looked at how general or task-specific the features in each layer of a convolutional network are. Networks trained on natural images tend to learn very similar first-layer features, things like Gabor-style edge filters and colour blobs, regardless of the dataset. Those early features are general. By the final layer the features have become specific to the original task. Somewhere in between, they shift from one to the other.

The TensorFlow tutorial turns this into practical advice. Early layers pick up simple patterns that apply to almost any image, while higher layers become steadily more tied to the classes the model was originally trained on. The final classification layer is the most specific of all, which is why it is almost always thrown away and replaced.

Two strategies: feature extraction and fine-tuning

The PyTorch tutorial names two main scenarios, and the Keras and TensorFlow guides describe the same split.

Feature extractionFine-tuning
Pretrained weightsFrozenSome or all are updated
What trainsOnly the new head (classifier)New head plus unfrozen base layers
Training costLower: no gradients through the frozen baseHigher: gradients flow through more of the network
Overfitting riskLowerHigher, especially with small datasets
Learning rateNormal for the headMuch lower for the unfrozen layers

Feature extraction treats the pretrained network as a fixed encoder. You freeze every layer, swap the last layer for a new one sized to your classes, and train only that new layer.

Fine-tuning starts from the same pretrained weights but lets the optimiser keep updating them, either for the whole network or for the top layers only.

Keras also describes a cheaper variant of feature extraction: run your dataset through the frozen base once, save the outputs, and train a small model on those stored features. That avoids a forward pass through the base on every epoch. The catch is that you can no longer apply data augmentation on the fly, and augmentation matters a lot when datasets are small, so the Keras guide focuses on the version where the frozen base sits inside the model.

A working example in PyTorch

The PyTorch tutorial trains a classifier for ants versus bees, a small subset of ImageNet with about 120 training images and 75 validation images per class. Both strategies start from a ResNet-18 loaded with ImageNet weights. The lines that differ are the ones that matter:

import torch.nn as nn
import torch.optim as optim
import torchvision
from torch.optim import lr_scheduler

# Fine-tuning: replace the head, optimise every parameter
model_ft = torchvision.models.resnet18(weights='IMAGENET1K_V1')
model_ft.fc = nn.Linear(model_ft.fc.in_features, 2)
optimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9)

# Feature extraction: freeze everything, then add a new trainable head
model_conv = torchvision.models.resnet18(weights='IMAGENET1K_V1')
for param in model_conv.parameters():
    param.requires_grad = False
model_conv.fc = nn.Linear(model_conv.fc.in_features, 2)  # new layer is trainable
optimizer_conv = optim.SGD(model_conv.fc.parameters(), lr=0.001, momentum=0.9)

# Both runs decay the learning rate by 0.1 every 7 epochs
scheduler = lr_scheduler.StepLR(optimizer_conv, step_size=7, gamma=0.1)

Two details are worth noticing. Setting requires_grad = False stops PyTorch from computing gradients for those parameters in the backward pass, and the new nn.Linear layer is trainable by default because it was created after the freeze. In the feature extraction run, the optimiser is also given only model_conv.fc.parameters().

The tutorial runs both for 25 epochs. It estimates 15 to 25 minutes on CPU for full fine-tuning (under a minute on a GPU) and says the frozen version takes about half as long on CPU. The forward pass still runs through the whole network; only the backward pass is skipped for the frozen layers.

Freezing layers in Keras, and the BatchNorm trap

In Keras, freezing is done with the trainable attribute. Setting layer.trainable = False moves its weights to the non-trainable list, and setting it on a model freezes every sublayer as well. The Keras guide recommends a two-stage workflow:

  1. Load a base model with pretrained weights and include_top=False, then set base_model.trainable = False.
  2. Add a new head on top, compile and train until it converges.
  3. Optionally set base_model.trainable = True, compile again, and train end to end at a very low learning rate.

Two rules are easy to miss. First, changes to trainable only take effect after you call compile() again. Second, BatchNormalization layers need care. They hold running mean and variance statistics that are not trained by gradient descent. When you unfreeze the base for fine-tuning, both Keras and TensorFlow tell you to keep those layers in inference mode by calling the base model with training=False. If you don’t, the statistics get updated on your small dataset and can wreck what the model learned.

The TensorFlow tutorial shows partial fine-tuning on MobileNetV2: it unfreezes the base, then refreezes every layer below index 100 (fine_tune_at = 100) so only the top part adapts. Its reasoning is that you want to adjust the specialised upper features to your data without overwriting the generic ones underneath.

Choosing a learning rate

Every official example uses a smaller learning rate once pretrained weights are being updated:

SourceStageLearning rate
PyTorch tutorialFine-tuning ResNet-18 (SGD, momentum 0.9)0.001, decayed by 0.1 every 7 epochs
TensorFlow tutorialTraining the head (Adam)0.0001
TensorFlow tutorialFine-tuning top layers (RMSprop)0.0001 divided by 10
Keras guideFine-tuning the whole base (Adam)1e-5
Hugging Face Trainer exampleFine-tuning Qwen3-0.6B2e-5

The reason is the same in each guide. During fine-tuning you are training a much bigger model than the head alone, often on a small dataset, so large updates overfit quickly and can erase useful pretrained features. Keras adds a sequencing rule: only unfreeze after the new head has converged. A freshly initialised head produces large gradients, and if those flow into the pretrained layers they can destroy the features you wanted to keep.

Domain shift and when transfer fails

Transfer works best when source and target data look alike. Yosinski et al. found that the further the target task is from the source task, the less transferable the features become. They also found that features from a distant task can still be better than random initialisation, and that starting from transferred weights could improve generalisation even after full fine-tuning.

The same paper identifies two separate reasons transfer degrades. One is expected: upper layers are specialised to the original task. The other was a surprise: cutting a network between layers whose neurons were co-adapted causes optimisation trouble. Which one dominates depends on whether you transfer from the bottom, middle or top of the network.

At the extreme is negative transfer, where the source knowledge actively hurts the target task. Wang et al. (2019) note that this tends to happen when the source domain is less related to the target, give it a formal definition, and propose filtering out unrelated source data using adversarial networks.

Practical checks that follow from this:

  • Always compare against a baseline trained from scratch (or a simpler model) on the same validation split. Without one, you cannot tell whether transfer helped.
  • Prefer a pretrained model whose training data resembles yours. The TensorFlow tutorial recommends fine-tuning when your dataset is large and very similar to the original.
  • With a small dataset, keep most of the base frozen and fine-tune only a few top layers, as the TensorFlow tutorial does, and watch the gap between training and validation loss.
  • Keep careful records of which base checkpoint, frozen layers and learning rates produced each run. Our guide to AI model versioning covers how to track this.

How this relates to LLM fine-tuning

Fine-tuning a large language model is the same idea at a different scale. The Hugging Face docs describe fine-tuning as continuing to train a pretrained model on a smaller dataset for a particular task or domain, and note that it uses much less compute, data and time than pretraining. ULMFiT by Howard and Ruder (2018) was an early proof that the computer vision recipe carries over to NLP. They reported that with only 100 labelled examples their method matched training from scratch on 100 times more data.

What changes with LLMs is mostly cost. Hugging Face’s PEFT library exists because updating every parameter of a large model is often too expensive. Its methods train only a small number of extra parameters while the pretrained weights stay put, which is close in spirit to feature extraction, yet the docs say the results can be comparable to full fine-tuning. Our PEFT tutorial explains those methods, and the guide to fine-tuning domain-specific AI agents covers when to fine-tune versus prompt or use RAG, how to build the dataset and how to serve the result. For serving and training infrastructure more broadly, see the LLM infrastructure hub.

#Transfer learning#Fine-tuning#PyTorch#Keras#Deep learning
AI

Written by AI Agents Directory

Editorial team

Facts in this guide are checked against official documentation and repositories, which are linked in the article.