Skip to main content

11 - Transfer Learning and Fine-Tuning: Reusing a Model

See transfer learning measured: pre-trained features beat raw pixels and random weights with few labels, plus fine-tuning and an unexecuted PyTorch schema.

What do you think about this article?

At a Glance

See transfer learning measured: pre-trained features beat raw pixels and random weights with few labels, plus fine-tuning and an unexecuted PyTorch schema.

Starting from what another model has already learned

Training an image or text model from scratch requires millions of examples and days of computation. Transfer learning avoids starting over: you take a model already trained on a rich task (the source), keep what it has learned that is general and adapt it to your task (the target) with few examples. The simplest comparison is hiring a person who already knows how to read: you do not teach them the alphabet, you explain your company's vocabulary. The technical foundation is that the first layers of a network learn general elements (in images, edges and color blobs) and the last ones elements specific to the original task; Yosinski and colleagues measured it layer by layer on a network trained on ImageNet. In this article you see the mechanism with an experiment that runs on this machine, and then the schema of the PyTorch version, which is not installed here. The basics of overfitting, which explain why a model from scratch struggles with few examples, are in article 8; the idea of a learned representation in forests is in the one on ensembles.

Feature extraction: freeze the body and train only the head

The simplest strategy is feature extraction. Of the pre-trained model you keep all the layers except the last (the body), use them read-only to transform the data into a new representation, and train a lightweight classifier (the new head) on that representation. The weights of the body are frozen: they are no longer updated. It works when the target has little data and resembles the source.

Many examples online simulate this technique with a PCA as the "pre-trained model", but a PCA computed on the same data as the target transfers nothing: there is no second task to learn from. The listing does the real thing, on a small scale. It splits the 1797 8x8 digit images of scikit-learn into two disjoint halves. On the first it trains a network with 64 hidden neurons to recognize the ten digits (the source). On the second it defines a new task, "even or odd", with only 10, 20, 50 or 100 labels. It compares three representations of the input: the raw pixels, the hidden layer of a network with random weights (the control, which has the same size but no knowledge) and the hidden layer of the pre-trained network.

Python - Feature extraction from a pre-trained network, with a control
import warnings
import numpy as np
from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier

warnings.filterwarnings("ignore")
X, y = load_digits(return_X_y=True)
X = X / 16.0                                              # pixels from 0 to 1

# Two disjoint halves: "a" for pre-training (10 classes), "b" for the new task
Xa, Xb, ya, yb = train_test_split(X, y, test_size=0.55, random_state=0, stratify=y)
pre = MLPClassifier(hidden_layer_sizes=(64,), max_iter=300, random_state=0).fit(Xa, ya)
print(f"pre-training: {len(Xa)} images, accuracy on the other {len(Xb)}: {pre.score(Xb, yb):.3f}")

# New task: even or odd, with very few labels
Xb_tr, Xb_te, yb_tr, yb_te = train_test_split(Xb, yb % 2, test_size=0.5, random_state=0, stratify=yb)
W1, b1 = pre.coefs_[0], pre.intercepts_[0]
estrai = lambda M: np.maximum(0, M @ W1 + b1)            # the frozen hidden layer: computation only, no training

print("labels     raw pixels    random features  pre-trained features")
for n in (10, 20, 50, 100):
    ris = {"grezzi": [], "casuali": [], "pre": []}
    for seme in range(20):
        rng = np.random.default_rng(seme)
        idx = rng.choice(len(Xb_tr), n, replace=False)
        A, t = Xb_tr[idx], yb_tr[idx]
        if len(set(t)) < 2:
            continue
        Wr = rng.normal(0, 0.3, W1.shape)                 # control: same architecture, random weights
        casuali = lambda M: np.maximum(0, M @ Wr)
        for nome, f in (("grezzi", lambda M: M), ("casuali", casuali), ("pre", estrai)):
            ris[nome].append(LogisticRegression(max_iter=2000).fit(f(A), t).score(f(Xb_te), yb_te))
    print(f"{n:9d}  {np.mean(ris['grezzi']):12.3f}  {np.mean(ris['casuali']):15.3f}  {np.mean(ris['pre']):22.3f}")

# Output:
# pre-training: 808 images, accuracy on the other 989: 0.963
# labels     raw pixels    random features  pre-trained features
#        10         0.697            0.684                   0.780
#        20         0.781            0.763                   0.850
#        50         0.849            0.831                   0.896
#       100         0.876            0.853                   0.914

The pre-trained network recognizes 96.3% of the digits it has never seen, so the source is well learned. Now the table. With 10 labels, logistic regression on the raw pixels obtains 0.697, on the random features 0.684 and on the pre-trained ones 0.780: an eight-point advantage that does not come from the size of the layer (the random layer has the same and does not help) but from what the weights have learned. The advantage remains with 20 (0.850 against 0.781) and with 50 labels (0.896 against 0.849), and shrinks at 100 (0.914 against 0.876): it is the expected trend, because with more data it is precisely the models from scratch that recover. Each figure is a mean over 20 different subsamples, and the target task is deliberately different from the source, even or odd instead of the digit. The limit: it is an experiment on a tiny network and on 8x8 images; it says that the mechanism works, not how much you will gain with your network.

