Computer Vision Questions
Modeling and pipelines for image data. Covers image classification, object detection (anchors, feature pyramids, non-maximum suppression, one-stage versus two-stage and anchor-free detectors), and semantic and instance segmentation; image preprocessing and augmentation; transfer learning, pretrained backbones and self-supervised pretraining; convolutional networks compared with vision transformers; annotation, labeling quality, dataset formats, active learning and leakage-safe splits; evaluation with intersection over union, average precision and mean average precision, and Grad-CAM; handling class imbalance, tiny objects and large images; and face detection and verification. Focuses on the fundamentals of applying learning to visual inputs and the practical constraints of vision systems. Model serving and compression, on-device deployment, distributed training, generic network mechanics, language and multimodal models, fairness and interpretability audits, and production monitoring and retraining pipelines are covered elsewhere.
Describe how Grad-CAM works for visualizing model decisions in CNNs. If asked to implement Grad-CAM for a PyTorch classification model, which layer would you hook into and what are the key steps to produce a heatmap overlay for a predicted class?
Sample Answer
Direct answer
Grad-CAM (gradient-weighted class activation mapping) answers "which image regions pushed the network toward this class?". Take the feature maps of the LAST convolutional block, weight each channel by how much the class score would change if that channel got stronger (the gradient averaged over positions), add the weighted channels, keep only the positive part, then upsample the small map to image size and blend it over the picture. You hook the last convolutional block because it is the deepest layer that still has spatial layout: earlier layers see edges and textures with no class meaning, and after the fully connected layers (layers in which every output mixes every input) the spatial layout is gone.
The mechanism, in order
Call the hooked layer's output A, a tensor of shape (channels C, height h, width w). A hook is a function PyTorch calls with a layer's output on the forward pass, or with the gradient flowing into the layer on the backward pass. Let yc be the logit (the raw pre-softmax score) of class c.
- Forward pass: run the image, store A from a forward hook.
- Pick the class: the predicted one, or any class you want explained.
- Backward pass from the single number yc (not from the loss, and not from the softmax probability, whose gradient is damped by the other classes). A backward hook stores ∂yc/∂A, same shape as A.
- Channel weights: average that gradient over the spatial positions.
- Weighted sum over channels, then ReLU (rectified linear unit, max(0,⋅)), which keeps only evidence FOR the class.
- Upsample to the input size with bilinear interpolation (each new pixel is a distance-weighted average of the four nearest map cells), rescale to [0,1], and blend with the image (in practice through a colour map such as the jet palette, which runs from blue for cold to red for hot).
Here k indexes channels, (i,j) indexes positions in the feature map, αkc is the importance of channel k for class c, and Ak(i,j) is the activation of channel k at that position.
Which layer, concretely. In a ResNet-style network, the output of the final residual stage (called layer4 in torchvision's ResNet, for example; a residual block adds its own input back onto its output), before global pooling. In a VGG-style network, the last convolution plus its ReLU. For a vision transformer there is no convolutional map, so you hook the last block's patch tokens and reshape them to the patch grid, which is a different setup. The hooked map is small (7x7 for a 224x224 ResNet input, for example), so each cell stands for a large block of input pixels, and the heat map is coarse by construction: that is the price of choosing the layer with the most class-specific meaning. Hooking an earlier layer gives a sharper but less class-specific map.
The formula on numbers you can follow by hand
Two channels on a 2x2 feature map, with made-up activations and gradients in the shapes the hooks return.
import numpy as np
# Grad-CAM by hand: 2 channels on a 2x2 feature map (made-up numbers, in the shape of the real tensors)
A = np.array([[[1., 0.], [0., 2.]], # channel 0 activations
[[0., 3.], [1., 0.]]]) # channel 1 activations
G = np.array([[[0.2, 0.4], [0.0, 0.2]], # d logit / d A for channel 0
[[-0.1, -0.3], [-0.1, -0.1]]])
alpha = G.mean(axis=(1, 2)) # one weight per channel
raw = (alpha[:, None, None] * A).sum(axis=0)
print("alpha:", np.round(alpha, 3))
print("weighted sum:", np.round(raw, 3).tolist())
print("after ReLU:", np.maximum(raw, 0).round(3).tolist())
Output:
alpha: [ 0.2 -0.15]
weighted sum: [[0.2, -0.45], [-0.15, 0.4]]
after ReLU: [[0.2, 0.0], [0.0, 0.4]]
Reading it. Channel 0's four gradients average to α0=0.2 (the class score rises when this channel gets stronger) and channel 1's average to α1=−0.15 (the score falls when it gets stronger). The weighted sum is 0.2A0−0.15A1. At the top right, channel 1 fires strongly (3) but argues against the class, so the sum is −0.45 and the ReLU sets it to 0. At the bottom right, channel 0 gives 0.2×2=0.4, the hottest cell. The result is a 2x2 map that is hot only where channels with positive weight are active.
A runnable version on a tiny network
The task is synthetic so that the right answer is known: class 0 has a bright 8x8 blob in the top-left, class 1 has one in the bottom-right. The network ends in global average pooling (averaging each channel's map over all positions to get one number per channel) plus a linear layer. The program trains four such networks from different seeds, runs Grad-CAM with hooks on each, and runs two checks. Check 1 uses a special property: with global average pooling followed by one linear layer, αkc=wc,k/(hw) exactly, where wc,k is the linear layer's weight for class c and channel k (so Grad-CAM reduces to the older CAM method, class activation mapping, which reads the channel weights straight from the final linear layer). Check 2 is a deletion test: if the map is faithful, erasing the hot patch should hurt the class margin (the predicted class's logit minus the other class's logit) more than erasing a random patch. Images whose map is all zero after the ReLU have no hot patch, so they are counted separately and left out of the deletion test and the heat share.
import numpy as np, torch, torch.nn as nn, torch.nn.functional as F
torch.set_num_threads(1)
# Synthetic task: class 0 = bright 8x8 blob in the top-left quadrant, class 1 = blob in the bottom-right.
def make(n, rng):
x = rng.normal(0, 0.3, size=(n, 1, 32, 32)).astype(np.float32)
y = rng.integers(0, 2, size=n)
pos = np.zeros((n, 2), dtype=int) # top-left corner of the blob
for i in range(n):
r = rng.integers(2, 6) if y[i] == 0 else rng.integers(18, 22)
c = rng.integers(2, 6) if y[i] == 0 else rng.integers(18, 22)
x[i, 0, r:r + 8, c:c + 8] += 1.5
pos[i] = (r, c)
return torch.from_numpy(x), torch.from_numpy(y), pos
class Net(nn.Module):
def __init__(self):
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(1, 8, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2), # 32 -> 16
nn.Conv2d(8, 16, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2), # 16 -> 8
nn.Conv2d(16, 16, 3, padding=1), nn.ReLU()) # last conv block: 16 x 8 x 8
self.head = nn.Linear(16, 2) # after global average pooling
def forward(self, x):
a = self.features(x)
return self.head(a.mean(dim=(2, 3)))
def hook_last_block(net):
# Hook the LAST convolutional block (its ReLU output): store its activations A and the gradient G of the logit w.r.t. A.
store = {}
layer = net.features[-1]
layer.register_forward_hook(lambda m, i, o: store.__setitem__("A", o))
layer.register_full_backward_hook(lambda m, gi, go: store.__setitem__("G", go[0]))
return store
def grad_cam(model, store, x, cls=None):
model.zero_grad()
logits = model(x) # (1, num_classes), pre-softmax scores
cls = int(logits.argmax(1)) if cls is None else cls
logits[0, cls].backward() # gradient of the class SCORE, not the loss
A, G = store["A"].detach(), store["G"].detach()
alpha = G.mean(dim=(2, 3), keepdim=True) # (1, C, 1, 1): one weight per channel
cam = F.relu((alpha * A).sum(dim=1, keepdim=True)) # (1, 1, h, w)
cam = F.interpolate(cam, size=x.shape[-2:], mode="bilinear", align_corners=False)
cam = (cam - cam.min()) / (cam.max() - cam.min() + 1e-8) # scale to [0, 1]; an all-zero map stays all zero
return cam[0, 0].numpy(), cls, alpha[0, :, 0, 0]
def margin(model, x, cls):
with torch.no_grad():
z = model(x)[0]
return (z[cls] - z[1 - cls]).item()
alpha_ok = []
def one_run(seed, n_test=30):
torch.manual_seed(seed); rng = np.random.default_rng(seed)
net = Net(); store = hook_last_block(net)
xtr, ytr, _ = make(400, rng)
opt = torch.optim.Adam(net.parameters(), lr=0.01)
for step in range(60):
opt.zero_grad(); F.cross_entropy(net(xtr), ytr).backward(); opt.step()
net.eval()
xte, yte, pte = make(n_test, rng)
acc = (net(xte).argmax(1) == yte).float().mean().item()
g = np.random.default_rng(seed + 1000)
peak_in, peak_near, empty, share, d_cam, d_rand, d_blob = [], [], 0, [], [], [], []
for i in range(n_test):
x = xte[i:i + 1]; cam, cls, alpha = grad_cam(net, store, x)
if i == 0: # check: with global-average-pool + linear head, alpha_k = w_k / (h*w)
alpha_ok.append(bool(torch.allclose(alpha, net.head.weight[cls].detach() / 64, atol=1e-6)))
br, bc = pte[i]
if cam.max() == 0:
empty += 1; peak_in.append(False); peak_near.append(False); continue
r, c = np.unravel_index(cam.argmax(), cam.shape)
peak_in.append(br <= r < br + 8 and bc <= c < bc + 8)
peak_near.append(br - 4 <= r < br + 12 and bc - 4 <= c < bc + 12)
share.append(cam[br:br + 8, bc:bc + 8].sum() / cam.sum())
# deletion test: replace an 8x8 patch (at the cam peak, at a random place, on the true blob) with the image mean
for (rr, cc), bucket in [((r, c), d_cam), ((g.integers(4, 28), g.integers(4, 28)), d_rand), ((br + 4, bc + 4), d_blob)]:
xd = x.clone(); r0, c0 = max(0, min(24, rr - 4)), max(0, min(24, cc - 4))
xd[0, 0, r0:r0 + 8, c0:c0 + 8] = x.mean()
bucket.append(margin(net, x, cls) - margin(net, xd, cls))
win = np.mean(np.array(d_cam) > np.array(d_rand))
return acc, np.mean(peak_in), np.mean(peak_near), empty, np.mean(share), np.mean(d_cam), np.mean(d_rand), np.mean(d_blob), win
print("seed acc peak-in-blob peak-within-4px empty-maps heat-in-blob margin drop: hot / random / true blob hot beats random")
res = []
for seed in range(4):
out = one_run(seed); res.append(out)
print(f"{seed:4d} {out[0]:.2f} {out[1]:11.0%} {out[2]:14.0%} {out[3]:10d} {out[4]:12.2f} {out[5]:10.2f} / {out[6]:.2f} / {out[7]:.2f} {out[8]:15.0%}")
res = np.array(res)
print("alpha equals w_k/(h*w) in every run:", all(alpha_ok))
print(f"blob covers {64 / 1024:.3f} of the image, the blob widened by 4 px covers at most {256 / 1024:.3f}")
print(f"ranges over 4 trained networks: peak inside blob {res[:, 1].min():.0%} to {res[:, 1].max():.0%}, "
f"hot patch beats random patch {res[:, 8].min():.0%} to {res[:, 8].max():.0%}; "
f"erasing the true blob costs {res[:, 7].min():.1f} to {res[:, 7].max():.1f} of margin")
Output:
seed acc peak-in-blob peak-within-4px empty-maps heat-in-blob margin drop: hot / random / true blob hot beats random
0 1.00 3% 100% 0 0.12 0.81 / 0.70 / 8.76 53%
1 1.00 27% 77% 0 0.12 5.06 / 1.82 / 11.53 67%
2 1.00 53% 57% 0 0.19 15.50 / 0.77 / 24.12 77%
3 1.00 0% 0% 17 0.00 -1.02 / 0.50 / 10.56 15%
alpha equals w_k/(h*w) in every run: True
blob covers 0.062 of the image, the blob widened by 4 px covers at most 0.250
ranges over 4 trained networks: peak inside blob 0% to 53%, hot patch beats random patch 15% to 77%; erasing the true blob costs 8.8 to 24.1 of margin
How to read it. The identity in check 1 holds in every run, so the hooks and the formula are implemented correctly. The localization quality does not carry over from one trained network to the next, even though all four networks classify the 30 test images of their run perfectly. Network 0 puts its peak within 4 pixels of the blob in every image but inside the blob in only 3 percent of them, so its heat sits on the blob's border. Networks 1 and 2 put the peak inside the blob in 27 and 53 percent of images. For network 3 the map for the predicted class is empty (all zero after the ReLU) for 17 of the 30 images, and in the others the peak is not near the blob, so for those images the network reaches its answer through evidence the positive-evidence map does not show on the object. The heat share inside the blob for networks 0 to 2 is 0.12 to 0.19 against the 0.062 a map spread evenly over the image would give.
The deletion test agrees with that spread. Erasing the hot patch cost 0.81, 5.06 and 15.50 of margin for networks 0 to 2, against 0.70, 1.82 and 0.77 for a random patch, and the hot patch beat the random one on 53, 67 and 77 percent of images; a map carrying no information would win about half the time. For network 3 the hot patch did worse than a random one (15 percent, on the 13 images with a non-empty map). Erasing the true blob cost 8.8 to 24.1, far more than any hot patch in networks 0, 1 and 3, so the map is a coarse hint and not an outline of what matters.
What this stand-in does and does not show. The original Grad-CAM paper describes its output as a coarse localization map built from the gradients flowing into the final convolutional layer, and on trained image classifiers the maps are generally used as a coarse guide to the class-relevant region. This stand-in has one input channel, three small convolutional layers, 60 training steps and a two-way head, and it does not reproduce a reliable version of that guide: the numbers above come from these four seeds and should not be read as typical Grad-CAM quality. What the run does teach is the procedure: implement the hooks, check the formula against a case where the answer is known, and test any map with a deletion check before trusting it, because a map can look plausible or fail without any error being raised. There is no universal threshold for a good win rate; read the ordering random patch, hot patch, true object, and treat a hot patch that does not beat a random one as a sign the map is not faithful for that network.
Pitfalls and trade-offs
- Eval mode and no in-place ops. Call
model.eval()so dropout (random zeroing of activations during training) and batch normalization (which normalizes with batch statistics in training and stored averages at test time) behave as at test time. In-place activations such asReLU(inplace=True)can break backward hooks. - Explaining the score, not the loss. Backpropagating the loss explains "why this label was right"; backpropagating yc explains "why this class", and lets you ask about a non-predicted class.
- Why ReLU. Without it, negative values (evidence against the class) blur into the map; with it, you see only positive evidence. To see counter-evidence, negate the weights.
- Coarse resolution. Hooking a higher-resolution layer sharpens it at the price of class specificity; Guided Grad-CAM is a refinement that multiplies the map by a pixel-level gradient picture (guided backpropagation) for sharper detail, and is used less often than plain Grad-CAM.
- It is a debugging aid, not proof. A heat map can look sensible for a wrong reason, and two different models can produce similar maps. Pair it with the deletion check above (and the spread across trained networks shown there), and with a sanity test: re-initialise the weights of the top layers at random and check that the map changes a lot (if it barely changes, the map mostly reflects the image, not the model).
- Common mistakes. Hooking after global pooling (no spatial map left), forgetting to detach before converting to numpy, normalising per image and then comparing intensity across images, and reading the heat map as a segmentation mask.
You have a small labeled image dataset in a domain unlike ImageNet. Compare training from scratch, fine-tuning a pretrained model and using a frozen backbone with a linear head. How do you choose?
Sample Answer
The idea in plain words
You have three ways to get a classifier from a small labelled set in a domain that does not look like ImageNet (for example microscopy (images taken through a microscope, such as stained cells), satellite tiles, X-rays or industrial parts):
- Train from scratch: random starting weights, everything learned from your images.
- Fine-tune a pretrained model: start from weights learned on a large source dataset (ImageNet is the usual example: about a million everyday photos in 1,000 classes) and keep training all or some layers.
- Frozen backbone with a linear head: keep the pretrained layers fixed, compute each image's feature vector once, and train only one linear layer (a single matrix multiply plus a bias) from features to classes. This is also called a linear probe: the cached feature vector for each image is computed once and stored, and the probe is trained on those stored vectors.
The choice turns on one question: do the pretrained features still describe your images? Early layers detect edges, blobs and textures, and those transfer even to unusual domains; later layers encode source-specific concepts that may be useless. The distance between the source images and yours is called the domain gap: a close-up photo of a cat breed is a small gap from ImageNet, a chest X-ray or a satellite tile is a medium-to-large one (still edges and textures, but different statistics and meaning), and an image whose pixels carry no local spatial pattern would be an extreme one. Less data pushes you toward fewer trainable parameters (frozen); more data and a larger domain gap push you toward more freedom (fine-tune everything, or scratch).
Comparison
| From scratch | Fine-tune | Frozen backbone + linear head | |
|---|---|---|---|
| Trainable parameters | All | All or the top layers | Only the head |
| Labelled data needed | Most | Moderate | Least |
| Compute | Highest (many epochs) | Medium | Lowest (features can be cached) |
| Risk | Overfits small data | Forgetting good features; overfitting | Features miss what matters in the domain |
| Wins when | Large dataset, or inputs unlike natural images in structure (different channels, no local spatial structure) | Moderate data, some domain gap | Tiny data, or domain close to the source |
A measured comparison with a controlled domain gap
The program builds a small convolutional network pretrained on 10-way digit recognition (images 0 to 899 of scikit-learn's 8 by 8 digits), then solves a 10-class task on disjoint images (900 onwards) in two target domains. The near domain is the same kind of image. The far domain applies a fixed random shuffle to the 64 pixel positions of every image, which keeps all the information but destroys local spatial structure, an extreme stand-in for a domain where convolution filters learned elsewhere do not fit. Each cell is a mean over 3 seeds followed by the standard deviation across those seeds (a measure of how much the result moves from seed to seed; seeds differ in the pretrained network, the labelled sample and the initialisation), with 5 or 20 labelled images per class and accuracy on every other target image. Three seeds is a small sample, so read the pattern, not the third decimal, and treat a gap smaller than about two standard deviations as unresolved. Each method gets the same data and number of epochs; fine-tuning uses a 10 times smaller learning rate than the others.
In plain terms the code does four things: it pretrains a network on the source images (pretrained), builds the shuffled version of the target images (to_domain applies one fixed random permutation of the 64 pixel positions, perm_pixels), picks n_per labelled images of each class as the training set (order[yd[order] == c][:n_per] takes the first n_per images of class c in a random order) and tests on all remaining images, then trains the three methods on that sample.
import copy
import numpy as np
import torch
import torch.nn as nn
from sklearn.datasets import load_digits
torch.set_num_threads(1)
X, y = load_digits(return_X_y=True)
X = torch.tensor(X / 16.0, dtype=torch.float32).reshape(-1, 1, 8, 8)
y = torch.tensor(y)
class Net(nn.Module):
def __init__(self):
super().__init__()
self.backbone = nn.Sequential(
nn.Conv2d(1, 16, 3, padding=1), nn.BatchNorm2d(16), nn.ReLU(),
nn.Conv2d(16, 32, 3, padding=1), nn.BatchNorm2d(32), nn.ReLU(),
nn.AdaptiveAvgPool2d(2), nn.Flatten())
self.head = nn.Linear(128, 10)
def forward(self, x):
return self.head(self.backbone(x))
def train(model, params, Xt, yt, epochs, lr, backbone_eval=False):
opt = torch.optim.Adam(params, lr=lr)
for _ in range(epochs):
model.train()
if backbone_eval:
model.backbone.eval()
perm = torch.randperm(len(Xt))
for i in range(0, len(Xt), 32):
b = perm[i:i + 32]
opt.zero_grad()
nn.functional.cross_entropy(model(Xt[b]), yt[b]).backward()
opt.step()
def accuracy(model, Xt, yt):
model.eval()
with torch.no_grad():
return (model(Xt).argmax(1) == yt).float().mean().item()
# Source domain: digits 0..899 as they are. Target domains use images 900.. only (disjoint).
perm_pixels = torch.randperm(64, generator=torch.Generator().manual_seed(123))
def to_domain(imgs, domain):
if domain == "near (same images)":
return imgs
return imgs.reshape(len(imgs), 64)[:, perm_pixels].reshape(-1, 1, 8, 8) # fixed pixel shuffle: no spatial structure left
SEEDS = 3
pretrained = []
for seed in range(SEEDS):
torch.manual_seed(seed)
net = Net()
train(net, net.parameters(), X[:900], y[:900], epochs=15, lr=1e-2)
pretrained.append(net)
print("10-class accuracy on the held-out target images; mean over 3 seeds")
print("each cell: mean +- standard deviation over the 3 seeds")
print(f"{'target domain':<22}{'labels/class':>13}{'scratch':>15}{'frozen+head':>15}{'fine-tune':>15}")
for domain in ("near (same images)", "far (pixels shuffled)"):
Xd = to_domain(X[900:], domain)
yd = y[900:]
for n_per in (5, 20):
acc = {"scratch": [], "frozen": [], "finetune": []}
for seed in range(SEEDS):
torch.manual_seed(100 + seed)
g = torch.Generator().manual_seed(seed)
order = torch.randperm(len(yd), generator=g)
small = torch.cat([order[yd[order] == c][:n_per] for c in range(10)])
test = torch.tensor(sorted(set(range(len(yd))) - set(small.tolist())))
Xs, ys, Xe, ye = Xd[small], yd[small], Xd[test], yd[test]
m = Net(); train(m, m.parameters(), Xs, ys, 25, 1e-2); acc["scratch"].append(accuracy(m, Xe, ye))
m = copy.deepcopy(pretrained[seed]); m.head = nn.Linear(128, 10); m.backbone.requires_grad_(False)
train(m, m.head.parameters(), Xs, ys, 25, 1e-2, backbone_eval=True); acc["frozen"].append(accuracy(m, Xe, ye))
m = copy.deepcopy(pretrained[seed]); m.head = nn.Linear(128, 10)
train(m, m.parameters(), Xs, ys, 25, 1e-3); acc["finetune"].append(accuracy(m, Xe, ye))
cell = lambda v: f"{np.mean(v):.3f}+-{np.std(v, ddof=1):.3f}"
print(f"{domain:<22}{n_per:>13}{cell(acc['scratch']):>15}{cell(acc['frozen']):>15}{cell(acc['finetune']):>15}")
Output:
10-class accuracy on the held-out target images; mean over 3 seeds
each cell: mean +- standard deviation over the 3 seeds
target domain labels/class scratch frozen+head fine-tune
near (same images) 5 0.901+-0.022 0.968+-0.009 0.934+-0.029
near (same images) 20 0.965+-0.017 0.981+-0.001 0.971+-0.000
far (pixels shuffled) 5 0.816+-0.011 0.745+-0.014 0.688+-0.041
far (pixels shuffled) 20 0.926+-0.002 0.858+-0.013 0.874+-0.006
Reading the table:
- Near domain, 5 labels per class: the frozen backbone with a linear head scored 0.968 against 0.901 for scratch, a gap of 0.067, well beyond two standard deviations of either (0.009 and 0.022). Fine-tuning scored 0.934; its 0.034 gap to the frozen head is about one of its own standard deviations (0.029), so with 3 seeds the order of those two is unresolved, though it points the way the usual finding does: with very little data, fewer trainable parameters tends to win when the features fit.
- Near domain, 20 labels per class: all three are within 0.016 (0.965, 0.981, 0.971), about the size of the seed spread of scratch (0.017), so the advantage of freezing has shrunk to roughly noise as data grows.
- Far domain: the order reverses. From scratch scored 0.816 and 0.926 at 5 and 20 labels per class, ahead of the frozen head (0.745, 0.858) and fine-tuning (0.688, 0.874) by 0.052 or more, well beyond two standard deviations in every cell. Between the frozen head and fine-tuning the order is unresolved (0.745 against 0.688 at 5 labels, 0.858 against 0.874 at 20). The pretrained filters assume neighbouring pixels belong together; once that is false, they are a worse starting point than a random initialisation, and fine-tuning gains nothing from them because it starts from that misleading point.
- What this toy does and does not show. It shows the mechanism and its direction: a method that reuses features wins while the features fit, and loses when they do not. The far domain here is deliberately extreme, a random pixel shuffle with no local structure left, so it is not a model of a realistic domain. Real data that is unlike ImageNet (an X-ray, a satellite tile, a stained cell) still contains edges, textures and shapes, which is why pretrained weights commonly remain the better starting point there on small datasets, with the margin shrinking as the labelled set grows and as the domain gap widens; the toy cannot measure that, so run the three-way comparison on your own data.
How to choose (a recommendation, with what would flip it)
- Default to a pretrained backbone, because real images almost always have local structure, and run a frozen backbone with a linear head first: it takes minutes and sets a floor.
- Fine-tune next (unfreeze the last blocks first, backbone learning rate well below the head's) and keep it only if validation beats the linear probe by more than the noise in the validation estimate (use cross-validation when the set is small).
- Train from scratch only when the inputs differ in structure from natural photos (many spectral channels, meaning many colour bands beyond red, green and blue as in satellite sensors; volumetric data, meaning 3-D scans made of stacked slices; or non-spatial data), or labelled data is plentiful (a rough rule of thumb is tens of thousands of images or more, but it moves with the size of the domain gap and the difficulty of the task, so confirm it on your own learning curve) and compute allows long training.
- When labelled data is scarce but unlabelled in-domain images are plentiful, pretrain on the unlabelled images with a self-supervised method (one that makes its own labels from the images, for example by hiding part of an image and training the network to predict it, or by teaching it that two altered views of one image belong together), then fine-tune on the labels.
- Diagnostic that settles it: plot validation accuracy against the number of labelled images for each method (a learning curve: train on 10, 20, 40, 80 percent of your labels and plot each score). If the frozen and fine-tuned curves are still climbing and scratch is far below, the pretrained features are helping; if scratch catches up as data grows, the gap is closing and more data favours scratch.
Mistakes
- Comparing methods on one validation split of a few dozen images and declaring a winner.
- Giving each method a different preprocessing or training budget, so the comparison measures the pipeline rather than the method.
- Fine-tuning everything at a large learning rate and concluding that pretraining "does not help".
- Using the source model's preprocessing for one method and not another.
You have a large proprietary dataset of about 10 million images. Is it still worth starting from a pretrained backbone, or should you train from scratch? What drives the decision?
Sample Answer
The idea in plain words
Pretraining means starting training from weights that were already trained on a large other dataset, instead of from random numbers (training "from scratch"); fine-tuning is then continuing to train those weights on your own labelled data. The usual reason to pretrain is data scarcity: with a few hundred images, the pretrained filters supply what the data cannot. With 10 million images that reason weakens, because your own data can teach the low-level features itself. But "weakens" is not "disappears". Recommendation: still start from a pretrained backbone and fine-tune all layers on the 10 million images, unless a specific constraint below applies; and settle it with a short experiment on your own data rather than by argument. The decision is driven by four things: how far your images are from the pretraining images (domain gap), how much compute you have, whether a pretrained model is allowed and available in the form you need, and what the learning curve of your own task looks like.
I assume the 10 million images are labelled. If they are mostly unlabelled, the same logic points to self-supervised pretraining on your own images (learning from the images without labels, for example by predicting masked or augmented views; the label-free task is called the self-supervised objective) and fine-tuning on the labelled part.
What changes with 10 million images
- Benefit of pretraining shrinks with target data. Pretrained weights are a good starting point in a non-convex optimisation (the loss surface has many dips, so where training starts influences which dip it reaches); the less target data, the more that starting point matters. With a lot of data, scratch training can catch up in final accuracy (it needs more steps to get there).
- Speed and stability. Even when the final accuracy ends up similar, the pretrained start usually reaches a given quality in fewer epochs, which is a compute saving, not an accuracy gain. The budget below shows the size of that saving for assumed inputs.
- Domain gap sets the ceiling of the benefit. If your images look like natural photographs, pretrained filters (edges, textures, parts) are directly useful. If they are something else (multispectral satellite bands, X-ray, microscope slides, depth maps, line drawings), lower layers may still help but higher layers carry little, and with 10 million images the start can matter less or even be a handicap.
A small experiment that shows the shape of the answer
What is established first, so the toy has something to be compared with: a published study that trained detection and segmentation models on the COCO dataset (He, Girshick and Dollar, "Rethinking ImageNet Pre-training", 2018) reports that pretraining speeds up convergence early in training, and that it does not necessarily improve final accuracy: a model trained from random initialisation can match a pretrained one if it is given more training iterations. The toy below shows the same pattern in miniature: at every target size the pretrained start is ahead by epoch 15, a scratch network given more epochs catches up once there are about 100 target images, and only the 20 image case keeps a gap at the end of the run.
This is a toy, not a claim about 10 million images, and it stops at 300 target images. It uses 16 by 16 synthetic images and a small convolutional network. The "source" task is 8-way orientation classification of noisy sinusoidal gratings (stripe patterns). The target is a different 4-way orientation task, so the stripe detectors learned on the source are relevant; the source-trained network is a stand-in for a real pretrained backbone, tiny and trained for a few epochs, so it should not be read as a model of real pretraining on millions of varied photos. For each target size n, one network is trained from random weights and another from the source-trained weights (every layer copied except the output layer, then all layers fine-tuned, which here means continuing training from the copied weights). Test accuracy is on 1000 fresh images, reported as mean and standard deviation over 6 seeds after epochs 5, 15, 30 and 60 of one 60-epoch run per network (an epoch is one pass over the data).
import numpy as np
import torch
from torch import nn
torch.set_num_threads(1)
G = 16
yy, xx = np.mgrid[:G, :G] - (G - 1) / 2
NOISE = 1.0
def grating(rng, theta):
"""16x16 sinusoidal grating at orientation theta (radians), random frequency and phase, plus Gaussian noise."""
f = rng.uniform(0.25, 0.5); ph = rng.uniform(0, 2 * np.pi)
return np.sin(f * (xx * np.cos(theta) + yy * np.sin(theta)) + ph) + NOISE * rng.standard_normal((G, G))
def make(rng, n, kind):
y = rng.integers(0, 8 if kind == "source" else 4, size=n)
if kind == "source": # 8 orientations, 22.5 degrees apart
x = [grating(rng, k * np.pi / 8 + rng.normal(0, 0.05)) for k in y]
else: # target: 4 other, coarser orientation classes
x = [grating(rng, k * np.pi / 4 + np.pi / 16 + rng.normal(0, 0.05)) for k in y]
return torch.tensor(np.stack(x), dtype=torch.float32)[:, None], torch.tensor(y)
def net(n_out):
return nn.Sequential(nn.Conv2d(1, 8, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(8, 16, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(16, 16, 3, padding=1), nn.ReLU(), nn.AdaptiveAvgPool2d(1),
nn.Flatten(), nn.Linear(16, n_out)) # the last module (index 10) is the output layer
def acc(model, x, y):
with torch.no_grad():
return (model(x).argmax(1) == y).float().mean().item()
def train(model, x, y, epochs, seed, log_at=(), xte=None, yte=None):
g = torch.Generator().manual_seed(seed)
opt = torch.optim.Adam(model.parameters(), lr=3e-3)
curve = {}
for ep in range(1, epochs + 1):
perm = torch.randperm(len(x), generator=g)
for i in range(0, len(x), 64):
b = perm[i:i + 64]
opt.zero_grad(); nn.functional.cross_entropy(model(x[b]), y[b]).backward(); opt.step()
if ep in log_at:
curve[ep] = acc(model, xte, yte)
return model, curve
xs, ys = make(np.random.default_rng(0), 1200, "source")
torch.manual_seed(0)
pre, _ = train(net(8), xs, ys, epochs=8, seed=0)
xs_test, ys_test = make(np.random.default_rng(998), 1000, "source")
print("source task (8 orientations) accuracy on 1000 fresh images:", round(acc(pre, xs_test, ys_test), 3))
body = {k: v for k, v in pre.state_dict().items() if not k.startswith("10.")} # every layer except the output layer
SEEDS, EPOCHS, LOG = 6, 60, (5, 15, 30, 60)
xt_test, yt_test = make(np.random.default_rng(999), 1000, "target")
print(f"\ntarget = 4 coarser orientation classes (chance 0.25); test set 1000 images; mean +- std over {SEEDS} seeds")
print("test accuracy after epoch e of one 60-epoch run (constant learning rate, so epoch 15 is the same as a 15-epoch run)")
print("n_target | start | " + " ".join(f"epoch {e:2d} " for e in LOG))
for n in (20, 100, 300):
runs = {"scratch": [], "pretrained": []}
for seed in range(SEEDS):
xt, yt = make(np.random.default_rng(100 + seed), n, "target")
torch.manual_seed(seed); m0, k0 = train(net(4), xt, yt, EPOCHS, seed, LOG, xt_test, yt_test)
torch.manual_seed(seed); m1 = net(4); m1.load_state_dict(body, strict=False)
m1, k1 = train(m1, xt, yt, EPOCHS, seed, LOG, xt_test, yt_test)
runs["scratch"].append([k0[e] for e in LOG]); runs["pretrained"].append([k1[e] for e in LOG])
for name, r in runs.items():
r = np.array(r)
print(f"{n:8d} | {name:10s} | " + " ".join(f"{m:.3f}+-{s:.3f}" for m, s in zip(r.mean(0), r.std(0))))
Output:
source task (8 orientations) accuracy on 1000 fresh images: 0.937
target = 4 coarser orientation classes (chance 0.25); test set 1000 images; mean +- std over 6 seeds
test accuracy after epoch e of one 60-epoch run (constant learning rate, so epoch 15 is the same as a 15-epoch run)
n_target | start | epoch 5 epoch 15 epoch 30 epoch 60
20 | scratch | 0.251+-0.012 0.295+-0.045 0.454+-0.070 0.737+-0.103
20 | pretrained | 0.225+-0.099 0.556+-0.142 0.827+-0.112 0.887+-0.077
100 | scratch | 0.273+-0.033 0.417+-0.131 0.948+-0.048 0.996+-0.003
100 | pretrained | 0.381+-0.122 0.900+-0.076 0.981+-0.015 0.994+-0.003
300 | scratch | 0.343+-0.073 0.982+-0.030 0.998+-0.002 0.998+-0.001
300 | pretrained | 0.844+-0.118 0.997+-0.001 0.999+-0.001 0.999+-0.001
Reading it: the source task is learned well on fresh images (0.937), so the copied body is a useful start. At every target size the pretrained start is ahead after 15 epochs: it scores 0.556 against 0.295 at 20 images, 0.900 against 0.417 at 100 images and 0.997 against 0.982 at 300 images. The epoch 5 column is too noisy to read (with 20 images the two arms are 0.225 and 0.251, inside a spread of 0.099, and the size of an early gap changes from one set of seeds to another), so rely on epoch 15 and later. Given more epochs the scratch network closes the gap: at 100 images the two are level by epoch 60 (0.996 against 0.994), and at 300 images they are level by epoch 30 (0.998 against 0.999). At 20 images a gap remains at epoch 60 (0.737 against 0.887), the seed-to-seed spread is large (standard deviations of 0.08 to 0.10), and whether still longer training would close it was not tested. So the toy shows two things: pretraining mostly buys speed, and the part of the benefit that lasts longest is on very small target sets. That is the pattern the published study describes (faster early convergence, and final accuracy that a longer random-initialisation run can match), and it is why the recommendation for 10 million images is to still start pretrained (fewer epochs for the same quality) unless a pilot or a constraint says otherwise, not because pretraining is needed to reach the final accuracy. Six seeds on a toy do not establish the size of the gaps, the source and target tasks here are closely related, which favours the pretrained start, and a real run on photographs would differ in every number.
When the target is not like the source. The toy does not test an unrelated target. The pretrained filters help only when the pixels mean the same thing: a backbone trained on everyday photographs sees edges, textures and object parts that also appear in many other photographs, but a 12-band satellite tile, an X-ray or a microscope slide has different statistics and different meaning per channel. That difference is the domain gap; the larger it is, the less of the pretrained start carries over, and with abundant target data the start can matter less or can even be a handicap, which is why the pilot below is worth running.
The compute side, as arithmetic
Training cost is roughly the number of images times the number of epochs times the cost of one forward-and-backward pass (run the image through the network, then push the error back through it to compute the updates), which is commonly taken as about 3 times the forward cost. FLOPs are floating-point operations, a count of arithmetic work; FLOP/s is how many a processor does per second, and 1 TFLOP/s is 1012 per second; an accelerator-hour is one GPU or similar chip running for an hour. The inputs below are assumptions (not measurements of any particular model or accelerator); substitute your own.
# Training compute for scratch vs fine-tune. Every input below is an ASSUMPTION to be replaced by your own measurements.
n_images = 10_000_000
fwd_flops = 4e9 # assumed forward FLOPs per image for the chosen backbone at the chosen resolution
train_factor = 3 # forward + backward is commonly taken as about 3x the forward cost
sustained = 3e13 # assumed sustained FLOP/s per accelerator (about 30 TFLOP/s)
for name, epochs in (("from scratch", 90), ("fine-tune pretrained", 10)):
total = n_images * epochs * train_factor * fwd_flops
gpu_hours = total / sustained / 3600
print(f"{name:21s} epochs {epochs:3d} total {total:.2e} FLOPs = {gpu_hours:7.1f} accelerator-hours")
print("ratio of the two budgets:", round((90 / 10), 1))
Output:
from scratch epochs 90 total 1.08e+19 FLOPs = 100.0 accelerator-hours
fine-tune pretrained epochs 10 total 1.20e+18 FLOPs = 11.1 accelerator-hours
ratio of the two budgets: 9.0
The ratio comes entirely from the assumed epoch counts (90 vs 10); the toy's epoch table is the measured evidence for the direction (the pretrained start reaches a given quality in fewer epochs), and the size of the saving on your task is exactly what the pilot below should measure. Pretraining also has a cost you did not pay yourself (someone else trained that backbone), so "from scratch" is not free of that comparison if you count it.
How to decide, in order
- Pilot learning curve. Train both arms on 1 percent, 10 percent and 100 percent of your data with the same architecture and schedule (and for the same wall-clock or step budget), and plot the metric against dataset size. If the gap is closing and falls inside seed noise (the run-to-run variation you get from changing only the random seed) at the sizes you can afford, scratch is viable. A plot of metric against dataset size like this is a learning curve. If it is large at 100 percent, keep the pretrained start.
- Check the input. Different channel count, different physical meaning of the pixels, very different resolution or a 3D or video input all weaken or break a pretrained start (the first layer can be adapted, but the benefit is smaller).
- Check constraints. Licensing and provenance of the pretrained weights, a requirement that no external data influences the model, bias or safety review, or an architecture you must change in ways that invalidate the weights all push toward scratch.
- Check compute. If you cannot afford many epochs on 10 million images, the pretrained start is the cheaper way to reach a given quality.
- Consider the middle path. Continue pretraining the backbone on your own images with a self-supervised objective, then fine-tune on labels; this adapts to your domain without throwing away generic features.
What would flip the recommendation to scratch: a large domain gap together with a dataset big enough that the pilot shows the pretrained arm no better, or a constraint on external weights.
Common mistakes
Comparing arms with different schedules or learning rates (a pretrained start often needs a smaller rate); evaluating at one dataset size and extrapolating; forgetting that label noise in 10 million labels can dominate the choice of backbone; assuming a pretrained model transfers because it scores well on its own benchmark; and ignoring that fine-tuning a pretrained model on a huge dataset can overwrite the pretrained features anyway, in which case the start mainly buys speed.
You have abundant unlabeled images from a new target domain and a small labeled subset. Propose a training schedule that adapts a pretrained vision model to that domain.
Sample Answer
Direct answer
Use the unlabeled images first and the labeled ones last, in four stages: (1) cheap, label-free corrections to the model's input statistics, (2) continued self-supervised training on the unlabeled target images, (3) supervised fine-tuning on the small labeled set with a gentle schedule, and (4) self-training, where the model's own confident predictions on unlabeled images become extra training labels. Hold the labeled target images in a validation split from the start, and compare every stage against two baselines: the pretrained model untouched, and fine-tuning on the labeled subset alone.
Terms. A pretrained model is a network already trained on a large source dataset. Domain shift means the target images differ systematically from the source (camera, lighting, scanner, geography, style). Fine-tuning continues training the pretrained weights on new data. Self-supervised training needs no labels: the model solves a task made from the images themselves, for example predicting masked-out patches (hide some patches of an image and train the network to fill them in) or matching two augmented views of one image (an augmentation is a random change such as a crop, flip or colour shift, and the network is trained to give the two views similar features, the idea behind contrastive training). A pseudo-label is a label the model assigns to an unlabeled image.
The schedule, in order
| Stage | Uses | What changes | Why this position |
|---|---|---|---|
| 0. Split and baselines | labeled target | Keep a validation split of labeled target images (never used for training or for choosing pseudo-labels in later stages); score the untouched model | Without it no later stage can be judged |
| 1. Re-estimate normalization statistics | unlabeled target | If the network has batch normalization (BN, which rescales activations using running means and variances), recompute those running statistics on target images. No weights are trained | Costs minutes and often removes the part of the gap that is only brightness, contrast or colour scale |
| 2. Continued self-supervised training | unlabeled target | Resume the pretraining objective (masked-patch prediction or contrastive matching) on target images, small learning rate, short | Moves the features toward target textures and objects without needing labels; most of the data is used here |
| 3. Supervised fine-tuning | labeled target | First train only a new classification head on frozen features (a linear probe), then unfreeze the backbone (the feature-extracting body of the network) with a small learning rate, lower for early layers | A freshly initialised head sends large, random gradients (the updates that tell each weight how to change) into the features; probing first, with the features frozen (their weights held fixed), protects the stage-2 features |
| 4. Self-training | both | Predict on unlabeled images, keep predictions above a confidence threshold, train on them with strong augmentation (heavy random distortion such as large crops, strong colour changes or blanked regions, which makes the agreement task harder), repeat for a few rounds | The only stage that turns the unlabeled pool into supervision; it needs a decent model to start, which is why it comes last |
Stage 2 is the one most worth cutting if compute is tight and the gap is mild (lighting, colour): stages 1, 3 and 4 are cheap. Stage 2 is the one to keep when the target objects look different, not just their pixel statistics.
For stage 4 the usual recipe is a teacher that predicts on a weakly augmented image (flip, small crop) and a student trained to agree with it on a strongly augmented version of the same image, with the teacher kept as a slow moving average of the student (an exponential moving average, EMA) so its labels do not jump between steps.
A small stand-in experiment
Training a real image model is far too slow for a worked example, so this is a stand-in: a logistic regression on 10 synthetic features plays the "pretrained model", trained on a source domain of 3000 points. The target domain is the same two classes after a 35 degree rotation of the plane that holds the class signal, a per-feature rescaling and an offset. There are 2000 unlabeled target points, 20 labeled per class (40 in total), and a separate 2000-point target test set. The rows of the output use the same stage numbers as the table above. Stage 1 here is standardising (subtracting the mean and dividing by the standard deviation of each feature) with target statistics instead of source ones; stage 2 has no counterpart in this toy (a logistic regression has no self-supervised objective); stage 3 trains on source (weight 0.1 per point) plus the 40 labels (weight 1) in a single fit, not one after the other as a real pipeline would; stage 4 adds predictions with confidence at least 0.95 at weight 0.5, for 3 rounds. Stage 0 is the untouched source model and the last row is a reference that knows every pool label. Everything is averaged over 20 seeds.
import numpy as np
from sklearn.linear_model import LogisticRegression
D = 10
ANGLE = np.deg2rad(35)
def make_domain(rng, n, target):
y = rng.integers(0, 2, n)
x = rng.normal(size=(n, D))
x[:, 0] += np.where(y == 1, 1.5, -1.5) # class signal lives in dims 0 and 1
x[:, 1] += np.where(y == 1, 1.0, -1.0)
if target: # domain gap: scale, rotation of the signal plane, offset
c, s = np.cos(ANGLE), np.sin(ANGLE)
rot = x[:, :2] @ np.array([[c, -s], [s, c]])
x[:, :2] = rot
x = x * np.linspace(0.6, 1.4, D) + np.linspace(-2, 2, D)
return x, y
def run(seed, n_lab=20, rounds=3, thr=0.95):
rng = np.random.default_rng(seed)
xs, ys = make_domain(rng, 3000, False)
xu, yu = make_domain(rng, 2000, True) # unlabeled target pool (labels used only for scoring)
xt, yt = make_domain(rng, 2000, True) # held-out target test set
idx = np.r_[np.where(yu == 0)[0][:n_lab], np.where(yu == 1)[0][:n_lab]]
xl, yl = xu[idx], yu[idx]
out = {}
src = LogisticRegression(max_iter=500).fit(xs, ys)
out["stage 0 source only"] = src.score(xt, yt)
mu, sd = xu.mean(0), xu.std(0) # stage 1: re-estimate input statistics on target
ms, ss = xs.mean(0), xs.std(0)
f = lambda x: (x - mu) / sd
g = lambda x: (x - ms) / ss
m1 = LogisticRegression(max_iter=500).fit(g(xs), ys)
out["stage 1 + target statistics"] = m1.score(f(xt), yt)
xl_n = f(xl)
w = np.r_[np.ones(len(xs)) * 0.1, np.ones(len(yl))] # stage 3 (toy version): labeled target examples count more
m2 = LogisticRegression(max_iter=500).fit(np.r_[g(xs), xl_n], np.r_[ys, yl], sample_weight=w)
out["stage 3 + 40 labeled target"] = m2.score(f(xt), yt)
m = m2
prec = []
for r in range(rounds): # stage 4: self-training on confident target predictions
p = m.predict_proba(f(xu))
keep = p.max(1) >= thr
pl = p.argmax(1)
prec.append((keep.mean(), (pl[keep] == yu[keep]).mean()))
X = np.r_[g(xs), xl_n, f(xu)[keep]]
Y = np.r_[ys, yl, pl[keep]]
w = np.r_[np.ones(len(xs)) * 0.1, np.ones(len(yl)), np.ones(keep.sum()) * 0.5]
m = LogisticRegression(max_iter=500).fit(X, Y, sample_weight=w)
out["stage 4 + self-training"] = m.score(f(xt), yt)
orc = LogisticRegression(max_iter=500).fit(f(xu), yu) # reference: every pool label known
out["oracle (2000 labels)"] = orc.score(f(xt), yt)
return out, prec
res, precs = [], []
for seed in range(20):
o, p = run(seed)
res.append(o); precs.append(p)
for k in res[0]:
v = np.array([r[k] for r in res])
print(f"{k:30s} mean acc {v.mean():.3f} std {v.std():.3f}")
d = np.array([r["stage 4 + self-training"] - r["stage 3 + 40 labeled target"] for r in res])
print(f"stage 4 minus stage 3: mean {d.mean():+.3f}, better in {(d > 0).sum()} of {len(d)} seeds")
pp = np.array(precs) # (seeds, rounds, 2)
for r in range(pp.shape[1]):
print(f"round {r+1}: kept {pp[:, r, 0].mean():.3f} of pool, pseudo-label precision {pp[:, r, 1].mean():.3f}")
Output:
stage 0 source only mean acc 0.506 std 0.008
stage 1 + target statistics mean acc 0.882 std 0.009
stage 3 + 40 labeled target mean acc 0.917 std 0.015
stage 4 + self-training mean acc 0.930 std 0.013
oracle (2000 labels) mean acc 0.964 std 0.004
stage 4 minus stage 3: mean +0.013, better in 20 of 20 seeds
round 1: kept 0.587 of pool, pseudo-label precision 0.991
round 2: kept 0.674 of pool, pseudo-label precision 0.988
round 3: kept 0.701 of pool, pseudo-label precision 0.988
What the run shows, and only this: on this toy, correcting the statistics recovers most of the lost accuracy (0.506 to 0.882), 40 labels add a little (0.917), stage 4 self-training adds a little more (0.930, better than stage 3 in 20 of 20 seeds, mean gain 0.013), and the oracle that knows every pool label reaches 0.964. The pseudo-labels it added were about 99% correct, which is why self-training helped here.
What not to take from it. The 0.506 starting point is chance, and the large stage-1 jump exists because I built the shift from a per-feature rescale, a per-feature offset and a rotation, and the first two are exactly what restandardising undoes. Do not read it as the typical size of stage 1's gain: on real images, restandardising usually removes only the part of the gap that is brightness or colour scale, and the remaining gap is why stages 2 to 4 exist. The toy cannot show why stage 2 pays for its cost, or why the order (unlabeled data first, labeled data last) matters, because it has no self-supervised step and fits source and labels together. Nothing here measures a real vision model.
Trade-offs and failure modes, in the order to check them
- Confirmation bias. The model trains on its own mistakes and becomes more sure of them. Track the pseudo-label precision (needs a few true labels: use the validation split) and the predicted class mix. If one class absorbs more and more pseudo-labels, raise the threshold or balance the kept labels per class.
- Confidence is not calibrated under shift. A model can be 95% sure and wrong on shifted images. Check a reliability table on the labeled target split before trusting a fixed threshold: group the predictions into confidence bins (0.5 to 0.6, ..., 0.9 to 1.0) and compute the real accuracy inside each bin. A well calibrated model (one whose stated confidence matches how often it is right) has accuracy near the bin's confidence; if the 0.9 to 1.0 bin is right only 70 percent of the time, a 0.95 threshold gives 70 percent pseudo-label precision, not 95 percent.
- Label shift. The target has different class proportions (the class priors, the share of each class) than the source: for example 50/50 in the source and 90/10 in the target. A model trained on the source tends to over-predict the class it saw more of, so pseudo-labels drift toward the source proportions. Estimate the target priors from the labeled split, or use per-class thresholds.
- Catastrophic forgetting in stage 2. (The network overwrites useful pretrained features while adapting.) Too high a learning rate or too many steps degrades the pretrained features. Re-run the linear probe on the validation split after stage 2; if it fell, shorten or lower the learning rate.
- A validation set of 40 images is noisy. A difference of one or two points means nothing. Fix the recipe in advance, tune very little, and use cross-validation over the labeled set (split it into folds, train on all but one, score on the held-out one, rotate, and average) if a decision hinges on small gaps.
- Leakage. The unlabeled pool must not contain the test images, and the validation images must stay out of the pseudo-labeling pool.
What would change the plan: if the gap is only photometric, stop after stage 1 plus augmentation; if labeled data is almost nil (a handful of images), freeze more and lean on stages 1 and 4; if the unlabeled pool is small, skip stage 2.
Common mistakes
Fine-tuning the whole network at the source learning rate on 40 labels; tuning thresholds on the same labeled images used for training; reporting target accuracy without the untouched-model and labeled-only baselines; running self-training from a model that is wrong most of the time, which amplifies the errors.
Compare RandAugment and AutoAugment as methods for learning image augmentation policies. Discuss computational cost, ease of tuning, and when automatically searched policies produce gains over manual augmentation.
Sample Answer
Direct answer
Both methods automate the choice of image augmentations, and they differ in how much they search. AutoAugment searches a large space of policies for the one with the best validation accuracy on the target dataset. RandAugment removes that search: it applies randomly chosen operations from a fixed list and leaves only a few knobs, in the common formulation the number of operations per image (N) and one shared strength (M), which you tune with a small grid on the real task. So AutoAugment costs far more compute and has far more to tune but can express a tailored policy; RandAugment is cheap and simple but is only as good as its operation list. The published results favour the cheap method: the RandAugment paper reports matching or surpassing earlier automated augmentation approaches, AutoAugment included, on CIFAR-10/100, SVHN and ImageNet, and coming within 0.3% mAP of AutoAugment on COCO detection, without a separate search phase. AutoAugment's own paper reports a CIFAR-10 error of 1.5% and ImageNet top-1 accuracy of 83.5%, which were records when published, so searched policies can beat the standard hand-written augmentation on large benchmarks. Whether they beat a manual choice on your data is a question for your own validation set, and a manual policy that already encodes the invariances your deployment needs is the baseline to beat (an invariance is a change to the input that should not change the answer, such as a digit shifted by a pixel or a photo taken in dimmer light). Automatic policies are most useful when you do not know them, when data is limited, and when the model is large enough to overfit; the toy below shows the mechanics of choosing by validation accuracy, and it does not reproduce the benchmark results above.
Terms. Augmentation creates modified copies of training images (shifted, rotated, blurred, recoloured) so the model learns to ignore changes that should not alter the label. An operation is one such transform with a magnitude (how strong). A policy is a recipe of operations with probabilities and magnitudes. Validation accuracy is accuracy on held-out labeled data used to choose settings. The two methods are described in the original papers (AutoAugment, 2018; RandAugment, 2019): the first uses a search algorithm over policies made of sub-policies of two operations, each with a probability and a magnitude, scored by validation accuracy; the second needs no separate search or proxy task. A proxy task is a cheaper stand-in for the real training job (a smaller network, fewer epochs or a subset of the data) used to score each candidate policy during the search; a policy that is best on the proxy may not be best on the real task. A sub-policy is one pair of operations applied in sequence, each with its own probability of being applied and its own magnitude; a policy is a set of sub-policies, and each image gets one of them at random. Regularization is anything that stops a model fitting the quirks of its training set, and augmentation is a regularizer because the model never sees exactly the same image twice. A model overfits when its accuracy on training images is far above its accuracy on new ones. The grid of N and M in RandAugment is simply every combination of the few values you try (N in {1, 2} and M in {0.25, 0.5, 1.0} gives 2 x 3 = 6 combinations, each needing one training run).
Comparison
| AutoAugment | RandAugment | |
|---|---|---|
| What is searched | Which operations, their probabilities and magnitudes, in sub-policies | Number of operations N and a shared magnitude M (common formulation) |
| Search space | Enormous (computed below for an illustrative setting) | A grid of a few dozen configurations |
| Cost | Many training runs, often on a smaller proxy task, before the real training | A few full training runs, on the real task |
| Tuning effort | The search itself; a policy found on one dataset may not transfer | Tune N and M like any hyperparameter |
| Strength | A tailored policy; can learn that some operations hurt | Simple, reproducible, no proxy |
| Weakness | Cost; proxy mismatch | Applies every listed operation equally often, so a harmful operation in the list costs accuracy |
A measurement on a toy task
This is a stand-in for an image model: logistic regression on scikit-learn's 8 by 8 digit images, trained on 600 images. It trains the model on unshifted, undimmed images and tests on images altered the way a deployment might alter them, in two scenarios. Scenario A: every validation and test image is shifted by up to one pixel in each direction, and the team's manual policy (shift only) is the right guess. Scenario B: every validation and test image is dimmer and noisier (a poor sensor), and the team's manual guess is still "shift only", which is now the wrong guess. The four operations are shift, noise, vertical flip (which makes 6 and 9, among others, harder to tell apart) and brightness. Policies compared: none; the manual shift-only policy; a RandAugment-style grid over N in {1, 2} and magnitude in {0.25, 0.5, 1.0} (6 runs), once with all four operations and once with the flip removed; and a random search over 10 policies of three (operation, probability, magnitude) triples. The toy is deliberately small and its operation list contains a harmful operation, so its ranking (manual best in scenario A, no augmentation as good as anything in scenario B) is a property of this setup and not evidence about the real methods. That random search is only a stand-in for AutoAugment: the real method searches a vastly larger space with a learning-based search algorithm, so these numbers describe this toy and say nothing about how well the real methods perform. In each scenario the validation images are altered like the test images, each configuration is chosen by validation accuracy and scored on the test set, and results are averaged over 5 seeds (each seed redraws the split).
import numpy as np
from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression
X0, y0 = load_digits(return_X_y=True); X0 = X0.reshape(-1, 8, 8) / 16.0
OPS = ["shift", "noise", "flipud", "brightness"]
def shift_img(img, dx, dy):
out = np.zeros_like(img)
ys, xs = slice(max(dy, 0), 8 + min(dy, 0)), slice(max(dx, 0), 8 + min(dx, 0))
yd, xd = slice(max(-dy, 0), 8 + min(-dy, 0)), slice(max(-dx, 0), 8 + min(-dx, 0))
out[ys, xs] = img[yd, xd]
return out
def apply(img, op, m, rng): # m in [0, 1] is the magnitude
if op == "shift":
k = int(round(2 * m)); return shift_img(img, int(rng.integers(-k, k + 1)), int(rng.integers(-k, k + 1)))
if op == "noise": return np.clip(img + rng.normal(0, 0.3 * m, img.shape), 0, 1)
if op == "flipud": return img[::-1] # ignores magnitude; changes which digit looks like which
return np.clip(img * (1 + rng.uniform(-0.5, 0.5) * m), 0, 1)
def augment(X, y, policy, rng, copies=2):
"""policy = ("rand", ops, N, M): N ops drawn uniformly from ops, one shared magnitude M (RandAugment style)
policy = ("list", [(op, prob, magnitude), ...]): every listed op tried independently (policy-search style)"""
Xs, ys = [X], [y]
for _ in range(copies):
new = []
for img in X:
if policy[0] == "rand":
_, ops, n, m = policy
for op in rng.choice(ops, size=n): img = apply(img, str(op), m, rng)
else:
for op, p, m in policy[1]:
if rng.random() < p: img = apply(img, op, m, rng)
new.append(img)
Xs.append(np.array(new)); ys.append(y)
return np.concatenate(Xs).reshape(-1, 64), np.concatenate(ys)
def fit_score(policy, data, rng):
(Xtr, ytr), (Xev, yev) = data
Xa, ya = augment(Xtr, ytr, policy, rng) if policy else (Xtr.reshape(-1, 64), ytr)
return LogisticRegression(max_iter=200).fit(Xa, ya).score(Xev.reshape(-1, 64), yev)
def shifted(X, rng): # deployment A: every image moved by up to 1 pixel
return np.array([shift_img(i, int(rng.integers(-1, 2)), int(rng.integers(-1, 2))) for i in X])
def dim_noisy(X, rng): # deployment B: every image dimmer and noisier (a poor sensor)
return np.clip(X * rng.uniform(0.5, 1.0, (len(X), 1, 1)) + rng.normal(0, 0.25, X.shape), 0, 1)
def one_seed(seed, deploy, manual):
rng = np.random.default_rng(seed); idx = rng.permutation(len(y0))
tr, va, te = idx[:600], idx[600:900], idx[900:]
Xtr, ytr = X0[tr], y0[tr]
Xva, Xte = deploy(X0[va], rng), deploy(X0[te], rng) # validation mirrors deployment
val, test = ((Xtr, ytr), (Xva, y0[va])), ((Xtr, ytr), (Xte, y0[te]))
def choose(cands): # pick by validation accuracy, report test accuracy
v = [fit_score(p, val, np.random.default_rng(seed)) for p in cands]
return cands[int(np.argmax(v))]
sc = lambda pol, d=test: fit_score(pol, d, np.random.default_rng(seed))
res = {"none": sc(None), "manual guess: shift only": sc(manual)}
for name, ops in (("RandAugment grid, all 4 ops", OPS), ("RandAugment grid, flipud removed", [o for o in OPS if o != "flipud"])):
grid = [("rand", ops, n, m) for n in (1, 2) for m in (0.25, 0.5, 1.0)] # 6 training runs
res[name] = sc(choose(grid))
pols = [("list", [(OPS[rng.integers(4)], float(rng.choice([0.2, 0.5, 0.8, 1.0])), float(rng.choice([0.25, 0.5, 0.75, 1.0]))) for _ in range(3)]) for _ in range(10)]
res["random policy search, 10 policies"] = sc(choose(pols))
return res
SHIFT_ONLY = ("list", [("shift", 1.0, 0.5)])
for title, deploy in (("A: deployment moves the digit by up to 1 pixel (the team's manual guess is right)", shifted),
("B: deployment is dimmer and noisier (the team's manual guess, shift only, is wrong)", dim_noisy)):
R = [one_seed(s, deploy, SHIFT_ONLY) for s in range(5)]
print("Scenario " + title)
print("policy test accuracy, mean +- sd over 5 seeds")
for k in R[0]:
v = np.array([r[k] for r in R]); print(f"{k:36s} {v.mean():.3f} +- {v.std():.3f}")
print("training runs spent on the search: RandAugment grid 6, random policy search 10")
print("grid configurations here:", 2 * 3, "| random policies here:", (4 * 4 * 4) ** 3)
print("illustrative AutoAugment-style space (16 ops, 11 probs, 10 magnitudes, 2 ops per sub-policy, 5 sub-policies):", f"{(16 * 11 * 10) ** 10:.1e}")
Output:
Scenario A: deployment moves the digit by up to 1 pixel (the team's manual guess is right)
policy test accuracy, mean +- sd over 5 seeds
none 0.363 +- 0.010
manual guess: shift only 0.585 +- 0.012
RandAugment grid, all 4 ops 0.403 +- 0.012
RandAugment grid, flipud removed 0.487 +- 0.009
random policy search, 10 policies 0.466 +- 0.052
Scenario B: deployment is dimmer and noisier (the team's manual guess, shift only, is wrong)
policy test accuracy, mean +- sd over 5 seeds
none 0.794 +- 0.016
manual guess: shift only 0.581 +- 0.006
RandAugment grid, all 4 ops 0.693 +- 0.021
RandAugment grid, flipud removed 0.773 +- 0.015
random policy search, 10 policies 0.806 +- 0.015
training runs spent on the search: RandAugment grid 6, random policy search 10
grid configurations here: 6 | random policies here: 262144
illustrative AutoAugment-style space (16 ops, 11 probs, 10 magnitudes, 2 ops per sub-policy, 5 sub-policies): 2.9e+32
What it shows, on this toy only. In scenario A, augmentation that matches the deployment shift is worth more than any amount of search (0.585 manual against 0.363 with none). Uniformly sampling from an operation list that contains a harmful operation gives 0.403, and removing that one operation raises it to 0.487, so the list matters as much as the tuning; a real RandAugment list is built from operations known to be safe for the data, and the flip is here on purpose as the bad entry. In scenario B the same manual shift-only guess is wrong and costs accuracy: 0.581 against 0.794 with no augmentation at all, a 0.213 loss from a confident, unverified choice. The validation-driven methods avoid that loss: the flip-free grid reaches 0.773 and the random search 0.806, which is about the same as no augmentation (0.794; the standard deviations are 0.015 to 0.016), so in this toy there was little for a search to gain over doing nothing in scenario B. No searched policy clearly beat doing nothing there, and none beat the right manual guess in scenario A. What the validation set bought was protection from a bad choice, and the cheapest way to get that is also the simplest: score the manual policy against no augmentation on validation images (2 runs) before spending 6 or 10 more. The random policy search varies the most across seeds in scenario A (standard deviation 0.052 against 0.009 to 0.012 for the others), because 10 random policies scored on 300 validation images sometimes pick a poor one. The search signal in both scenarios is the validation set, which only reflects what the validation images contain.
Search-space sizes, multiplied out. The grid has 2 x 3 = 6 configurations. The random policy space is (4×4×4)3=643=262,144: each of 3 triples picks one of 4 operations, 4 probabilities and 4 magnitudes. For the illustrative AutoAugment-style setting, one operation slot has 16×11×10=1,760 choices (16 operations, 11 probabilities, 10 magnitudes); a sub-policy has 2 such slots and a policy has 5 sub-policies, so 10 slots in all, giving 176010≈2.9×1032. That number comes from this arithmetic, not from a statement about any published setting.
When do searched policies beat manual augmentation?
- When you do not know which invariances matter (unfamiliar imagery, many classes) and a large benchmark-style dataset and model are available, as in the published CIFAR-10, ImageNet and SVHN results above. Scenario B is a small reminder that a confident manual guess can be wrong, and that validating it against no augmentation catches that.
- When the training set is small and the model large, so regularization from varied copies is the main lever.
- When you can afford the search or can reuse a policy found on a similar dataset (check it transfers: validate it on yours).
- They do not help when the augmentations are mismatched with deployment (the flip case above), when validation data does not represent deployment, or when the weakness is something augmentation cannot create, such as a missing class of object.
Trade-offs and mistakes
Tuning strength on a validation set too small to separate the options; copying a policy tuned on natural photos to medical or document images, where a flip or colour shift can change the label; counting only the search cost and forgetting that stronger augmentation also needs longer training to converge; comparing a searched policy to no augmentation instead of to a sensible manual baseline, and, in the other direction, crediting a search for avoiding a bad manual choice when no augmentation would have avoided it equally well.
Unlock Full Question Bank
Get access to all 10 Computer Vision interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.