TExcelTAD
Home › Training Strategies: Transfer, Fine-Tuning, Semi-Supervised, Active, Online & Distributed › Feature Extraction: a Frozen Backbone and a Simple Classifier

Feature Extraction: a Frozen Backbone and a Simple Classifier

Fine-tuning a network means a training loop, a GPU for anything large, and a full copy of the model per task. Often you can skip all of that: run the pretrained network once over your data, keep the vector it produces just before its output layer, and train an ordinary scikit-learn classifier on those vectors. This is feature extraction: the backbone is a fixed function, z=ϕ(x)\mathbf{z} = \phi(\mathbf{x}), and only a small model on top is learned.

Why it works, and the workflow

A pretrained backbone maps raw inputs (pixels, tokens, audio samples) into an embedding space where similar things are close and the directions mean something: texture, shape, topic, sentiment. If the classes of your task are roughly linearly separable in that space, a linear classifier on z\mathbf{z} is enough:

y^=softmax⁡(Wϕ(x)+b),ϕ fixed,W,b learned\hat{y} = \operatorname{softmax}(W \phi(\mathbf{x}) + \mathbf{b}), \qquad \phi \text{ fixed}, \quad W, \mathbf{b} \text{ learned}

Training it is a convex problem (logistic regression), so it has one optimum, needs no learning-rate tuning and finishes in seconds.

  1. Choose a backbone and its preprocessing (image size and normalisation, tokenizer).
  2. Remove the head: take the output of the last hidden layer or the pooled embedding (in PyTorch, model.fc = nn.Identity()).
  3. Embed every example once, in eval() mode and under torch.no_grad(), and store the vectors.
  4. Train classical models on the stored vectors: logistic regression, linear SVM, kNN, a small MLP, gradient boosting. Cross-validate them as usual; trying another one costs seconds because the backbone does not run again.
  5. Evaluate on the test embeddings once.

From scratch: a frozen backbone as a scikit-learn transformer

A frozen backbone is just a fixed transformation, so it fits into a scikit-learn Pipeline like a scaler. The backbone here is the hidden layer of an MLP trained on one half of the digits (source task: which digit), and the target task is the one from Transfer Learning: is the digit prime, with 100 labelled images. Because ϕ\phi is fixed, cross-validating several heads on top is cheap and leak-free.

python · try it yourself
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split, cross_val_score, StratifiedKFold
from sklearn.neural_network import MLPClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC

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)
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]

class FrozenBackbone(BaseEstimator, TransformerMixin):
    """The source network's hidden layer, used as a fixed feature map."""
    def __init__(self, W, b):
        self.W, self.b = W, b                         # copied weights, never updated
    def fit(self, X, y=None):
        return self                                   # nothing to learn: frozen
    def transform(self, X):
        return np.maximum(0, X @ self.W + self.b)

rng = np.random.default_rng(0)
lab = np.concatenate([rng.choice(np.where(y_tgt == c)[0], 50, replace=False) for c in (0, 1)])
test = np.setdiff1d(np.arange(len(y_tgt)), lab)
X_lab, y_lab = X_tgt[lab], y_tgt[lab]
cv = StratifiedKFold(5, shuffle=True, random_state=0)
heads = {"logistic": LogisticRegression(max_iter=2000), "kNN (k=5)": KNeighborsClassifier(),
         "RBF SVM": SVC()}
print("5-fold CV on the 100 labelled images")
scores = {}
for name, head in heads.items():
    for feats in ("pixels", "frozen features"):
        steps = [StandardScaler(), head] if feats == "pixels" else [FrozenBackbone(W1, b1), StandardScaler(), head]
        scores[(feats, name)] = (cross_val_score(make_pipeline(*steps), X_lab, y_lab, cv=cv).mean(), steps)
    print(f"  {name:10s} pixels {scores[('pixels', name)][0]:.3f} | frozen features {scores[('frozen features', name)][0]:.3f}")
(feats, name), (cv_acc, steps) = max(scores.items(), key=lambda kv: kv[1][0])
best = make_pipeline(*steps).fit(X_lab, y_lab)            # refit the CV winner on all 100 labels
print(f"chosen by CV: {feats} + {name} -> test accuracy {best.score(X_tgt[test], y_tgt[test]):.3f} on {len(test)} images")
5-fold CV on the 100 labelled images
  logistic   pixels 0.940 | frozen features 0.930
  kNN (k=5)  pixels 0.900 | frozen features 0.980
  RBF SVM    pixels 0.910 | frozen features 0.960
chosen by CV: frozen features + kNN (k=5) -> test accuracy 0.962 on 799 images

The head matters as much as the features. On pixels, logistic regression is best (0.940); on the frozen features it is slightly worse (0.930), but kNN jumps from 0.900 to 0.980 and the RBF SVM from 0.910 to 0.960. The backbone has put images of the same digit close together, which is exactly what a nearest-neighbour vote needs. Cross-validation picks frozen features with kNN, and the single test on the 799 unlabelled images gives 0.962, against 0.906 for logistic regression on pixels with 100 labels in the transfer lesson. (With 5 folds of 20 images, each CV score moves in steps of 0.01 and is noisy; the test set is the more reliable number.)

With a pretrained ResNet-18

The same recipe with a real backbone: ResNet-18's 512-number pooled output for the texture crops of the previous lesson (six classes, 36 training and 60 test crops). fc = nn.Identity() removes the head, one pass under torch.no_grad() embeds all 96 crops, and from then on everything is scikit-learn.