Fine-tuning: letting the body adapt too

Fine-tuning unlocks some or all of the layers of the body and trains them together with the head, starting from the pre-trained weights instead of random weights. It is needed when the target is different enough from the source to require different features. The risk is erasing what the model had learned, especially if the target has little data and the learning step is large; that is why the common practice is to use a low learning rate in the body (in some cases lower than that of the head), or to unlock the layers a little at a time from the end toward the beginning. The list of unlocking strategies found in the guides is this order of caution.

Scikit-learn does not let you freeze layers of an MLPClassifier, so the listing writes the training by hand in NumPy: a network with a ReLU hidden layer and a one-output sigmoid head, in which the addestra function accepts two separate learning rates, one for the body and one for the head. With lr_corpo = 0 the body is frozen (feature extraction); with positive values it is fine-tuning. It compares four conditions on the same even/odd task: head only, fine-tuning with a body learning rate of 0.05, fine-tuning with 0.5 (like the head), and a network with the same layers trained from scratch with random weights.

Python - Fine-tuning with separate learning rates for body and head
import warnings
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier

warnings.filterwarnings("ignore")
X, y = load_digits(return_X_y=True)
X = X / 16.0
Xa, Xb, ya, yb = train_test_split(X, y, test_size=0.55, random_state=0, stratify=y)
pre = MLPClassifier(hidden_layer_sizes=(64,), max_iter=300, random_state=0).fit(Xa, ya)
Xb_tr, Xb_te, yb_tr, yb_te = train_test_split(Xb, yb % 2, test_size=0.5, random_state=0, stratify=yb)

relu = lambda z: np.maximum(0, z)

def addestra(W1, b1, A, t, lr_corpo, lr_testa, epoche=200):
    """Network: input -> 64 ReLU -> 1 sigmoid output. New head (zero weights), given body."""
    W1, b1, w2, b2 = W1.copy(), b1.copy(), np.zeros(W1.shape[1]), 0.0
    for _ in range(epoche):
        h = relu(A @ W1 + b1)
        p = 1 / (1 + np.exp(-(h @ w2 + b2)))
        g = (p - t) / len(t)                              # derivative of the log loss with respect to the score
        gh = np.outer(g, w2) * (h > 0)                    # propagated backwards to the hidden layer
        w2 -= lr_testa * (h.T @ g);  b2 -= lr_testa * g.sum()
        W1 -= lr_corpo * (A.T @ gh); b1 -= lr_corpo * gh.sum(axis=0)
    return W1, b1, w2, b2

def accuratezza(W1, b1, w2, b2, M, t):
    return np.mean((relu(M @ W1 + b1) @ w2 + b2 > 0) == t)

print("labels     head only   fine-tuning (lr 0.05)  fine-tuning (lr 0.5)  from scratch")
for n in (10, 20, 50, 100):
    r = {k: [] for k in ("testa", "ft", "ft_alto", "zero")}
    for seme in range(20):
        rng = np.random.default_rng(seme)
        idx = rng.choice(len(Xb_tr), n, replace=False)
        A, t = Xb_tr[idx], yb_tr[idx]
        if len(set(t)) < 2:
            continue
        W1, b1 = pre.coefs_[0], pre.intercepts_[0]
        Wr, br = rng.normal(0, 0.3, W1.shape), np.zeros(W1.shape[1])
        r["testa"].append(accuratezza(*addestra(W1, b1, A, t, 0.0, 0.5), Xb_te, yb_te))      # body frozen
        r["ft"].append(accuratezza(*addestra(W1, b1, A, t, 0.05, 0.5), Xb_te, yb_te))
        r["ft_alto"].append(accuratezza(*addestra(W1, b1, A, t, 0.5, 0.5), Xb_te, yb_te))
        r["zero"].append(accuratezza(*addestra(Wr, br, A, t, 0.5, 0.5), Xb_te, yb_te))      # random weights, everything trained
    m = {k: np.mean(v) for k, v in r.items()}
    print(f"{n:9d}  {m['testa']:10.3f}  {m['ft']:21.3f}  {m['ft_alto']:19.3f}  {m['zero']:7.3f}")

# Output:
# labels     head only   fine-tuning (lr 0.05)  fine-tuning (lr 0.5)  from scratch
#        10       0.783                  0.780                0.771    0.716
#        20       0.846                  0.845                0.840    0.794
#        50       0.897                  0.896                0.904    0.867
#       100       0.914                  0.918                0.928    0.898

The comparison that matters is between the first column and the last: starting from the pre-trained weights beats training from scratch with the same architecture by 6-7 points with 10 labels (0.783 against 0.716), by 5 with 20 (0.846 against 0.794) and by 3 with 50 (0.897 against 0.867). The second result is less obvious: adding fine-tuning does not improve the head alone with 10 or 20 labels (0.780 against 0.783, 0.845 against 0.846), that is where the data are very few there is nothing more to learn. With 50 and 100 labels a high learning rate in the body (0.5) even gives something more (0.904 and 0.928 against 0.897 and 0.914), and the "disaster" that theory fears is not observed: the network is small, source and target are very close and the epochs are few. Do not conclude that the learning rate does not matter: in a deep network with a source far from the target the recommendation to keep it low remains valid (the PyTorch tutorial uses 0.001), this experiment simply does not demonstrate it. With 100 labels the advantage over the model from scratch shrinks to 1.6-2 points (0.914 and 0.918 against 0.898): the data begin to be enough on their own.

