TExcelTAD

Transfer Learning: Why Reuse Works

You need a classifier for five kinds of handwritten symbol and you have 25 labelled examples. A network trained from scratch on 25 images learns little. But somebody already trained a network on thousands of images of other symbols, and the strokes, curves and loops it learned to detect are the same building blocks your symbols are made of. Transfer learning reuses what a model learned on a source task to learn a target task with less data, less compute or both.

The idea

A trained network is a stack of feature detectors. In an image model the first layers respond to edges and colour blobs, the middle layers to textures and parts, the last layers to whole objects of the training classes. The lower and middle layers are useful for almost any image task; only the top is specific. Language models behave the same way: lower layers encode word pieces and syntax, upper layers task-specific meaning.

source large data set backbone: edges, textures, parts source head (1000 classes) copy the weights thrown away target small data set same backbone (frozen or tuned) new head (your classes) only the new head starts from random weights

Definitions

A domain is an input space with its distribution, D=(X,P(X))\mathcal{D} = (\mathcal{X}, P(X)); a task is a label space with the conditional distribution to learn, T=(Y,P(Y∣X))\mathcal{T} = (\mathcal{Y}, P(Y \mid X)). Transfer learning uses a model trained on a source pair (DS,TS)(\mathcal{D}_S, \mathcal{T}_S) to help learn a target pair (DT,TT)(\mathcal{D}_T, \mathcal{T}_T). Write the source model as a head on top of a feature map, fS=gS∘ϕf_S = g_S \circ \phi. The target model keeps ϕ\phi and learns a new head:

fT(x)=gT(ϕ(x)),ϕ copied from fS,gT newf_T(\mathbf{x}) = g_T(\phi(\mathbf{x})), \qquad \phi \text{ copied from } f_S, \quad g_T \text{ new}

What happens to ϕ\phi next names the variant:

Variant ϕ\phi during target training Lesson
Feature extraction frozen: only gTg_T learns Feature Extraction
Partial fine-tuning the top layers of ϕ\phi learn, the bottom stays frozen Partial Fine-Tuning
Full fine-tuning all of ϕ\phi learns, with a small learning rate Fine-Tuning
Parameter-efficient ϕ\phi frozen, small added modules learn LoRA, Adapters

Transfer helps when the source features are relevant to the target. When they are not, it can hurt: negative transfer, a target model that is worse than one trained from scratch.

A transfer experiment you can run

The 8 x 8 digits from scikit-learn, split in half. The source half keeps its labels, the digit 0 to 9, and trains an MLP with one hidden layer of 64 ReLU units; that hidden layer is the backbone ϕ\phi. The target task is a different question about the other half of the images: is the digit a prime (2, 3, 5, 7)? Only a handful of target images are labelled. The rest are the test set. Same input domain, new task, few labels: the situation of a team reusing an ImageNet model for its own classes.

Four ways to learn the target, for 10 to 100 labels, each averaged over 5 random draws of the labelled images:

python · try it yourself
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.linear_model import LogisticRegression

X, y = load_digits(return_X_y=True)
X = X / 16.0
X_src, X_tgt, y_src, digit_tgt = train_test_split(X, y, test_size=0.5, random_state=0, stratify=y)
y_tgt = np.isin(digit_tgt, [2, 3, 5, 7]).astype(int)       # target task: prime digit or not

# the source model is trained once, on the source half and the source task only
source = MLPClassifier(hidden_layer_sizes=(64,), max_iter=500, random_state=0).fit(X_src, y_src)
W1, b1 = source.coefs_[0], source.intercepts_[0]
phi = lambda A: np.maximum(0, A @ W1 + b1)                 # the backbone: the hidden ReLU layer

