◆ AI All-in-One

Level 3 In-Depth AI · Deep Learning

Transfer Learning

Start from a network someone else already trained on a huge dataset, and adapt it to your problem. It turns a task that needed millions of labelled examples into one that needs hundreds.

Level
●●●●● Easy
Reading
12 min
To learn it well
45 minutes to read, an afternoon to practise
↗ Plan a path here

Read first

Training Neural Networks in Practice

This leads to

Fine-Tuning
The full path from zero — 26 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. Python for AI
  6. How Machines Learn
  7. Partial Derivatives and Gradients
  8. Matrices and Matrix Multiplication
  9. The Chain Rule
  10. Supervised, Unsupervised and Reinforcement Learning
  11. Gradient Descent
  12. Tensors and Shapes
  13. NumPy and Array Thinking
  14. Supervised Learning
  15. Linear Regression
  16. Training, Validation and Test Sets
  17. The Perceptron
  18. Logistic Regression
  19. Overfitting and the Bias–Variance Tradeoff
  20. Regularization: L1 and L2
  21. Neural Networks
  22. Backpropagation
  23. Dropout and Regularizing Neural Networks
  24. PyTorch
  25. Optimizers: SGD, Momentum and Adam
  26. Training Neural Networks in Practice
  27. Transfer Learning

Read them roughly in this order. See it on the concept map →

Why it matters

Training a good image classifier from scratch takes a lot of labelled data. The networks that first beat humans at ImageNet saw 1.28 million labelled photos and needed days of GPU time. Most real projects have nothing like that: a few hundred X-rays, a thousand product photos, two thousand customer emails.

Transfer learning is the escape. Take a network that has already been trained on a huge dataset, a pretrained model, keep what it has learned, and adapt it to your task with your small dataset. The knowledge transfers. A network that learned to recognise 1,000 kinds of everyday objects has also learned, along the way, how to detect edges, textures, shapes and parts. Those skills are useful for almost any image task, including ones it never saw.

This changed practical deep learning more than almost any architecture. From around 2014 it became the default for computer vision: start from an ImageNet-pretrained network. From 2018, with ULMFiT, BERT and GPT, it became the default for language too. Today the whole field runs on it. A foundation model is pretrained once at great expense by a large lab and then adapted, by Fine-Tuning, LoRA or just prompting, to thousands of downstream tasks. If you take one practical lesson from the deep learning part of this guide, take this one: don't train from scratch if you don't have to.

The intuition

Imagine hiring a radiologist versus hiring someone who has never seen a medical image. Neither knows your hospital's particular scanner or your rare condition. But the radiologist already knows anatomy, what normal tissue looks like, and how to read a grey-scale image. They need a few dozen examples of your rare condition. The newcomer needs years.

A pretrained network is the experienced hire. As the CNN chapter showed, a deep network learns a hierarchy: early layers detect edges and colour blobs, middle layers textures and simple shapes, later layers object parts and whole objects. Only the very last layer, the classifier head, is truly specific to the original 1,000 ImageNet classes. Everything below it, the backbone, is a general-purpose feature extractor.

So you keep the backbone, throw away the old head, and attach a new head for your own classes. Then you choose how much of the backbone to let change.

1 · Pretrainbig dataset, e.g. ImageNet image edges textures parts objects head: 1,000 classes 2a · Feature extractionfreeze the body, train a new head image edges textures parts objects new head: 4 classes 2b · Fine-tuningnew head + small learning rate image edges textures parts objects new head: 4 classes copyweightsor frozen (not updated)trained (in 2b: gently, small learning rate)new, trained from scratch
Fig. 1 Transfer learning in two steps. A network is pretrained on a big dataset. For a new task, copy its weights and replace the head. In feature extraction (2a) the whole body is frozen and only the new head learns. In fine-tuning (2b) some or all layers also learn, gently, with a small learning rate.

Key idea Transfer learning reuses a pretrained network's learned features. Replace its head, then either freeze the body and train only the new head (feature extraction) or let the body adjust too with a small learning rate (fine-tuning).

How it works

Why features transfer

In 2014 Jason Yosinski and colleagues measured how transferable each layer of an ImageNet network is. They split ImageNet's classes into two unrelated halves, trained on one half, and transplanted layers into a network for the other half. The first layers transferred almost perfectly. They are general, the same Gabor-like edge and colour detectors that appear in nearly every image network. Transferability fell gradually with depth as the features became specific to the original classes. And a surprising bonus: transplanted features that were then fine-tuned gave better results than training on the target half alone.