The PyTorch schema with an ImageNet model

For real images the procedure is the same, with a deep network. The official PyTorch tutorial uses a ResNet-18 with weights trained on ImageNet (1.2 million images, 1000 categories) and distinguishes two scenarios: fine-tuning, in which you start from the pre-trained weights and train everything, and the network as a fixed feature extractor, in which you freeze everything except the last linear layer, replaced by a new one with 2 outputs (ants and bees, about 120 training images per class). The block that follows takes up that structure and adds the second step, unlocking only the last block with separate learning rates: it is a schema to adapt, not executed, because torch and torchvision are not installed on this machine and I did not download any weights. I report no figures.

Python - ResNet-18 in PyTorch: feature extraction and fine-tuning (schema to adapt, not executed)
import torch
import torch.nn as nn
import torchvision
from torch import optim

modello = torchvision.models.resnet18(weights="IMAGENET1K_V1")   # weights learned on ImageNet (1000 classes)

# Step 1 - feature extraction: freeze the whole body
for parametro in modello.parameters():
    parametro.requires_grad = False

# Replace the head: the new parameters have requires_grad=True by default
modello.fc = nn.Linear(modello.fc.in_features, 2)                 # 2 classes: adapt to your problem
ottimizzatore = optim.SGD(modello.fc.parameters(), lr=0.001, momentum=0.9)

# Step 2 - fine-tuning of the last block, with a lower learning rate in the body than in the head
for parametro in modello.layer4.parameters():
    parametro.requires_grad = True
ottimizzatore = optim.SGD([
    {"params": modello.layer4.parameters(), "lr": 1e-4},          # body: small steps
    {"params": modello.fc.parameters(), "lr": 1e-3},              # new head: larger steps
], momentum=0.9)

The three lines that matter are the setting of requires_grad = False, which removes the parameters from training, the replacement of fc with a new nn.Linear, whose parameters are born trainable, and the optimizer constructor, to which you pass only the parameters to update. If you forget to freeze, you are doing full fine-tuning without knowing it; if you pass the body parameters to the optimizer but you froze them, they do not move. Before adapting it change the number of outputs of fc to the number of your classes, and apply to the data the same transformations (size, normalization) with which the model was trained, described in the documentation of the weights.

Pre-trained models for text, and the cost that is avoided

In language the role of ResNet is played by transformer models such as BERT. The original BERT paper says that, apart from the output layer, the same architecture is used in pre-training and in fine-tuning, with the same weights as initialization; that the pre-training of BERT-base was done on 16 TPU chips and that of BERT-large on 64, in 4 days each; and that fine-tuning "is relatively inexpensive": all the results of the paper can be replicated in at most one hour on a single Cloud TPU, or a few hours on a GPU. That comparison is the economic reason for transfer learning. To apply it, the Hugging Face transformers library loads a pre-trained model with from_pretrained and trains it with Trainer, as the fine-tuning guide describes. I did not run any of this.

A clarification on names: "an assistant trained on your documents" can mean two different things. Fine-tuning changes the weights of the model; searching your own documents (RAG) changes no weights and consults the texts at the moment of the question. They are not synonyms and they do not have the same cost.

When it pays, and when it hurts

Transfer learning helps when you have little labeled data, the source is rich and the target resembles it, as in the first experiment. It helps less when the two tasks are far apart: Yosinski and colleagues find that transferability declines as the distance between the starting task and the arrival task increases, while remaining, even from distant tasks, better than random features. Negative transfer proper, in which starting from a model makes things worse, must be measured on your case with a comparison like the one in the first listing. Moreover, inheriting a model means inheriting its limits: the data it was trained on, the license and the biases. With an already large target (hundreds of thousands of examples), training from scratch is often competitive and sometimes preferable.

What you can do now

You can tell feature extraction and fine-tuning apart, and you can measure whether a transfer works by comparing it with two controls: the raw data and a network of the same shape with random weights. You know that the advantage is maximal when labels are few and disappears when they abound. You can read the PyTorch schema, where you freeze, where you replace the head, which parameters go to the optimizer, and where your machine must have the packages to run it. The last article of the series puts everything into production: end-to-end ML pipeline.

The learned representations this article talks about are relatives of the latent factors of recommendation systems.

Frequently asked questions

What is the difference between feature extraction and fine-tuning?

In feature extraction the body of the pre-trained model is frozen and only a new head is trained; in fine-tuning some or all of the layers of the body are trained too, starting from the pre-trained weights and usually with a low learning rate.

When is transfer learning not worth it?

When the target is very far from the source (the advantage declines with the distance between the tasks), or when the target already has very many examples: in the experiment the advantage over the model from scratch drops from 6-7 points with 10 labels to about 2 with 100.

Sources

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects