Representations, Transfer & Inductive Bias
What networks learn, and how to reuse it.
A trained network is two models stacked together: a feature extractor and a simple classifier on top. Keep the first, replace the second, and a network trained on millions of photographs becomes a classifier for a task with only a few thousand labeled images. This lesson makes "representation" precise, derives the self-supervised objectives that produce good ones, compares the ways to reuse them, explains why a network's confidence is not a probability you can trust, and reads architectures as assumptions about the data.
What you’ll learn
- Split a classifier into a trained feature extractor and a linear head, and test what a representation contains with a linear probe.
- Derive the objectives of self-supervised pretraining: masked prediction and the contrastive InfoNCE loss.
- Compare feature extraction, full fine-tuning and parameter-efficient fine-tuning by cost and behavior.
- Explain why softmax confidences need not be calibrated, and distinguish aleatoric from epistemic uncertainty.
- Count the parameters that weight sharing saves in a convolutional layer, and prove that reordering the inputs of self-attention, with no positional encoding added, only reorders its outputs.
A network is a feature map plus a head
Cut a classification network just below its output layer. The layers under the cut turn an input into a vector , and the output layer is ordinary multinomial logistic regression on that vector:
Basis-function and kernel methods fix the feature map in advance. A network learns and together, so training searches for features that make the classes linearly separable at the top: representation learning (Bengio, Courville & Vincent, 2013). In image networks the learned features follow a recognizable progression, from first-layer filters resembling Gabor filters and color blobs (Yosinski, Clune, Bengio & Lipson, 2014) to detectors of object parts in deeper layers.
Discrete inputs get the same treatment. A word from a vocabulary of words is a one-hot vector , and a first linear layer maps it to , the -th column: an embedding table. Training places items that behave alike close together, measured by the cosine of the angle between their vectors, and in trained word embeddings some relations even become consistent directions (Mikolov et al., 2013).
Alain & Bengio (2016) proposed a simple test of what a layer encodes: keep frozen and train only a linear classifier on to predict some property. Such a linear probe scores well when a linear map can read the property off the features. Success is evidence of presence, not of use: the output may ignore that information entirely, and only an intervention (removing or altering the information and watching the output) tests use. Probes are kept linear because a flexible enough probe can learn the property by itself.
Pretraining without labels
Labels are expensive and raw data are plentiful. Self-supervised pretraining invents a prediction task from the data itself, trains a network on it at scale, and keeps the feature map. Two families dominate.
Predict what is hidden. BERT (Devlin, Chang, Lee & Toutanova, 2019) selects 15% of the token positions of its input, hides most of them behind a special mask token (a few are swapped for random tokens or left as they are), and predicts the original token at each selected position from the rest; with the selected positions, the loss is . Autoregressive language models predict each token from the ones before it, . Doing either well requires features that capture syntax, word meaning and many facts.
Tell matching views apart. SimCLR (Chen, Kornblith, Norouzi & Hinton, 2020) draws a batch of images and makes two randomly augmented views of each, views in all. Each view passes through an encoder and then a small projection head, giving a vector . The two views of one image are a positive pair, and every other view in the batch is a negative.
SimCLR is trained with a batch of images, two views each. How many negatives does each view's loss term contain?
Show the answer
510
There are views. Excluding the view itself and its positive partner leaves negatives, so the softmax in runs over 511 candidates. Chen et al. found that contrastive learning benefits from larger batches more than supervised learning does: a larger batch supplies more negatives, which in their experiments made training converge in fewer epochs.
Chen et al. also found that the composition of augmentations matters a great deal. Their widest encoder, a ResNet-50 with every layer widened fourfold, reached 76.5% top-1 ImageNet accuracy with a linear probe on its frozen features, on par with a standard ResNet-50 trained on all the labels. As of the mid-2020s, starting from a pretrained network rather than from random weights is the norm in vision and language, and reusing it is transfer learning.
Reusing a representation
| Strategy | What is trained | Suits | Risk |
|---|---|---|---|
| Feature extraction (linear probe) | only a new head on frozen features | very little target data; a target domain resembling the pretraining data | the frozen features may lack what the target needs |
| Full fine-tuning | every layer, usually with a small learning rate | enough target data; the best in-distribution accuracy | overfitting small datasets; distorting features that mattered out of distribution |
| Parameter-efficient fine-tuning | small added modules (adapters) or low-rank weight updates (LoRA) | many tasks sharing one large backbone | occasionally below full fine-tuning |
import torch
from torchvision.models import resnet50, ResNet50_Weights
n_classes = 3 # classes of the target task
net = resnet50(weights=ResNet50_Weights.IMAGENET1K_V2) # ImageNet-pretrained backbone
net.fc = torch.nn.Linear(net.fc.in_features, n_classes) # fresh output layer
# Stage 1, linear probe: only the new output layer learns.
net.requires_grad_(False)
net.fc.requires_grad_(True)
opt = torch.optim.SGD(net.fc.parameters(), lr=0.1, momentum=0.9)
# ... train until the head has converged ...
# Stage 2, fine-tuning: every layer learns, the backbone with smaller steps.
net.requires_grad_(True)
backbone = [p for name, p in net.named_parameters() if not name.startswith('fc.')]
opt = torch.optim.SGD([{'params': backbone, 'lr': 1e-3},
{'params': net.fc.parameters(), 'lr': 1e-2}], momentum=0.9)Fitting the output layer before unfreezing the backbone ("LP-FT": linear probing, then fine-tuning) keeps the large gradients of an untrained head away from the pretrained features. Transfer Learning & Fine-Tuning shows why this protects out-of-distribution accuracy.
How general are learned features? Yosinski et al. (2014) split ImageNet's classes into two halves, trained on one and transferred layers to the other. First-layer features were general, later layers increasingly specific to their task; transfer worked less well the more distant the tasks, but even features from a distant task beat random ones; and initializing with transferred weights and then fine-tuning gave a boost to generalization that lingered after fine-tuning. When source and target differ too much, transfer can also hurt ("negative transfer").
You have 500 labeled chest X-rays and a ResNet pretrained on ImageNet photographs. What is the most sensible first approach?
- Train the ResNet from random initialization on the 500 images
- Fine-tune all layers with the learning rate used for ImageNet training
- Train a new head on the frozen pretrained features, then consider fine-tuning everything with a small learning rate
- Pretrain a new network from scratch on the 500 X-rays with a self-supervised loss
Show the answer
C. Train a new head on the frozen pretrained features, then consider fine-tuning everything with a small learning rate
With 500 examples, the pretrained features are the most valuable thing you have. A probe tells you how far they go on their own; careful fine-tuning can then adapt them without destroying them. Whether ImageNet features help on medical images is an empirical question, and the probe answers it cheaply.
Confident is not the same as correct
A softmax output is positive and sums to one, so it looks like a probability. Nothing forces it to behave like one. Multiply all the logits by : the largest probability, the network's confidence, rises toward 1 for every input, yet no prediction changes. And on a training set that the network classifies perfectly, cross-entropy keeps rewarding larger logits. Guo, Pleiss, Sun & Weinberger (2017) found that modern networks, deeper and wider and trained with batch normalization and little weight decay, are markedly overconfident, unlike networks of a decade earlier. Their fix is one parameter: divide the logits by a temperature fitted on held-out data. Since every logit is divided by the same , the ranking of the classes, and therefore the accuracy, does not change.
Calibration on held-out data from the training distribution is only half the story. Uncertainty comes in two kinds:
- Aleatoric uncertainty is noise in given : overlapping classes, ambiguous images, label noise. More data does not remove it.
- Epistemic uncertainty is ignorance about the right model, because the data are limited. It shrinks with more data, and it should be large for inputs unlike anything seen in training.
A single softmax vector cannot tell the two apart, and a temperature fitted in-distribution does not fix behavior far from the data: moving out along almost any ray from the origin, a ReLU network eventually becomes arbitrarily confident (Hein, Andriushchenko & Bitterwolf, 2019). Capturing epistemic uncertainty takes several plausible models, as in deep ensembles, MC dropout and Bayesian neural networks; conformal prediction adds distribution-free coverage guarantees on top of any model.
Architecture is an assumption
Every architecture builds in an inductive bias. Compare two ways to map a RGB image to 16 feature maps of the same size. A fully connected layer needs million weights. A convolutional layer assumes locality (each output looks at a small neighborhood) and weight sharing (the same filter at every position).
A convolutional layer with filters maps a 3-channel image to 16 channels, with one bias per output channel. What is its total parameter count?
Show the answer
448
Each of the 16 filters has weights plus a bias: parameters, about 100,000 times fewer than the fully connected layer. The count would be the same for a image.
A transformer makes a different assumption. Self-attention on token vectors , with every token attending to every token (no causal mask), computes with , , , the softmax applied row by row. Token order plays no role in this computation, as a short derivation shows.
Reorder the tokens with a permutation matrix . The queries, keys and values are reordered the same way, so the score matrix is permuted on both sides:
Reordering the rows of a score matrix, and the entries inside every row by the same permutation, only reorders the outputs of a softmax taken row by row: . With :
So without positional information a transformer treats its input as a set: reordering the words just reorders the outputs. Positional encodings added to the token vectors (Vaswani et al., 2017) break this symmetry and let order matter; so does a causal mask, which lets each token attend only to earlier ones. Graph neural networks (GNNs) build in the symmetry that matters for graphs instead: renumbering the nodes permutes the per-node outputs and leaves whole-graph outputs unchanged.
Key takeaways
- Below its output layer, a classifier is a trained feature extractor , and the output layer is a linear head on top. Embeddings are the first layer for discrete inputs, and linear probes test what the features make linearly decodable.
- Self-supervised pretraining learns features from unlabeled data, by predicting masked or next tokens or by contrasting augmented views with the InfoNCE loss over negatives.
- Reuse ranges from a linear probe through parameter-efficient methods to full fine-tuning; training the head first protects the pretrained features.
- Softmax confidences need not be calibrated; temperature scaling fixes in-distribution calibration without changing accuracy, but epistemic uncertainty, the kind that shrinks with data, needs several plausible models.
- Architectures are assumptions: convolutions build in locality and translation equivariance with a tiny fraction of a dense layer's weights; self-attention is permutation-equivariant until positional encodings break the symmetry.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
What does a linear probe on a frozen hidden layer measure?
- Whether the network's output depends causally on the probed property
- How well the property can be read out of the layer by a linear map
- The number of features in the layer
- How well the whole network would do after fine-tuning
Show the answer
B. How well the property can be read out of the layer by a linear map
The probe is a linear classifier trained on the frozen features; its accuracy measures linear decodability. Use, causation and fine-tuned performance are different questions.
In contrastive pretraining such as SimCLR, which design choice most directly determines what information the learned features keep?
- The number of negatives in each batch
- The temperature of the loss
- The depth of the encoder
- The augmentations used to create the two views
Show the answer
D. The augmentations used to create the two views
The loss can be driven down only by features that identify a view's partner despite the augmentations, so the features become insensitive to whatever the augmentations change (crop position, color) and keep what they preserve. Chen et al. found the composition of augmentations critical to the quality of the representation.
Which kind of uncertainty should shrink as you collect more training data from the same distribution?
- Epistemic uncertainty, the uncertainty about which model is right
- Aleatoric uncertainty, the noise in given
- Both shrink at the same rate
- Neither: uncertainty depends only on the architecture
Show the answer
A. Epistemic uncertainty, the uncertainty about which model is right
More data pins down the model, reducing epistemic uncertainty; the inherent noise of given stays whatever it is. An image that is genuinely ambiguous stays ambiguous however many others you see.
A transformer encoder (full self-attention, no causal mask) without positional encodings is given the sentence "dog bites man" and then "man bites dog". What can you say about its outputs?
- They are identical vectors in the same order
- They are completely unrelated
- The output vectors for each word are the same in both cases, just listed in a different order
- The second output is the first reversed in each coordinate
Show the answer
C. The output vectors for each word are the same in both cases, just listed in a different order
Self-attention is permutation-equivariant, , and so are the token-wise layers around it. Each word's output depends on the set of words, not on their order, so the two sentences produce the same vectors in permuted positions. Positional encodings are what let the model tell them apart.
A network is calibrated by temperature scaling on held-out data from its training distribution. Which statement is true?
- It is now calibrated on any input, including inputs far from the training data
- Its accuracy has improved
- Its predicted classes have changed on about half of the inputs
- It can still be highly confident on inputs unlike anything it was trained on
Show the answer
D. It can still be highly confident on inputs unlike anything it was trained on
One temperature fitted in-distribution rescales all logits uniformly. It cannot create the epistemic uncertainty a model should express on unfamiliar inputs, where ReLU networks can be arbitrarily confident.
Go deeper
- Transfer Learning & Fine-Tuning · Reusing features across tasks, and when it fails.
- Uncertainty in Neural Networks · Deep ensembles, MC dropout and Bayesian neural networks.
- Architectures as Inductive Bias · Invariance and equivariance: why CNNs, GNNs and transformers look the way they do.
Further reading
- Y. Bengio, A. Courville & P. Vincent, "Representation learning: a review and new perspectives," IEEE Transactions on Pattern Analysis and Machine Intelligence 35(8), 1798–1828 (2013).
- J. Yosinski, J. Clune, Y. Bengio & H. Lipson, "How transferable are features in deep neural networks?," NeurIPS (2014).
- T. Chen, S. Kornblith, M. Norouzi & G. Hinton, "A simple framework for contrastive learning of visual representations," ICML (2020).
- C. Guo, G. Pleiss, Y. Sun & K. Q. Weinberger, "On calibration of modern neural networks," ICML (2017).