python · try it yourself
import numpy as np
import torch
from torch import nn
from torchvision.models import resnet18, ResNet18_Weights
from skimage import data
from skimage.color import rgb2gray
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import LinearSVC

rng = np.random.default_rng(0)
names = ["brick", "grass", "gravel", "moon", "cell", "immunohistochemistry"]
def grey(name):
    img = getattr(data, name)()
    return (rgb2gray(img) * 255).astype(np.uint8) if img.ndim == 3 else img
def crops(img, n, left, size=48):
    half = img.shape[1] // 2
    out = []
    for _ in range(n):
        x = rng.integers(0, half - size) + (0 if left else half)
        y = rng.integers(0, img.shape[0] - size)
        out.append(img[y:y + size, x:x + size])
    return out
X_tr, y_tr, X_te, y_te = [], [], [], []
for c, name in enumerate(names):
    img = grey(name).astype(np.float32) / 255
    for p in crops(img, 6, True):   X_tr.append(p); y_tr.append(c)
    for p in crops(img, 10, False): X_te.append(p); y_te.append(c)
mean = torch.tensor([0.485, 0.456, 0.406])[:, None, None]
std = torch.tensor([0.229, 0.224, 0.225])[:, None, None]
to_tensor = lambda ps: (torch.tensor(np.stack(ps))[:, None].repeat(1, 3, 1, 1) - mean) / std

backbone = resnet18(weights=ResNet18_Weights.IMAGENET1K_V1)
backbone.fc = nn.Identity()                    # remove the head: output = 512-d embedding
backbone.eval()
with torch.no_grad():                          # one pass, no gradients, no training
    Z_tr = backbone(to_tensor(X_tr)).numpy()
    Z_te = backbone(to_tensor(X_te)).numpy()
print("embeddings:", Z_tr.shape, Z_te.shape)

heads = {"logistic regression": LogisticRegression(max_iter=5000),
         "linear SVM": LinearSVC(C=0.1, max_iter=20000),
         "kNN (k=1)": KNeighborsClassifier(n_neighbors=1)}
for name, head in heads.items():
    clf = make_pipeline(StandardScaler(), head).fit(Z_tr, y_tr)
    print(f"{name:20s} test accuracy {clf.score(Z_te, y_te):.3f}")
embeddings: (36, 512) (60, 512)
logistic regression  test accuracy 0.967
linear SVM           test accuracy 0.967
kNN (k=1)            test accuracy 0.933

Logistic regression on the frozen 512-number embeddings scores 0.967 on the 60 test crops, essentially what the trained head of the previous lesson reached (0.983, one crop apart), without a single gradient step through the network. The linear SVM ties it and 1-nearest-neighbour is close behind (0.933).

Feature extraction or fine-tuning?

Feature extraction Fine-tuning
Trained parameters the head only (thousands) all or many (millions)
Backbone passes one per example, ever one forward and backward per example per epoch
Hardware a CPU is often enough usually a GPU
Many tasks on the same data one set of embeddings serves all of them one model copy per task
Classical tools any scikit-learn model, cross-validation, calibration a deep-learning training loop
Accuracy good when the pretrained features fit the task higher when the domain or task differs from pretraining and labels are plentiful
Data augmentation weak (each augmented copy must be embedded too) natural, a new random view every epoch

A good habit is to start with feature extraction. It is a strong baseline that takes minutes, and it tells you how much the backbone already knows. If a linear head is far from good enough, fine-tune; if it is nearly there, you may be done.

Pitfalls

  • Embedding in train() mode. Dropout and batch norm behave differently in training mode; extract features in eval() and under no_grad().
  • Fitting the scaler on all embeddings. The embeddings are fixed, but a StandardScaler or PCA on top is fitted, so it belongs inside the pipeline and on training rows only.
  • Choosing the head on the test set. Comparing three heads on the test set, as the recorded example does for brevity, is a choice made with test data. With more labels, choose by cross-validation on the training embeddings.
  • Stale embeddings. If the backbone or its preprocessing changes, every stored vector must be recomputed, and the version of the backbone stored with them.

Practice

  1. In the scikit-learn example, why does FrozenBackbone.fit do nothing?
  2. You have 50,000 product photos and 20 different classification tasks on them. Why is feature extraction attractive?
  3. The kNN head with k=1k = 1 works well on the ResNet embeddings. What does that say about the embedding space?
Answers
  1. The backbone's weights are frozen: there is nothing to learn from the target data. Implementing fit as a no-op is what lets it sit inside a Pipeline and cross-validation without leaking anything.
  2. Each photo goes through the expensive backbone once; the 20 heads are then trained on the same stored vectors in seconds each, instead of fine-tuning 20 copies of a large network.
  3. Crops of the same texture land close to each other and far from the other textures: the nearest training crop almost always has the right class. The pretrained space already groups the classes.

Test yourself

In PyTorch, what does model.fc = nn.Identity() do to a torchvision ResNet?

  1. Freezes the model
  2. Removes the classification head, so the model outputs its 512-number pooled embedding
  3. Resets all weights
  4. Converts it to scikit-learn

Why is training a logistic-regression head on fixed embeddings easier than fine-tuning a network?

  1. It uses more data
  2. The problem is convex, with one optimum and no learning-rate schedule to tune
  3. It always gives higher accuracy
  4. It needs a GPU

When does fine-tuning usually beat feature extraction clearly?

  1. When there are very few labels
  2. When the target domain differs from the pretraining data and there are enough labels to adapt the backbone
  3. When the backbone is frozen
  4. Never