The same year, Ali Sharif Razavian and colleagues took features from a pretrained CNN, trained only a simple linear classifier on top, and got strong results on a wide range of vision tasks: fine-grained bird species, scenes, image retrieval. Their paper's title called it "an astounding baseline".

Option 1: feature extraction

Feature extraction freezes all the pretrained weights (sets them so they don't update) and trains only the new head.

  1. Load the pretrained network.
  2. Remove its final layer. For ResNet-50 the old head maps 2,048 features to 1,000 classes.
  3. Freeze every remaining parameter.
  4. Add a new head: a linear layer from 2,048 features to your number of classes.
  5. Train only the head.

Because only the head learns, there are very few parameters to fit: 2,048×5+5=10,2452{,}048 \times 5 + 5 = 10{,}245 for 5 classes, against about 23 million in the frozen body. That is why it works with tiny datasets and hardly overfits. It is also fast. You can even run the body once over your whole dataset, save the 2,048-number feature vector for every image, and then train a logistic regression or other small model on those features in seconds.

Option 2: fine-tuning

Fine-tuning also replaces the head, then continues training some or all of the backbone on your data. It adapts the features themselves, which helps when your images differ from the pretraining data.

Three practical rules:

  • Use a small learning rate, often 10 to 100 times smaller than for training from scratch, such as 1e-4 or 1e-5 with Adam. The pretrained weights are already good. Large steps would destroy them in the first few batches, a form of catastrophic forgetting.
  • Train the new head first. A freshly initialised head produces random, large gradients. Train it alone for an epoch or two, then unfreeze the body. Unfreezing one block at a time, from the top down, is called gradual unfreezing.
  • Use smaller learning rates for earlier layers. Early layers hold the most general features and need the least change. Giving each layer group its own rate, such as 1e-5 for the first blocks, 1e-4 for the last and 1e-3 for the head, is called discriminative learning rates. Jeremy Howard and Sebastian Ruder popularised both tricks in ULMFiT (2018).

Which to choose

The answer depends mostly on two things: how much labelled data you have, and how similar it is to what the model was pretrained on.

Fine-tune everythingsmall learning rate;pretrained start still helps Fine-tune everythingor train from scratch; a pretrainedstart often still speeds things up Feature extractionfreeze the body,train only a new head Hardest casefreeze early layers only,fine-tune gently, augment similar (e.g. photos → other photos) different (e.g. photos → X-rays) how similar is your data to the pretraining data? lots (100,000+) little (hundreds) labelled data you have
Fig. 2 A rough guide to transfer learning choices. With little data similar to the pretraining data, freeze the body and train a new head. With lots of data, fine-tune everything. Little data from a different domain is the hardest case: keep the general early layers, adapt the later ones gently, and use augmentation.

When your data looks different from the pretraining data, for example medical scans, satellite images or spectrograms versus everyday photos, this is called domain shift. The early layers (edges, textures) still transfer well. The later, more specific layers transfer less, so it pays to let them adapt.

Worked example: what does the head learn?

Suppose the frozen backbone turns each image into just two features, "roundness" and "furriness", and you want to tell cats (label 1) from mugs (label 0). Three training images come out as (0.8, 0.9) for a cat, (0.7, 0.1) for a mug and (0.6, 0.8) for another cat. The new head is a logistic regression on these two numbers. A weight vector like w=(0,5)\mathbf{w} = (0, 5) with bias −2.5-2.5 gives the scores 5×0.9−2.5=2.05 \times 0.9 - 2.5 = 2.0, 5×0.1−2.5=−2.05 \times 0.1 - 2.5 = -2.0 and 5×0.8−2.5=1.55 \times 0.8 - 2.5 = 1.5: positive for both cats, negative for the mug. With good features, the head's job is easy. Real backbones give 512 to 2,048 features instead of two, but the principle is the same. All the hard work of turning pixels into meaningful numbers was done during pretraining.

Beyond images

  • Language. A pretrained language model such as BERT or a GPT-style model is the backbone. Add a classification head, or simply fine-tune the whole model on your examples. Fine-Tuning, Instruction Tuning and Chat Models and LoRA are all forms of transfer learning. For large language models, prompting is transfer with no training at all.
  • Audio and speech. Models like Whisper are fine-tuned for new languages or accents (Speech Recognition).
  • Multimodal. CLIP's image features transfer to new classification tasks without any training, just by comparing the image with text descriptions of the classes.

In code

A small but complete demonstration that runs offline. We "pretrain" a network on 5,000 images of single lines (vertical, horizontal or diagonal) and then reuse it for a new task: tell apart four kinds of pairs of lines, with only 40 labelled examples. Three approaches are compared on 1,000 new test images:

import copy
import torch
import torch.nn as nn

torch.manual_seed(0)
def stroke(kind, n=16):
    """A 16x16 image with one line at a random offset: 0 |, 1 -, 2 \\, 3 /."""
    img, o, r = torch.zeros(n, n), torch.randint(-4, 5, (1,)).item(), torch.arange(n)
    if kind == 0: img[:, n // 2 + o] = 1
    if kind == 1: img[n // 2 + o, :] = 1
    if kind == 2: img[r, (r + o).clamp(0, n - 1)] = 1
    if kind == 3: img[r, (n - 1 - r + o).clamp(0, n - 1)] = 1
    return img
def dataset(n, task):
    X, y = [], []
    for _ in range(n):
        k = torch.randint(4, (1,)).item()
        if task == "source": img = stroke(k)                   # which single line?
        else:                                                 # which PAIR of lines?
            a, b = [(0, 2), (0, 3), (1, 2), (1, 3)][k]
            img = (stroke(a) + stroke(b)).clamp(max=1)
        X.append(img + 0.5 * torch.rand(16, 16)); y.append(k)
    return torch.stack(X), torch.tensor(y)

def train(model, X, y, steps):
    params = [p for p in model.parameters() if p.requires_grad]
    opt = torch.optim.Adam(params, lr=3e-3)
    for _ in range(steps):
        i = torch.randint(len(X), (32,))
        loss = nn.functional.cross_entropy(model(X[i]), y[i])
        opt.zero_grad(); loss.backward(); opt.step()
def accuracy(model, X, y):
    with torch.no_grad(): return (model(X).argmax(1) == y).float().mean().item()
def backbone():
    return nn.Sequential(nn.Flatten(), nn.Linear(256, 128), nn.ReLU(), nn.Linear(128, 32), nn.ReLU())

pretrained = backbone()                                       # 1. pretrain on 5,000 source images
train(nn.Sequential(pretrained, nn.Linear(32, 4)), *dataset(5000, "source"), steps=600)

X_small, y_small = dataset(40, "target")                      # 2. new task: only 40 labelled images
X_test, y_test = dataset(1000, "target")
for name in ["from scratch", "frozen features", "fine-tune all"]:
    torch.manual_seed(1)
    body = backbone() if name == "from scratch" else copy.deepcopy(pretrained)
    if name == "frozen features":
        body.requires_grad_(False)                            # only the new head will learn
    model = nn.Sequential(body, nn.Linear(32, 4))             # new head for the new classes
    train(model, X_small, y_small, steps=300)
    print(f"{name:16} test accuracy {accuracy(model, X_test, y_test):.3f}")

# from scratch     test accuracy 0.734
# frozen features  test accuracy 1.000
# fine-tune all    test accuracy 0.989

From scratch, 40 examples are not enough to learn line detectors that work at every position: 73%. Reusing the pretrained body gets essentially everything right. Fine-tuning everything with the same, fairly high learning rate does slightly worse than freezing. With so little data, the updates disturb good features a little. That is the reason for the small-learning-rate rule.

With a real pretrained network from torchvision, the recipe is the same. This needs a weights download (about 45 MB), so it isn't run here:

import torch.nn as nn
from torchvision.models import resnet18, ResNet18_Weights

weights = ResNet18_Weights.DEFAULT
model = resnet18(weights=weights)                # pretrained on ImageNet
preprocess = weights.transforms()                # the exact resizing and normalisation it expects

for p in model.parameters():                     # feature extraction: freeze everything ...
    p.requires_grad = False
model.fc = nn.Linear(model.fc.in_features, 5)    # ... then replace the 1,000-class head (512 -> 5)
# Train as usual; only model.fc has requires_grad=True.
# To fine-tune instead, unfreeze model.layer4 (the last block) and use a small learning rate.

For text, Hugging Face Transformers does the head-swapping for you: AutoModelForSequenceClassification.from_pretrained("bert-base-uncased", num_labels=2) loads BERT's body and attaches a fresh two-class head (The Hugging Face Ecosystem).

Common pitfalls

  • Wrong preprocessing. A pretrained network expects inputs prepared exactly as in its training: the same image size, the same normalisation (for ImageNet models, subtract the channel means 0.485, 0.456, 0.406 and divide by 0.229, 0.224, 0.225), the same tokenizer for text. Mismatches don't crash. They just quietly ruin accuracy. Use the transforms or tokenizer shipped with the weights.
  • Learning rate too high when fine-tuning. The loss jumps at the start of fine-tuning and validation accuracy ends up below what the frozen features gave. Lower the rate by 10×.
  • Batch normalisation in frozen networks. Freezing the weights does not freeze batch-norm's running statistics. In training mode they keep updating from your (small, different) batches. Keep frozen parts in eval() mode (Normalization Layers: BatchNorm and LayerNorm).
  • Forgetting the optimizer. If you create the optimizer before unfreezing layers, or pass it all parameters while expecting only some to change, the training won't do what you think. Rebuild the optimizer after changing what is trainable.
  • Leaking test data through the pretraining set. Popular benchmarks overlap with web-scraped pretraining data. Your score may partly reflect memorisation rather than transfer.

Watch out A pretrained model brings its pretraining data's blind spots and biases with it. An ImageNet model has seen few medical images and an unbalanced sample of the world's people and places. A language model has absorbed whatever its web text contained. Check performance on the groups and conditions you actually care about (Bias and Fairness).

Where it leads

A bit of history

The idea that learning one task should help with another is old. Lorien Pratt studied "discriminability-based transfer" between neural networks in the early 1990s, and Rich Caruana's 1997 work on multitask learning explored related ideas. The modern era began right after AlexNet. In 2013–2014, DeCAF (Donahue and colleagues), CNN Features off-the-shelf (Razavian and colleagues) and Yosinski's transferability study showed that ImageNet features worked across a wide range of vision problems, and "start from an ImageNet model" became standard practice. Language followed in 2018: ULMFiT (Howard and Ruder) showed that a pretrained LSTM language model could be fine-tuned for text classification with very few labels, and BERT and GPT turned pretrain-then-fine-tune into the dominant recipe. A 2018 study by Kaiming He and colleagues added a useful caveat: with enough target data and long enough training, models trained from scratch can catch up on some tasks. Pretraining mostly buys you speed and data efficiency.

Try it

  1. In the demo, change the 40 target examples to 400. How do the three approaches compare now? Then try 8.
  2. Fine-tune with a smaller learning rate: give train a lr argument and use 1e-3 for the "fine-tune all" case. Does it beat frozen features?
  3. Harder: add a fourth approach that unfreezes only the last Linear layer of the backbone. Where does it land?

Hint for 1: with enough data, from scratch catches up. Transfer helps most when labels are scarce.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. You have 300 labelled photos of 5 kinds of product, similar to everyday images. What is the most sensible first approach?

  2. You replace ResNet-50's head with a new linear layer for 5 classes and freeze everything else. How many parameters are trained?

  3. When you start fine-tuning a pretrained model, the loss jumps and final accuracy ends up below what frozen features gave. What should you change first?

  4. You fine-tune an ImageNet model on chest X-rays. Which layers are most likely to transfer well unchanged?

  5. You froze a pretrained CNN's weights, but its batch-norm layers are still in training mode. What goes wrong?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Course

Practical Deep Learning for Coders

Jeremy Howard (fast.ai) · Beginner · Free

Top-down and code-first: you train state-of-the-art models in lesson one, then learn how they work. It suits programmers.

Tutorial

Transfer Learning for Computer Vision Tutorial

Sasank Chilamkurthy (PyTorch) · Beginner · Free

Official PyTorch tutorial: fine-tune a pretrained ResNet, or use it as a frozen feature extractor, on a small ants-versus-bees dataset.

Course

Hugging Face LLM Course

Hugging Face · Intermediate · Free

Using Transformers, datasets and tokenizers, fine-tuning, and building with open LLMs, with runnable notebooks.

Docs

timm (PyTorch Image Models)

Ross Wightman and Hugging Face · Intermediate · Free

A library of hundreds of pretrained image backbones with a uniform API, the usual starting point for vision transfer learning.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/dl/transfer-learning.md