def finetune(Xl, yl, rng, epochs=200, lr=0.1):
    """Copy the backbone, add a new random 2-class head, train everything."""
    V1, c1 = W1.copy(), b1.copy()
    V2, c2 = rng.normal(0, 0.1, (64, 2)), np.zeros(2)
    for _ in range(epochs):
        h = np.maximum(0, Xl @ V1 + c1)
        z = h @ V2 + c2
        p = np.exp(z - z.max(1, keepdims=True)); p /= p.sum(1, keepdims=True)
        g = p.copy(); g[np.arange(len(yl)), yl] -= 1; g /= len(yl)
        gh = g @ V2.T * (h > 0)
        V2 -= lr * h.T @ g; c2 -= lr * g.sum(0)
        V1 -= lr * Xl.T @ gh; c1 -= lr * gh.sum(0)
    return lambda A: (np.maximum(0, A @ V1 + c1) @ V2 + c2).argmax(1)

print(f"source model, digit accuracy on its training half: {source.score(X_src, y_src):.3f}")
print("labels | scratch logistic | scratch MLP | frozen features | fine-tuned")
for n in [10, 20, 40, 100]:
    r = {k: [] for k in ("log", "mlp", "frozen", "ft")}
    for seed in range(5):
        rng = np.random.default_rng(seed)
        lab = np.concatenate([rng.choice(np.where(y_tgt == c)[0], n // 2, replace=False) for c in (0, 1)])
        test = np.setdiff1d(np.arange(len(y_tgt)), lab)
        Xl, yl, Xte, yte = X_tgt[lab], y_tgt[lab], X_tgt[test], y_tgt[test]
        r["log"].append(LogisticRegression(max_iter=2000).fit(Xl, yl).score(Xte, yte))
        r["mlp"].append(MLPClassifier(hidden_layer_sizes=(64,), max_iter=2000, random_state=seed).fit(Xl, yl).score(Xte, yte))
        r["frozen"].append(LogisticRegression(max_iter=2000).fit(phi(Xl), yl).score(phi(Xte), yte))
        r["ft"].append((finetune(Xl, yl, rng)(Xte) == yte).mean())
    print(f"{n:6d} | {np.mean(r['log']):16.3f} | {np.mean(r['mlp']):11.3f} | {np.mean(r['frozen']):15.3f} | {np.mean(r['ft']):10.3f}")
source model, digit accuracy on its training half: 1.000
labels | scratch logistic | scratch MLP | frozen features | fine-tuned
    10 |            0.750 |       0.764 |           0.816 |      0.819
    20 |            0.837 |       0.848 |           0.881 |      0.879
    40 |            0.876 |       0.892 |           0.918 |      0.916
   100 |            0.906 |       0.922 |           0.936 |      0.941

Read the table by rows. With 10 labels the reused backbone lifts accuracy from 0.750 (logistic regression on pixels) to 0.816; with 20 labels from 0.837 to 0.881. The gain shrinks as labels grow, to about 0.03 at 100 labels: transfer is worth most where labels are scarcest. Here fine-tuning the whole network and training a head on frozen features are tied, which is typical with very few labels: there is not enough data to improve 4,000 backbone weights without overfitting them. Each test set is the rest of the 899 target images (799 to 889 of them), so a difference of 0.01 is about 8 or 9 images.

Negative transfer

Transfer works because the source features are relevant. Train the same source network on the same images with shuffled labels: it still learns hidden features (it tries to memorise), but they no longer describe strokes and shapes.

python · try it yourself
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.exceptions import ConvergenceWarning
import warnings
warnings.filterwarnings("ignore", category=ConvergenceWarning)   # shuffled labels cannot be fitted: expected

X, y = load_digits(return_X_y=True)
X = X / 16.0
X_src, X_tgt, y_src, digit_tgt = train_test_split(X, y, test_size=0.5, random_state=0, stratify=y)
y_tgt = np.isin(digit_tgt, [2, 3, 5, 7]).astype(int)
labels = {"real labels": y_src, "shuffled labels": np.random.default_rng(0).permutation(y_src)}
for name, ys_used in labels.items():
    src = MLPClassifier(hidden_layer_sizes=(64,), max_iter=500, random_state=0).fit(X_src, ys_used)
    W1, b1 = src.coefs_[0], src.intercepts_[0]
    phi = lambda A: np.maximum(0, A @ W1 + b1)
    accs = []
    for seed in range(5):
        rng = np.random.default_rng(seed)
        lab = np.concatenate([rng.choice(np.where(y_tgt == c)[0], 10, replace=False) for c in (0, 1)])
        test = np.setdiff1d(np.arange(len(y_tgt)), lab)
        head = LogisticRegression(max_iter=2000).fit(phi(X_tgt[lab]), y_tgt[lab])
        accs.append(head.score(phi(X_tgt[test]), y_tgt[test]))
    print(f"source on {name:15s}: fits its own labels {src.score(X_src, ys_used):.2f}"
          f" | target accuracy, 20 labels, frozen features {np.mean(accs):.3f}")
source on real labels    : fits its own labels 1.00 | target accuracy, 20 labels, frozen features 0.881
source on shuffled labels: fits its own labels 0.62 | target accuracy, 20 labels, frozen features 0.761

The network cannot fit shuffled labels (0.62 on its own training data instead of 1.00), and the features it learned while trying are worse than raw pixels: 0.761 with 20 labels, against 0.837 for logistic regression on the pixels and 0.881 with the real backbone. That is negative transfer.

The same thing happens, more quietly, when the source domain is far from the target: ImageNet features help less on spectrograms or satellite infrared bands than on photos, and a model pretrained on English news helps less on source code or chemistry notation. Always compare with a from-scratch baseline.

The transfer-learning workflow

  1. Pick a source model trained on data as close to yours as possible (natural photos, medical images, legal text, code), with a licence that allows your use. Check its input format: image size and normalisation, tokenizer, sampling rate.
  2. Replace the head: remove the source output layer and add one with your number of classes, initialised at random.
  3. Train the head first with the backbone frozen, so the random head's large early gradients do not wreck the pretrained features.
  4. Optionally unfreeze the top of the backbone, or all of it, and continue with a learning rate 10 to 100 times smaller.
  5. Validate against a baseline trained from scratch (and a frozen-feature baseline), and stop early on the validation metric.

The next lesson runs exactly these steps on a pretrained ResNet-18.

Advantages and limits

Advantages Limits
Good accuracy from a few dozen to a few hundred labels Inherits the source model's biases, blind spots and licence terms
Much less compute than training from scratch Input format is fixed by the source (image size, tokenizer, channels)
Training is more stable: the features are already sensible Negative transfer when the domains differ too much
Pretrained models exist for images, text, audio, code, proteins Large backbones are slow at inference even if training was cheap

Practice

  1. In the first example, why are the labels drawn half from each class instead of at random?
  2. Why do the source model and the target task use different halves of the images?
  3. A colleague reports 0.99 for "transfer: fine-tuned" after choosing the number of epochs that gave the best test accuracy. What is wrong?
Answers
  1. With 10 random draws one class might get one or zero examples; balanced draws keep the comparison about the strategy, not about the luck of the draw. Repeating over 5 draws shows how much the result still varies.
  2. If the backbone had been trained on the test images, it would have seen them (with their digit, which decides the target label) before the test. The experiment would measure leakage, not transfer.
  3. The test set was used to make a choice, so its score is optimistic. The number of epochs must be chosen on a validation set (with so few labels, cross-validation on the labelled examples), and the test set used once.

Test yourself

What is replaced when a pretrained image classifier is transferred to a new set of classes?

  1. The first convolution layer
  2. The output head, which is replaced by a new one sized for the target classes
  3. The whole network
  4. Only the batch-normalisation layers

Which statement describes negative transfer?

  1. The target model is trained with a negative learning rate
  2. Using source features makes the target model worse than training from scratch
  3. The source and target share no labels
  4. The target data set has more examples than the source

Why is the new head trained first with the backbone frozen?

  1. To save disk space
  2. A randomly initialised head sends large, noisy gradients back that can damage the pretrained features
  3. Because frozen layers train faster
  4. The backbone cannot be trained