Key ideas
- Transfer learning starts a new model from the weights of a model pretrained on a large source dataset (e.g. ImageNet) instead of from random weights, so what it learned carries over1. Copying only the architecture transfers nothing.
- Fine-tuning recipe1: copy every layer except the output layer, add a new output layer sized for the target classes and initialized randomly, then train on the target data, the copied layers with a small learning rate (they are already good) and the new layer with a larger one (d2l uses 10×). Inputs must be preprocessed as in pretraining; d2l normalizes the inputs of its ImageNet-pretrained ResNet-18 with per-channel mean and std 1.
- Fixed feature extractor: run the frozen network, read the activations of one layer (e.g. AlexNet's 4096-D codes just before the classifier) and train a linear classifier, such as a linear SVM or softmax, on them2. Cheap, and it works with few labels. Any layer can serve; the vector length is that layer's size (a flattened conv map keeps spatial information; a globally pooled one does not).
- Which strategy (rules of thumb)2:
| Target data | Similar to source | Very different |
|---|---|---|
| small | linear classifier on top features | linear classifier on earlier-layer features |
| large | fine-tune the whole network | fine-tune (or train), starting from pretrained weights |
- Why it works3: first-layer features (Gabor-like edges, colour blobs) are general and later layers become specific to the source task; transferability drops as the tasks grow apart, yet even distant-task features beat random ones, and a transferred initialization still helps after fine-tuning. Freezing copied middle layers also hurts because neighbouring layers had co-adapted; letting the copied layers fine-tune removes that drop3.
- Discriminative fine-tuning (ULMFiT): every layer gets its own learning rate, 2.6 times smaller per step down, , so the general lower layers change least; ULMFiT pairs it with slanted triangular learning rates (short linear increase, long linear decay) and gradual unfreezing from the last layer down, which avoids catastrophic forgetting4.
- Domain adaptation: keep training a pretrained model on data from the target domain (e.g. a language model on legal or medical text) so it fits that domain better; ULMFiT fine-tunes its language model on the target task's text before training the classifier4.
- Linear probing vs. fine-tuning: with a random head, the backbone changes while the head is still being learned, which distorts the pretrained features. On 10 distribution-shift datasets, fine-tuning was about 2% better in-distribution but 7% worse out-of-distribution than linear probing; linear probing first and full fine-tuning afterwards (LP-FT) beat both5.
- Distribution shift6, with the training and the target distribution: covariate shift changes but keeps (photos at training, cartoons at test); reweight training examples by , estimated with a classifier that separates target from source inputs. Label shift changes but keeps (a disease becomes more common, its symptoms look the same); reweight by , estimating the target by solving with the validation confusion matrix and the mean test prediction. Concept shift changes what the labels mean.
- Self-supervised pretraining learns features without labels. SimCLR makes two random augmentations of every image in a batch of ; for each view the other view of the same image is the positive and the other views are negatives; the loss (NT-Xent) is a softmax cross-entropy over cosine similarities divided by a temperature 7. The augmentations define the task, so the features learn to ignore what they change. A constant encoder would satisfy the positive term alone; the negatives push different images apart, and more of them (larger batches, longer training) help7. A linear classifier on SimCLR features matched a supervised ResNet-50 on ImageNet, and fine-tuning on 1% of the labels reached 85.8% top-5 accuracy7.
- Neural style transfer keeps a pretrained VGG-19 frozen and optimizes the pixels of a synthesized image8: content loss compares feature maps at a layer near the output, style loss compares Gram matrices (channel × channel inner products summed over positions, so "which features co-occur", not where) at several layers, and a total-variation term removes high-frequency noise8.
Formulas
New head parameters: . Label-shift weight: . Gram matrix of a map: , independent of and . For unit vectors, .
Worked example
ResNet-18 ends in global average pooling to 512 features. For 5 target classes the new head Linear(512, 5) has parameters, the only trainable ones if the backbone is frozen. Unfreezing the last stage (layer4, parameters) as well makes of the parameters trainable.
Contrastive batch with images: 16 views; each anchor has 1 positive and 14 negatives, so 15 terms in the denominator. With unit vectors and , even a perfect encoder (positive similarity 1, negatives ) has loss ; with it drops to about , which is why the temperature is needed.
In code
import torch
import torchvision
from torch import nn
model = torchvision.models.resnet18(weights=None) # weights="IMAGENET1K_V1" in practice
for p in model.parameters():
p.requires_grad = False # 1) freeze the backbone ...
model.fc = nn.Linear(model.fc.in_features, 5) # 2) ... then add a new, trainable head
print(sum(p.numel() for p in model.parameters() if p.requires_grad)) # 2565
opt = torch.optim.SGD([p for p in model.parameters() if p.requires_grad], lr=1e-3)
print(model(torch.zeros(2, 3, 224, 224)).shape) # torch.Size([2, 5])
Common pitfalls
- Freezing with a loop over
model.parameters()after replacing the head also freezes the head;backward()then fails because nothing requires a gradient. model.eval()does not freeze weights; setrequires_grad=False(PyTorch) ortrainable = False(Keras).- Passing only
model.classifier.parameters()to the optimizer trains all layers of that classifier, not just the new last layer. - Use the pretraining normalization statistics, not those of your new dataset, and keep random augmentation out of the validation set.
- Fine-tuning everything with a large learning rate on 300 images overfits and wipes out the pretrained features.
- For data very different from the source, features from the last layers are the least transferable (earlier layers are more general), and if such data are also plentiful, pretraining helps least2.
- Style transfer trains the image, not the network; the Gram matrix discards where features occur.
- Label shift is not covariate shift: when the class frequencies change but each class looks the same, does change, so reweight by 6.
References
- Dive into Deep Learning — Sec. 14.2.1 Steps; 14.2.2.1 Reading the Dataset; 14.2.2.2 Defining and Initializing the Model; 14.2.3 Summary
- CS231n course notes: Transfer Learning — Transfer Learning (ConvNet as fixed feature extractor; When and how to fine-tune?; Practical advice)
- Yosinski et al. (2014), How transferable are features in deep neural networks? — Abstract; Sec. 4.1 Similar Datasets (Random A/B splits)
- Howard & Ruder (2018), Universal Language Model Fine-tuning for Text Classification — Sec. 3.2 Target task LM fine-tuning (Discriminative fine-tuning, Slanted triangular learning rates); 3.3 Target task classifier fine-tuning (Gradual unfreezing)
- Kumar et al. (2022), Fine-Tuning can Distort Pretrained Features and Underperform Out-of-Distribution — Abstract
- Dive into Deep Learning — Sec. 4.7.1 Types of Distribution Shift; 4.7.3.2 Covariate Shift Correction; 4.7.3.3 Label Shift Correction
- Chen et al. (2020), A Simple Framework for Contrastive Learning of Visual Representations (SimCLR) — Abstract; Sec. 2.1 The Contrastive Learning Framework; 3 Data Augmentation for Contrastive Representation Learning; 5.2 Contrastive learning benefits (more) from larger batch sizes and longer training
- Dive into Deep Learning — Sec. 14.12.1 Method; 14.12.4 Extracting Features; 14.12.5 Defining the Loss Function