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.
Explain Non-Maximum Suppression (NMS) used in object detection. Provide a clear algorithmic description (greedy NMS) and discuss drawbacks such as suppressing nearby true positives for crowded scenes. How does Soft-NMS differ and when would you use it?
Sample Answer
The idea in plain words
A detector looks at the image through thousands of overlapping windows, so a single real object is usually flagged by many nearby boxes, each with its own confidence score. Non-maximum suppression (NMS) cleans this up: keep the highest-scoring box, throw away the boxes that overlap it too much (measured by IoU, intersection over union, the shared area divided by the combined area), then repeat with what is left. The weakness is that "overlaps a lot" does not always mean "duplicate": in a crowd, two different people really do overlap. Soft-NMS keeps the same loop but turns the hard delete into a score reduction, so a genuine neighbour can survive with a lower score.
Greedy NMS, step by step
For the boxes of one class, with a score for each and an IoU threshold T:
- Sort the boxes by score, highest first.
- Take the top box and add it to the output.
- Compute its IoU with every remaining box and delete those whose IoU is above T.
- Repeat from step 2 until nothing remains.
Cost: sorting is O(nlogn). The loop is O(n2) IoU computations in the worst case (when nothing overlaps, every box is compared with every later one). The loop is sequential because each kept box changes what is left, which is why it is awkward to run in parallel. In a multi-class detector it is run per class, so a person box never suppresses a chair box.
Where it breaks: crowded scenes
The program below uses one class with five boxes: two people standing close together (box 0 is the best box for person P and box 1 a duplicate of it; box 2 is the best box for person Q and box 3 a duplicate of it) and one separate object (box 4). The true count is 3 objects. It runs hard NMS at two thresholds and then Soft-NMS in its two common forms.
import numpy as np
def iou(a, b):
iw = max(0.0, min(a[2], b[2]) - max(a[0], b[0]))
ih = max(0.0, min(a[3], b[3]) - max(a[1], b[1]))
inter = iw * ih
ar = lambda r: (r[2] - r[0]) * (r[3] - r[1])
return inter / (ar(a) + ar(b) - inter)
# One class. Two people stand close together (boxes 0-1 and 2-3 each cover one person),
# and the detector also fires on a far-away object (box 4).
boxes = np.array([[100, 50, 200, 250], # person P, best box
[104, 54, 204, 254], # person P, duplicate
[120, 60, 220, 260], # person Q, standing close behind P
[123, 64, 223, 264], # person Q, duplicate
[400, 50, 480, 200]], # a separate object
dtype=float)
scores = np.array([0.95, 0.90, 0.85, 0.80, 0.70])
print("IoU between P and Q (best boxes):", round(iou(boxes[0], boxes[2]), 4))
def hard_nms(boxes, scores, thr):
order = list(np.argsort(-scores, kind="stable"))
keep = []
while order:
i = order.pop(0) # highest remaining score
keep.append(i)
order = [j for j in order if iou(boxes[i], boxes[j]) <= thr] # drop overlaps above thr
return keep
def soft_nms(boxes, scores, method, sigma=0.5, thr=0.5, floor=0.001, trace=False):
s = scores.copy()
idx = list(range(len(s)))
out = []
while idx:
m = max(idx, key=lambda k: s[k]) # highest current score
idx.remove(m)
out.append((m, s[m]))
if trace:
print(f"pick box {m} at {s[m]:.3f}")
for j in idx:
o = iou(boxes[m], boxes[j])
before = s[j]
if method == "linear":
s[j] *= (1 - o) if o > thr else 1.0
else: # gaussian
s[j] *= np.exp(-(o * o) / sigma)
if trace and o > 0:
print(f" box {j}: IoU {o:.3f}, score {before:.3f} -> {s[j]:.3f}")
idx = [j for j in idx if s[j] >= floor]
return out
print("hard NMS at 0.5 keeps boxes:", [int(i) for i in hard_nms(boxes, scores, 0.5)])
print("hard NMS at 0.7 keeps boxes:", [int(i) for i in hard_nms(boxes, scores, 0.7)])
for method in ("linear", "gaussian"):
res = soft_nms(boxes, scores, method)
print(f"soft NMS ({method}) final scores:", {int(k): round(float(v), 3) for k, v in res})
print("linear Soft-NMS, one line per decay:")
soft_nms(boxes, scores, "linear", trace=True)
The complete output:
IoU between P and Q (best boxes): 0.6129
hard NMS at 0.5 keeps boxes: [0, 4]
hard NMS at 0.7 keeps boxes: [0, 2, 4]
soft NMS (linear) final scores: {0: 0.95, 4: 0.7, 3: 0.354, 1: 0.038, 2: 0.01}
soft NMS (gaussian) final scores: {0: 0.95, 4: 0.7, 3: 0.429, 1: 0.085, 2: 0.03}
linear Soft-NMS, one line per decay:
pick box 0 at 0.950
box 1: IoU 0.888, score 0.900 -> 0.101
box 2: IoU 0.613, score 0.850 -> 0.329
box 3: IoU 0.558, score 0.800 -> 0.354
pick box 4 at 0.700
pick box 3 at 0.354
box 1: IoU 0.625, score 0.101 -> 0.038
box 2: IoU 0.906, score 0.329 -> 0.031
pick box 1 at 0.038
box 2: IoU 0.687, score 0.031 -> 0.010
pick box 2 at 0.010
Reading it:
- P and Q are different people but their best boxes have IoU 0.6129.
- Hard NMS at T=0.5 keeps boxes 0 and 4. Box 2, a correct detection of person Q with score 0.85, is deleted because it overlaps the higher-scoring box 0 by 0.6129 > 0.5. One person is missed: a false negative caused by the suppression rule itself.
- Hard NMS at T=0.7 keeps boxes 0, 2 and 4, which is the correct set of three here. The cost of raising T is that more true duplicates slip through; in this tiny example the duplicates happen to overlap their partner above 0.7 (0.888 and 0.906, both visible in the trace below), so 0.7 happens to work. This toy therefore does not show hard NMS failing at its best threshold; it shows the failure at 0.5 and the reason a fixed cutoff is fragile. A loosely placed duplicate with IoU 0.6 to its partner would survive a 0.7 cutoff and appear as a false positive, while a real neighbour at 0.65 would be deleted by a 0.6 cutoff. Because IoU alone cannot tell a duplicate from a neighbour, no single T suits both crowds and sparse scenes.
Soft-NMS
Instead of deleting a box that overlaps the current best box M, Soft-NMS lowers its score si as a function of the overlap. Here IoU(M,bi) is the overlap between M and box bi, T is the threshold and σ is a width parameter:
linear:si←{si(1−IoU(M,bi))siif IoU(M,bi)>Totherwise Gaussian:si←siexp(−σIoU(M,bi)2)The loop is the same: repeatedly take the highest remaining score, decay the others, and finish by discarding boxes whose score fell under a small floor or a final reporting threshold. Note that every decay uses the CURRENT score of the box, so a box can be decayed several times, once by each higher-scoring box that is picked before it.
To check the linear numbers by hand, follow the trace the program prints (box 2 is the best box of person Q, box 3 its duplicate):
- Pick box 0 (0.95). Box 1 overlaps it at 0.888, so 0.90×(1−0.888)=0.101. Box 2 overlaps at 0.613, so 0.85×(1−0.613)=0.329. Box 3 overlaps at 0.558, so 0.80×(1−0.558)=0.354. Box 4 has no overlap and keeps 0.7.
- The highest remaining score is now box 4 (0.7), which changes nothing. Next is box 3 (0.354), because box 3 overlapped box 0 less than box 2 did and lost less score. Box 3 overlaps box 2 at 0.906, so box 2 falls again: 0.329×(1−0.906)=0.031. Box 3 overlaps box 1 at 0.625, so box 1 falls to 0.101×(1−0.625)=0.038.
- Box 1 (0.038) is picked and overlaps box 2 at 0.687, so box 2 ends at 0.031×(1−0.687)=0.010.
The result looks odd: the box with the higher starting score for Q (box 2, 0.85) ends below its duplicate (box 3). That is an accident of geometry, since box 3 sits slightly farther from person P and so lost less score to box 0. Both boxes cover the same person, so reporting box 3 for Q is acceptable; Soft-NMS makes no promise about which box of a pair survives, only that one of them survives with a usable score. The Gaussian form does the same with smoother decay and ends with box 3 at 0.429.
So both forms leave box 0 at 0.95 and box 4 at 0.7, push the duplicate of P (box 1) down to 0.038 (linear) and 0.085 (Gaussian), and keep person Q alive as box 3. A final score cut of 0.3 returns three boxes (0, 4, 3), the right count. The IoU cutoff is not gone, though: it is replaced by other choices, namely T (linear) or σ (Gaussian; larger σ decays less) and the final score cut. Choose them on validation data by the metric you care about (for example AP); the 0.3 here is a demo value, and tuning it on the test set would leak test information into the result. A wide gap between the real scores (0.95, 0.7, 0.354) and the duplicates (0.038 and below) is what makes any cut in between work.
When to use which
- Hard NMS: sparse scenes (few, well-separated objects), or when downstream code needs exactly one box per object with no extra score cutoff. It is simple, fast and has one hyperparameter.
- Soft-NMS: crowded scenes (people, fruit on a tree, birds) and metrics that reward recall such as AP, where keeping a low-score true positive helps more than a low-score false positive hurts. Here recall is the fraction of real objects that receive a correct box, and AP (average precision) summarises precision across recall levels by ranking all boxes by score; a surviving neighbour with a low score sits at the bottom of that ranking, so it adds recall while costing little precision. It adds a parameter (σ or T) and a final score cutoff to choose, and leaves more low-score boxes in the raw output.
Pitfalls
- NMS uses only classification confidence to pick the winner, so a high-score but poorly placed box can suppress a better-placed one.
- Applying NMS across classes by mistake deletes true neighbours of different classes; run it per class or add the class id to the keep rule.
- Tune the threshold on validation data per scene type; a threshold tuned on street scenes is wrong for a crowd.
- Some detectors avoid NMS entirely by training with a one-to-one matching of predictions to objects, which removes the duplicates at the source.
You must build an image classifier for a niche product category with only a few hundred labeled images, but you have access to large generic image datasets. Propose a strategy and say what could make it fail.
Sample Answer
The idea in plain words
A few hundred labelled images are too few to learn visual features from scratch, but large generic image collections have already taught a backbone (the feature-extracting part of a network, everything before the final classification layer) what edges, textures, shapes and parts look like. Transfer learning reuses that: you keep the backbone and train only what is specific to your problem. The strategy is to start with the cheapest version (frozen backbone features plus a simple classifier on top), measure it honestly, and move to partial fine-tuning only if the measurement says there is headroom. What can make it fail is mostly not the model; it is a domain gap, an evaluation that leaks, and shortcuts in the data.
The strategy, in order
- Fix the evaluation before touching a model. With a few hundred images, the validation protocol decides whether you can trust any result. Define the unit of generalisation (a new product, a new photo session, a new store) and split by it, so that images of the same physical item never appear on both sides. Use k-fold cross-validation (split the data into k parts, train on k-1, test on the remaining one, rotate) with that grouping, report per-class recall (for each class separately, the share of its images the model found, so a rare class cannot hide behind a big one), and keep a final test set you look at once.
- Frozen features plus a linear classifier (a linear probe). Pass each image through the pretrained backbone once, store the feature vector (an embedding, a fixed-length list of numbers summarising the image), and train a regularised logistic regression on top (logistic regression is a linear classifier that outputs class probabilities; regularised means it is penalised for large weights, which curbs overfitting when examples are few; the setting
Cis the inverse of that penalty, so a smallCpulls the weights harder towards zero, and a code example below compares three values). It trains in seconds, has few parameters to overfit, and is a strong baseline. Compare two or three candidate backbones this way, choosing the one whose features separate your classes best on grouped cross-validation, not the one with the best name or generic benchmark score. - Partial fine-tuning if the probe leaves headroom (headroom means a gap between the probe's score and the score you need). Fine-tuning means continuing to train the pretrained weights on your data; here you unfreeze the last block or two of the backbone (let those layers learn again while the earlier ones stay fixed), use a small learning rate for them (and a larger one for the new classifier), apply label-preserving augmentation (crops, flips if the product has no handedness, colour jitter within what the real cameras produce), stop early on grouped validation, and compare to the probe on the same folds. With a few hundred images, full fine-tuning at a high rate tends to erase the pretrained features; if it does not beat the probe on grouped folds, ship the probe.
- Get more signal cheaply. Writing down labelling rules for look-alike classes and labelling more images is the core move. Choose which images to label next with active learning (the model picks which unlabelled images a person should label next). The common rule, most uncertain first, tends to suit larger labelling budgets; at a budget of a few hundred labels, published work on low-budget active learning (Hacohen, Dekel and Weinshall, 2022, "Active Learning on a Budget: Opposite Strategies Suit High and Low Budgets") finds that typical, representative examples are the better ones to query. So compare any selection rule against random picks on grouped validation before trusting it. Two heavier options come last and are rarely the first thing to try with a few hundred images: pseudo-labels (the model's own confident predictions on unlabelled images used as extra training labels, which can reinforce its mistakes) and self-supervised adaptation of the backbone (continuing to train it on your unlabelled product images with a label-free task). Try them only if steps 1 to 3 plateau and you have a large unlabelled pool.
- Plan for abstention. A niche product classifier will see items from no known class. Abstention means the model declines to answer: choose a confidence threshold on validation data (the minimum predicted probability for the top class below which the image goes to a person), rather than forcing a label. The threshold trades coverage for accuracy, and the code example below prints that trade-off.
Worked example: why step 1 comes first
The program below uses a stand-in for backbone features: random vectors built as category signal plus item-specific appearance plus photo noise, for 3 categories with 20 physical items each and 5 photos per item (300 images). A real system would take these vectors from a pretrained backbone; here the point is the evaluation, not the features. The classifier is logistic regression with C=1.0. It reports accuracy under three protocols averaged over 10 generated datasets: a random 5-fold split, a split that keeps every item's photos together, and the grouped split with a shared offset added to every test embedding to imitate a new camera or background.
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, StratifiedGroupKFold
# STAND-IN for frozen-backbone embeddings: 3 product categories, 20 physical items per category, 5 photos per item.
# embedding = category signal + item-specific appearance + photo noise. A real system would use a pretrained backbone's features.
D, CLASSES, ITEMS, PHOTOS = 32, 3, 20, 5
def make(seed):
rng = np.random.default_rng(seed)
cmean = rng.standard_normal((CLASSES, D)) * 0.35
X, y, g = [], [], []
for c in range(CLASSES):
for i in range(ITEMS):
item = rng.standard_normal(D) * 1.0 # what makes THIS item look like itself (shared by its photos)
for _ in range(PHOTOS):
X.append(cmean[c] + item + 0.5 * rng.standard_normal(D))
y.append(c); g.append(c * ITEMS + i)
return np.array(X), np.array(y), np.array(g), cmean
def cv_acc(X, y, splits, shift=None):
accs = []
for tr, te in splits:
Xte = X[te] + (shift if shift is not None else 0)
clf = LogisticRegression(C=1.0, max_iter=2000).fit(X[tr], y[tr])
accs.append(clf.score(Xte, y[te]))
return float(np.mean(accs))
print("300 images (3 categories x 20 items x 5 photos); linear probe on stand-in embeddings; 5-fold; mean over 10 datasets")
rows = {"random split": [], "split by item": [], "split by item + camera shift": []}
for seed in range(10):
X, y, g, _ = make(seed)
rand = list(StratifiedKFold(5, shuffle=True, random_state=0).split(X, y))
grp = list(StratifiedGroupKFold(5, shuffle=True, random_state=0).split(X, y, g))
rows["random split"].append(cv_acc(X, y, rand))
rows["split by item"].append(cv_acc(X, y, grp))
shift = np.random.default_rng(1000 + seed).standard_normal(D) * 0.8 # a new camera/background adds a shared offset to every test embedding
rows["split by item + camera shift"].append(cv_acc(X, y, grp, shift))
for k, v in rows.items():
print(f"{k:30s} accuracy mean {np.mean(v):.3f} (min {np.min(v):.3f}, max {np.max(v):.3f})")
print("chance level: 0.333")
# does any item appear on both sides of the split?
X, y, g, _ = make(0)
leak = lambda splits: sum(len(set(g[tr]) & set(g[te])) for tr, te in splits)
print("items present in both train and test folds, summed over 5 folds -> random:", leak(list(StratifiedKFold(5, shuffle=True, random_state=0).split(X, y))),
"| grouped:", leak(list(StratifiedGroupKFold(5, shuffle=True, random_state=0).split(X, y, g))))
Output:
300 images (3 categories x 20 items x 5 photos); linear probe on stand-in embeddings; 5-fold; mean over 10 datasets
random split accuracy mean 0.903 (min 0.800, max 0.953)
split by item accuracy mean 0.639 (min 0.503, max 0.797)
split by item + camera shift accuracy mean 0.611 (min 0.470, max 0.773)
chance level: 0.333
items present in both train and test folds, summed over 5 folds -> random: 206 | grouped: 0
The same data and the same classifier score 0.903 under a random split and 0.639 when items are kept together; chance is 0.333. The gap is leakage: in the random split, 206 item-fold pairs have an item on both sides (the sum over 5 folds, for the first dataset), so the classifier memorises item appearance instead of category. The shift to a new camera lowers the grouped score further, to 0.611. The spread across datasets (0.503 to 0.797 for the grouped split) also shows how noisy a score from 300 images is, which is why you repeat or cross-validate before deciding. These numbers describe this stand-in and its settings only; they show the direction and the size of the trap, not what a real dataset would score.
The pipeline in code: embeddings, probe, grouped folds, abstention
The worked example above shows the evaluation trap. This program shows the strategy itself, end to end. The images and the backbone are both stand-ins: the images are 12 by 12 synthetic arrays and the "backbone" is a small untrained convolutional network, so its features are random; a real system would load a pretrained backbone here and feed it real photos, and the steps after the embeddings would be unchanged. It extracts one embedding per image with gradients off, compares three values of C on grouped 5-fold cross-validation (on the first dataset, then on ten others), collects an out-of-fold confidence for each image, and prints what each abstention threshold costs and buys.
import numpy as np
import torch
from torch import nn
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedGroupKFold
torch.set_num_threads(1)
# The pipeline of steps 1 and 2: extract embeddings with a frozen backbone, fit a linear probe, grouped cross-validation, abstention threshold.
# STAND-INS: the "images" are 12 x 12 synthetic arrays and the "backbone" is a small UNTRAINED convolutional network, so the features
# are random. A real system would load a pretrained backbone here and feed it real photos; nothing below depends on that choice.
CLASSES, ITEMS, PHOTOS = 3, 20, 5
def make_embeddings(seed):
"""Synthetic images (class prototype + item appearance + photo noise) and their frozen-backbone embeddings."""
rng = np.random.default_rng(seed)
protos = 0.7 * rng.standard_normal((CLASSES, 12, 12))
imgs, y, g = [], [], []
for c in range(CLASSES):
for i in range(ITEMS):
item = 1.0 * rng.standard_normal((12, 12)) # appearance shared by the photos of one physical item
for _ in range(PHOTOS):
imgs.append(protos[c] + item + 0.6 * rng.standard_normal((12, 12))); y.append(c); g.append(c * ITEMS + i)
X_img = torch.tensor(np.stack(imgs), dtype=torch.float32)[:, None]
torch.manual_seed(seed)
backbone = nn.Sequential(nn.Conv2d(1, 8, 3), nn.ReLU(), nn.AdaptiveAvgPool2d(2), nn.Flatten()) # frozen: no optimiser ever sees it
backbone.eval()
with torch.no_grad(): # no gradients: the backbone is only a feature extractor
emb = backbone(X_img).numpy() # (300 images, 32 numbers each): one embedding per image
return emb, np.array(y), np.array(g)
emb, y, g = make_embeddings(0)
print("embeddings:", emb.shape)
folds = list(StratifiedGroupKFold(5, shuffle=True, random_state=0).split(emb, y, g)) # an item's photos never straddle the split
for C in (0.01, 1.0, 100.0): # C is the INVERSE regularisation strength: small C = stronger pull towards small weights
accs = [LogisticRegression(C=C, max_iter=5000).fit(emb[a], y[a]).score(emb[b], y[b]) for a, b in folds]
print(f"C={C:<6} grouped 5-fold accuracy {np.mean(accs):.3f}")
# the same comparison on 10 other generated datasets, so the ordering of the C values is not read off one draw
means = {C: [] for C in (0.01, 1.0, 100.0)}
for seed in range(1, 11):
e2, y2, g2 = make_embeddings(seed)
f2 = list(StratifiedGroupKFold(5, shuffle=True, random_state=0).split(e2, y2, g2))
for C in means:
means[C].append(np.mean([LogisticRegression(C=C, max_iter=5000).fit(e2[a], y2[a]).score(e2[b], y2[b]) for a, b in f2]))
for C, v in means.items():
print(f"C={C:<6} over 10 other datasets: mean {np.mean(v):.3f}, min {np.min(v):.3f}, max {np.max(v):.3f}")
print("datasets where C=100.0 beats C=1.0:", int(np.sum(np.array(means[100.0]) > np.array(means[1.0]))), "of 10; where C=0.01 is the lowest:",
int(np.sum((np.array(means[0.01]) < np.array(means[1.0])) & (np.array(means[0.01]) < np.array(means[100.0])))), "of 10")
# out-of-fold confidence for every image (each image is scored by a probe that never saw its item), with C = 1.0
conf = np.zeros(len(y)); correct = np.zeros(len(y), bool)
for a, b in folds:
probe = LogisticRegression(C=1.0, max_iter=5000).fit(emb[a], y[a])
conf[b] = probe.predict_proba(emb[b]).max(1); correct[b] = probe.predict(emb[b]) == y[b]
p, n = correct.mean(), len(y)
print(f"pooled out-of-fold accuracy {p:.3f} on {n} images; standard error sqrt(p(1-p)/n) = {np.sqrt(p * (1 - p) / n):.3f}")
print("abstention threshold -> share of images answered, accuracy on the answered ones")
for t in (0.0, 0.5, 0.6, 0.7):
keep = conf >= t
print(f" confidence >= {t}: answered {keep.mean():.2f}, accuracy {correct[keep].mean():.3f}")
print("for comparison: accuracy 0.60 measured on 150 images has standard error", round(float(np.sqrt(0.6 * 0.4 / 150)), 3))
Output:
embeddings: (300, 32)
C=0.01 grouped 5-fold accuracy 0.610
C=1.0 grouped 5-fold accuracy 0.700
C=100.0 grouped 5-fold accuracy 0.693
C=0.01 over 10 other datasets: mean 0.732, min 0.640, max 0.920
C=1.0 over 10 other datasets: mean 0.783, min 0.673, max 0.950
C=100.0 over 10 other datasets: mean 0.821, min 0.693, max 0.970
datasets where C=100.0 beats C=1.0: 9 of 10; where C=0.01 is the lowest: 10 of 10
pooled out-of-fold accuracy 0.700 on 300 images; standard error sqrt(p(1-p)/n) = 0.026
abstention threshold -> share of images answered, accuracy on the answered ones
confidence >= 0.0: answered 1.00, accuracy 0.700
confidence >= 0.5: answered 0.70, accuracy 0.789
confidence >= 0.6: answered 0.39, accuracy 0.846
confidence >= 0.7: answered 0.21, accuracy 0.887
for comparison: accuracy 0.60 measured on 150 images has standard error 0.04
Reading it: each image becomes 32 numbers. On the first dataset C=1.0 and C=100.0 are about equal (0.700 and 0.693) and a very small C is lower (0.610). Over ten other generated datasets the smallest C is the lowest every time and C=100.0 beats C=1.0 in 9 of 10 (means 0.821 and 0.783), so which penalty strength wins depends on the draw of data, and the first dataset alone would have suggested a tie. Treat the penalty strength as a setting to check on grouped folds rather than assume; the features here are random, so which C wins on real embeddings is a different matter. To choose the abstention threshold, pick the coverage you can afford: at a confidence of 0.6 the probe answers 39 percent of images and is right on 84.6 percent of them, while the rest go to a person. The standard error of an accuracy p measured on n images is p(1−p)/n: for 0.700 on 300 images it is 0.026, and an accuracy of 0.60 measured on 150 images has a standard error of 0.6×0.4/150=0.04, so a 0.62 score on such a set is well inside the noise of a 0.60 one. This standard error treats images as independent; photos of one item are correlated, so the real uncertainty is larger, which is one more reason a 0.60 vs 0.62 difference is not a reason to prefer the heavier model.
What can make it fail
- Domain gap. If the niche products look nothing like the generic images (industrial parts, macro shots, microscopy, textures that differ by tiny details), the backbone's features may not separate the classes. Symptom: the probe sits near the accuracy of a trivial baseline and fine-tuning barely moves it. Response: fine-tune deeper layers, try a backbone pretrained on something closer, or collect more labels.
- Leaky validation (shown above): near-duplicate photos, frames from one video, same item in many views. Check by grouping and by counting overlap.
- Shortcut features. The classifier may use the background, the lighting, the watermark or the shelf instead of the product. Check by testing on images with a different background, by masking the object or the background and seeing which one the score depends on, and by looking at the images the model gets wrong.
- Class imbalance and fine-grained classes. Report per-class recall, not only accuracy; a majority-class guess can look good.
- Label noise. With few images a handful of wrong labels matters; review the most confident mistakes.
- Deployment shift. New cameras, seasons, packaging redesigns. Keep a small labelled sample from production and re-measure on it.
- Licensing or provenance of the pretrained weights, for commercial use.
Common mistakes
Tuning many things on the same few hundred validation images, so the chosen configuration is the one that fits their noise; reporting accuracy from a random split; fine-tuning everything at the rate used for training from scratch; and forgetting that the "known classes only" assumption fails the day an unknown product shows up.
You have two segmentation models: Model A has higher mIoU but is overconfident and poorly calibrated; Model B has slightly lower mIoU but better calibrated probabilities. For a safety-critical application where false positives are costly, explain how you would decide which model to deploy and describe recalibration or architectural modifications to improve reliability.
Sample Answer
Direct answer
I would not pick between them on mIoU. mIoU (mean intersection over union: for each class, the overlap between predicted and true pixels divided by their union, averaged over classes) measures where the decision boundary lies, and it is blind to how trustworthy the probabilities are. The two properties are separable: a simple recalibration step called temperature scaling changes the confidence of every prediction but never changes which class wins (the class with the largest score, the argmax), so it leaves mIoU exactly unchanged. So the plan is: recalibrate Model A on held-out data, then compare both models on the metric the safety case actually cares about, which is how many false positives you get at the confidence level you act on, and how much true signal you still catch there. In the simulation below, the recalibrated Model A is at least as precise as Model B at the 0.9 confidence level (0.959 against 0.953) and finds more of the true object (recall 0.302 against 0.215), so I would deploy A after recalibration, provided the same holds on real held-out data from the deployment setting. That result depends on A having real ranking skill (its scores put true object pixels above background pixels better than B's do); a second variant of A with no such advantage ties with B after recalibration, and then the choice rests on robustness under shift and on cost.
Terms. Calibrated: among pixels where the model says 90 percent, about 90 percent really are that class. Overconfident: the model's stated probabilities are higher than its hit rate. A reliability diagram plots stated confidence on the x axis against the observed fraction correct on the y axis; a calibrated model follows the diagonal and an overconfident one sags below it. The operating point is the confidence threshold at which the system acts. False positive: the model marks a pixel as the object when it is not. Temperature scaling: divide all logits (the pre-softmax scores) by one number T chosen on a validation set to minimize negative log-likelihood (NLL, the average of −log of the probability given to the true class).
What to measure, in order
- Calibration, with its data. A reliability diagram (stated confidence on one axis, observed accuracy on the other) and expected calibration error (ECE): split predictions into confidence bins, and average the gap between accuracy and confidence in each bin, weighted by the bin's share of predictions. ECE depends on the number of bins and on the binning, so report the convention (below: 15 equal-width bins of top-label confidence). Also report NLL, which does not depend on binning. For segmentation, compute these per pixel, and also look separately at pixels near object boundaries, because boundary pixels are where the model is least certain and background pixels dominate the count.
- Operating-point metric. Safety-critical use means the system acts when confidence is high, so measure precision (share of flagged pixels that are truly the object) and recall (share of true object pixels that are flagged) at the confidence threshold you will use. A false positive cost sets this threshold.
- Robustness. The same metrics under distribution shift (deployment images that differ from the training images, for example a new scanner or new lighting), because calibration fitted on one distribution can degrade on another.
Runnable simulation
A stand-in, not a real segmentation network: each pixel gets a score drawn from a Gaussian whose mean depends on its true class (foreground 20 percent of pixels), and the model's logit is derived from it. Model A has better separation (more ranking skill) but its logits are inflated by a factor of 3, which makes it overconfident. Model B has slightly worse separation (so lower mIoU) and is calibrated. A variant, A2, has the same separation as B but the same factor-3 inflation as A, to show what recalibration does when A has no ranking advantage. Results are averaged over 10 seeds, each with 100,000 test pixels and a separate 100,000-pixel validation draw used only to fit T. Because the true log-odds are known in this construction, "calibrated" is exact for B and "inflated by 3" is exact for A. The mIoU here is the mean of the foreground and background IoU at probability 0.5.
import numpy as np
from scipy.optimize import minimize_scalar
from scipy.special import expit
PRIOR = np.log(0.2 / 0.8) # 20% of pixels are foreground
def simulate(seed, d, scale, n=100_000):
"""Pixel-level foreground logits. score ~ N(+-d/2, 1); the TRUE log-odds is d*score + PRIOR.
scale > 1 makes the model overconfident (its logits are inflated by that factor); scale = 1 is calibrated."""
g = np.random.default_rng(seed)
y = (g.random(n) < 0.2).astype(int)
s = (2 * y - 1) * d / 2 + g.normal(size=n)
return scale * (d * s + PRIOR), y
def miou(z, y): # mean of foreground IoU and background IoU at threshold p = 0.5
pred = (z > 0).astype(int); out = []
for c in (0, 1):
i = ((pred == c) & (y == c)).sum(); u = ((pred == c) | (y == c)).sum(); out.append(i / u)
return float(np.mean(out))
def ece(z, y, bins=15): # top-label confidence, 15 equal-width bins on [0.5, 1]
p = expit(z); conf = np.maximum(p, 1 - p); correct = ((p > 0.5).astype(int) == y)
edges = np.linspace(0.5, 1.0, bins + 1); idx = np.clip(np.digitize(conf, edges[1:-1]), 0, bins - 1)
return float(sum((idx == b).mean() * abs(correct[idx == b].mean() - conf[idx == b].mean()) for b in range(bins) if (idx == b).any()))
def nll(z, y):
return float(np.mean(np.logaddexp(0, z) - y * z))
def fit_temperature(z, y): # one scalar T > 0 minimising validation NLL; argmax is unchanged
return minimize_scalar(lambda t: nll(z / t, y), bounds=(0.05, 20), method="bounded").x
def prec_recall_at(z, y, p_min=0.9): # pixels the model calls foreground with p >= p_min
sel = expit(z) >= p_min
return float(y[sel].mean()) if sel.any() else float("nan"), float(sel[y == 1].mean())
rows = {"A raw": [], "A + T": [], "B raw": [], "A2 + T": []}
temps = []
for seed in range(10):
zA, y = simulate(seed, d=2.2, scale=3.0); zA_v, y_v = simulate(1000 + seed, d=2.2, scale=3.0)
zB, _ = simulate(seed, d=2.0, scale=1.0)
zA2, _ = simulate(seed, d=2.0, scale=3.0); zA2_v, y2_v = simulate(1000 + seed, d=2.0, scale=3.0) # inflated like A, but no ranking advantage over B
T = fit_temperature(zA_v, y_v); temps.append(T)
T2 = fit_temperature(zA2_v, y2_v)
for name, z in (("A raw", zA), ("A + T", zA / T), ("B raw", zB), ("A2 + T", zA2 / T2)):
p, r = prec_recall_at(z, y)
rows[name].append([miou(z, y), ece(z, y), nll(z, y), p, r])
assert miou(zA, y) == miou(zA / T, y) # temperature scaling cannot change the argmax decision
print("10 seeds x 100k test pixels each; temperature fitted on a separate 100k-pixel validation draw per seed")
print(f"fitted T for A: mean {np.mean(temps):.2f}, min {min(temps):.2f}, max {max(temps):.2f} (inflation factor used: 3.0)")
print(f"{'model':8s} {'mIoU':>6s} {'ECE':>6s} {'NLL':>6s} {'prec@p>=0.9':>12s} {'recall@p>=0.9':>14s}")
for k, v in rows.items():
m = np.mean(v, axis=0)
print(f"{k:8s} {m[0]:6.3f} {m[1]:6.3f} {m[2]:6.3f} {m[3]:12.3f} {m[4]:14.3f}")
print("seed-to-seed standard deviation of precision / recall at p>=0.9:")
for k, v in rows.items():
sd = np.std(v, axis=0)
print(f"{k:8s} precision {sd[3]:.4f} recall {sd[4]:.4f}")
# the cost rule on numbers: a false positive costs 9, a false negative costs 1
cost_fp, cost_fn = 9, 1
print(f"act when probability exceeds cost_fp / (cost_fp + cost_fn) = {cost_fp / (cost_fp + cost_fn):.2f}")
Output:
10 seeds x 100k test pixels each; temperature fitted on a separate 100k-pixel validation draw per seed
fitted T for A: mean 2.98, min 2.96, max 3.02 (inflation factor used: 3.0)
model mIoU ECE NLL prec@p>=0.9 recall@p>=0.9
A raw 0.736 0.067 0.399 0.876 0.556
A + T 0.736 0.002 0.236 0.959 0.302
B raw 0.699 0.003 0.268 0.953 0.215
A2 + T 0.699 0.003 0.268 0.953 0.216
seed-to-seed standard deviation of precision / recall at p>=0.9:
A raw precision 0.0022 recall 0.0020
A + T precision 0.0023 recall 0.0039
B raw precision 0.0028 recall 0.0036
A2 + T precision 0.0029 recall 0.0040
act when probability exceeds cost_fp / (cost_fp + cost_fn) = 0.90
Reading the table. Model A raw has the higher mIoU (0.736 vs 0.699) and a calibration error of 0.067 against 0.003 for B. At the "90 percent or higher" threshold, A raw's flagged pixels are only 0.876 correct, below the 0.9 the stated probabilities promised. Temperature scaling recovers the inflation factor (fitted T about 2.98 against the 3.0 used), makes ECE 0.002, and leaves mIoU at 0.736 (the program asserts the equality). With calibrated probabilities, the flagged pixels are 0.959 correct, slightly above B's 0.953, and A also captures more of the true object (recall 0.302 vs 0.215). That is a statement about this construction, in which A's advantage in ranking skill was built in. The A2 row removes that advantage: after temperature scaling it matches B to within 0.001 (mIoU 0.699 for both, precision 0.953 for both, recall 0.216 against 0.215), so recalibration alone gives no reason to prefer it, and the decision falls back to robustness under shift, ease of recalibrating on deployment data, and cost. The seed-to-seed standard deviation of precision is about 0.002 to 0.003. A's precision edge of about 0.006 is small but consistent across random draws (a sharper model puts more of its flagged pixels well above 0.9, so calibrated A is slightly more precise than B), while the recall gap (0.302 against 0.215) is many times its 0.004 spread.
When the decision flips, and other fixes
- If A cannot be recalibrated well (calibration breaks under the shift you expect, or the errors are confident failures such as unfamiliar objects mislabelled with high confidence), B's honest uncertainty is worth more than A's mIoU. Temperature scaling fixes a uniform inflation; it cannot fix a model that is confidently wrong on a class it never learned.
- Richer recalibration, in order of cost. Temperature scaling is one number. Per-class temperatures or vector scaling (a separate scale and offset per class on the logits) add a handful of numbers for when classes are miscalibrated differently. Isotonic regression fits a never-decreasing step curve from stated confidence to observed hit rate, and needs plenty of validation data; use it when the miscalibration is not a pure scale. Always fit on a validation set that matches deployment and report on a separate test set.
- Training-time or architectural changes for reliability cost a retrain or several forward passes, so they come after recalibration. Label smoothing (training against targets like 0.9 and 0.1 instead of 1 and 0) and a focal-style loss (one that shrinks the penalty on pixels already classified confidently) both change confidence behaviour; verify with ECE, since they do not guarantee calibration. Deep ensembles (several independently trained models whose predictions are averaged) and Monte Carlo dropout (keep dropout switched on at test time and run the image several times) give several predictions per image, with their disagreement as an uncertainty map, at a multiple of the inference cost. A reject head is an extra output that says "unsure", so the system can abstain and hand the region to a person.
- Cost-sensitive objective. If false positives are costly, weight them in the loss or choose the threshold from the cost ratio on calibrated probabilities. A calibrated probability makes that threshold interpretable: act when the probability exceeds cost_fp / (cost_fp + cost_fn) if the cost of a false positive is cost_fp and the cost of a false negative cost_fn. For example, with cost_fp = 9 and cost_fn = 1 the threshold is 9 / (9 + 1) = 0.90, the 0.9 used in the table above (the last line of the program prints it); if a false positive were only three times as costly as a miss, it would be 3 / 4 = 0.75.
- Common mistakes. Fitting the temperature on the test set, reporting ECE without the binning, trusting a single global ECE dominated by easy background pixels, assuming calibration survives a distribution shift, and concluding that a lower mIoU means a worse model for the application.
A detection dataset has a few very common classes and many rare ones. How would you handle the imbalance, and how do you decide which approaches to try first?
Sample Answer
The idea in plain words
Detection has imbalance at three different levels, and each needs its own remedy. Foreground versus background: a detector scores thousands of candidate locations per image and almost all of them are background. Head versus tail classes: a few classes supply most of the labelled objects (these are the head classes; the many rare ones are the tail). Co-occurrence: a rare-class object sits in an image together with common-class objects, so oversampling the image also oversamples the common ones. Classification imbalance only has the middle level, which is why the usual classification recipes need adapting here.
Level 1: foreground versus background
Take the candidate locations (anchors or grid cells) of one image: say 10000 easy background ones that the model scores at probability 0.01 of "object", and 20 object ones scored at 0.30. Plain cross-entropy (the negative log of the probability given to the true label) adds up over all of them, so the easy background dominates. By hand: a background location scored 0.01 for "object" gives the true label (background) probability pt=0.99, so it costs −ln0.99=0.0101; 10000 of them cost 100.5. An object location scored 0.30 has pt=0.30 and costs −ln0.30=1.204; 20 of them cost 24.1. The background share is 100.5/(100.5+24.1)=0.81. With focal loss a background location is multiplied by (1−0.99)2=0.0001 and an object location by (1−0.30)2=0.49, giving totals 0.0101 and 11.80, a background share of 0.0009. Focal loss multiplies each term by (1−pt)γ, where pt is the probability the model gives the true label and γ is a focusing setting (2 in the program). Confident, correct terms shrink towards zero, and the loss concentrates on the hard ones. The program computes the share of the total loss that the easy background carries under each loss.
Level 2 and 3: head versus tail, and co-occurrence
Repeat-factor sampling works at the image level and handles co-occurrence by design. For class c let fc be the fraction of training images that contain it. Choose a threshold t. The class repeat factor is
rc=max(1,fct)and an image is repeated rimg=maxc∈imagerc times per epoch (use the integer part plus a random draw for the fraction). Classes seen in more than a fraction t of images are not boosted, and rarer ones are boosted by the square root of how far they fall below t, a gentler curve than full inverse-frequency weighting. The program builds a synthetic long-tailed dataset of 3000 images with 20 classes (counted at image level: one count per class present, not per box) and shows the effect for several thresholds.
import numpy as np
rng = np.random.default_rng(0)
# synthetic long-tailed detection set: 3000 images, 20 classes, class c appears in an image with prob p_c
n_img, n_cls = 3000, 20
p = 0.6 / (np.arange(1, n_cls + 1) ** 1.3)
has = rng.random((n_img, n_cls)) < p
has[~has.any(1), 0] = True # every image has at least one object
f = has.mean(0) # f_c: fraction of images that contain class c
# repeat-factor sampling: class factor r_c = max(1, sqrt(t / f_c)); an image repeats by the max over its classes
t = 0.05 # threshold; classes seen in more than t of images are not boosted
r_cls = np.maximum(1.0, np.sqrt(t / f))
r_img = np.where(has, r_cls, 1.0).max(1)
before = has.sum(0).astype(float); after = (has * r_img[:, None]).sum(0)
print("images per epoch: %d -> %.0f (x%.2f)" % (n_img, r_img.sum(), r_img.sum() / n_img))
print("%-5s %7s %8s %9s %9s" % ("class", "f_c", "r_c", "share-before", "share-after"))
for c in [0, 1, 4, 9, 14, 19]:
print("%-5d %7.4f %8.2f %12.3f %12.3f" % (c, f[c], r_cls[c], before[c] / before.sum(), after[c] / after.sum()))
for thr in [0.01, 0.05, 0.2, 0.5]:
rc = np.maximum(1.0, np.sqrt(thr / f)); ri = np.where(has, rc, 1.0).max(1); aft = (has * ri[:, None]).sum(0)
own = has.sum(0) * rc # each class boosted by its own r_c only, ignoring co-occurrence
print("t=%.2f: epoch size x%.2f, most common : rarest class = %.0f : 1 (before sampling %.0f : 1; own factor only %.0f : 1)" % (thr, ri.sum() / n_img, aft[0] / aft[19], before[0] / before[19], own[0] / own[19]))
# focal loss: down-weights easy examples by (1 - p_t)^gamma, with p_t the probability given to the true label
gamma = 2.0
n_neg, n_pos = 10000, 20 # background anchors vs object anchors in one image
p_neg_obj = np.full(n_neg, 0.01) # model says "object" with prob 0.01 on easy background
p_pos_obj = np.full(n_pos, 0.30) # and 0.30 on true objects
ce_neg = -np.log(1 - p_neg_obj).sum(); ce_pos = -np.log(p_pos_obj).sum()
fl_neg = ((p_neg_obj ** gamma) * -np.log(1 - p_neg_obj)).sum(); fl_pos = (((1 - p_pos_obj) ** gamma) * -np.log(p_pos_obj)).sum()
print("easy background share of total loss: cross-entropy %.2f, focal (gamma=2) %.4f" % (ce_neg / (ce_neg + ce_pos), fl_neg / (fl_neg + fl_pos)))
The complete output:
images per epoch: 3000 -> 3390 (x1.13)
class f_c r_c share-before share-after
0 0.7347 1.00 0.435 0.404
1 0.2467 1.00 0.146 0.138
4 0.0697 1.00 0.041 0.038
9 0.0260 1.39 0.015 0.019
14 0.0173 1.70 0.010 0.015
19 0.0137 1.91 0.008 0.013
t=0.01: epoch size x1.00, most common : rarest class = 54 : 1 (before sampling 54 : 1; own factor only 54 : 1)
t=0.05: epoch size x1.13, most common : rarest class = 31 : 1 (before sampling 54 : 1; own factor only 28 : 1)
t=0.20: epoch size x1.65, most common : rarest class = 21 : 1 (before sampling 54 : 1; own factor only 14 : 1)
t=0.50: epoch size x2.38, most common : rarest class = 18 : 1 (before sampling 54 : 1; own factor only 9 : 1)
easy background share of total loss: cross-entropy 0.81, focal (gamma=2) 0.0009
Reading the output:
- Easy background carries 0.81 of the cross-entropy total but 0.0009 of the focal-loss total, so focal loss frees the gradient for the hard and rare examples.
- At t=0.05, the epoch grows by 1.13 times and the ratio between the most common and rarest class falls from 54:1 to 31:1. At t=0.20 it falls to 21:1 and the epoch grows by 1.65 times, so the rare classes buy their gain with training time. At t=0.01 nothing changes, because t is below even the rarest class frequency (0.0137): the threshold must be chosen against your own fc values.
- Even at t=0.50 the ratio is 18:1, for two reasons. The square root flattens only part of the way: if each class were boosted by its own rc and nothing else, the ratio at t=0.50 would be 9:1 (the "own factor only" figure at the end of each line above). The rest is co-occurrence: a boosted image still contains common classes, and they are repeated with it. Co-occurrence is a reason to add class-aware crops or copy-paste (pasting rare-class object cutouts into other images) on top. There is no ratio that is "good enough" in itself: the aim is not 1:1 (the tail classes would be memorised), it is tail AP that stops improving on validation while head AP holds, so use the ratio only to see how far the sampler moves the data.
Which approaches to try first
I would go in this order, because each step is cheaper and less risky than the next and each tells you whether to continue:
- Diagnose per class before touching anything. Compute AP (average precision, the area under a class's precision-recall curve; mAP is its mean over classes) per class and plot it against the training count. Check the tail's failure mode: missing labels, confusion with a visually similar head class (a confusion matrix: a table of how often each true class was predicted as each other class, here over matched boxes), or genuinely low recall. A label problem in the tail is not fixed by sampling.
- Focal loss or an equivalent for the foreground/background level, if the detector does not already include it. Many detectors already include something for this level; check yours rather than adding a second one. Sampling and reweighting (steps 3 and 5) act on class imbalance, not on this level, so they do not replace it.
- Repeat-factor or class-aware sampling, with the threshold chosen against your fc values as shown. It changes only the data loader and is easy to reverse.
- Data, not only loss: collect or mine more tail examples, add copy-paste, and fix mislabelled tail objects. This often helps more per hour than loss tweaks, though how much depends on how the tail fails, which step 1 shows.
- Loss re-weighting by class (class-balanced terms give each class a weight that falls with its count; logit-adjusted terms add the log of each class's training frequency to the scores during training so rare classes are not drowned out), and decoupled training (learn the features with natural sampling, then retrain only the classification layer with class-balanced sampling) if sampling alone leaves the tail behind.
- Stop when the tail class AP stops improving on a validation set.
What would flip the order: if the tail has only a handful of examples (say fewer than 10), more data and few-shot methods (learning a class from a handful of labelled examples, usually by reusing features learned elsewhere) or pretrained-feature methods come before any reweighting, because no sampling scheme invents new appearances, and repeated images can simply be memorised.
How you know it worked
Report per-class AP and the average over classes (the macro average, where every class counts equally) next to the frequency-weighted mean (where a class counts in proportion to its objects, so head classes dominate), plus head and tail groups separately. Rare classes have few validation objects, so give a confidence interval before claiming a gain; a bootstrap over images means resampling the validation images with replacement many times, recomputing the metric each time, and reading the spread. Check that head-class AP did not drop more than you accept.
Common mistakes
- Oversampling images by the rare class and not noticing the head classes inside them are oversampled too.
- Choosing t without looking at fc, so nothing changes (the t=0.01 row).
- Judging success by overall mAP when the head classes dominate it.
- Over-boosting until the model memorises the few tail images.
You are building an image classifier with about 200k labeled 224x224 images. Would you choose a CNN or a vision transformer? Discuss transfer learning, robustness, training cost and inference cost.
Sample Answer
Direct answer
With 200k labeled 224x224 images I would start from a pretrained convolutional network (CNN) and fine-tune it (continue training all of its weights on my labels, starting from weights learned on another dataset), and I would run a pretrained vision transformer (ViT) as the challenger on the same split. The deciding facts are how good the available pretrained weights are for my domain, the inference budget, and what the shifted-data test set says (a test set deliberately made unlike the training photos: other cameras, lighting, blur). The data size alone does not pick the family: 200k images is enough to fine-tune either. The usual finding in the ViT literature is that a ViT trained from random weights on a dataset of this size trails a CNN, and that large-scale pretraining is what closes the gap. The program below measures cost, not accuracy, so it does not test that finding, and I would not claim it as a result of mine; I would check it on my own data with the two-arm comparison described under "Recommendation".
Two terms first. A CNN slides small learned filters over the image, so every layer reuses the same weights at every position. A vision transformer cuts the image into square patches, turns each patch into a vector (a token), and lets every token look at every other token with attention (a weighted average whose weights are computed from the tokens themselves).
What differs mechanically
| CNN | ViT | |
|---|---|---|
| Built-in assumption (inductive bias) | Nearby pixels matter most; the same pattern means the same thing anywhere | Almost none: position comes only from added position vectors |
| Cost growth with image side | Proportional to pixel count | Attention part grows with the square of the token count, which itself grows with pixel count |
| Data appetite when trained from scratch | Lower, the bias does part of the work | Higher, it must learn locality from data |
| Output feature maps | Natural multi-scale pyramid (a stack of feature maps at several resolutions, fine to coarse, which detection and segmentation heads use) | Single resolution unless the design adds pooling stages |
Numbers for the two shapes
The program below builds a ResNet-18-shaped CNN (the 18-layer residual-network layout: a 7 by 7 first convolution, then four stages of two 2-layer blocks) and a transformer with the common "base" shape (width 768, 12 layers, 12 heads, patch 16), counts parameters from the built modules, and counts multiply-accumulates (MACs: one multiply plus one add) from the formulas and from hooks on the CNN. A hook is a function PyTorch calls after a layer runs; here it reads the layer's output size to count that layer's MACs. These are two example shapes, not a ranking of products. The last lines confirm that the patch embedding is just one linear layer applied to each flattened patch.
Where the per-layer MAC formula comes from. In one transformer layer with n tokens of width d:
- Each token is turned into three vectors by learned matrices: a query (what this token is looking for), a key (what it offers to others) and a value (what it passes on when attended to). Each of the three is an n×d by d×d matrix product, costing nd2 MACs. After attention, one more d×d product mixes the result (the output projection). Four products of nd2 give 4nd2.
- Attention scores compare every query with every key: n×n scores, each a length-d dot product (summed over heads), so n2d MACs. Applying the weights to the values is another n×n by n×d product, another n2d. Together 2n2d.
- The feed-forward block widens each token from d to dff and back: 2nddff.
The program prints each term for n=197, d=768, dff=3072, then the same at 384. norm_first=True only places the layer normalisation before each sub-block, and GELU is the smooth activation function used in the feed-forward block; neither changes the MAC count.
import torch, torch.nn as nn
torch.set_num_threads(1)
torch.manual_seed(0)
def count_params(m):
return sum(p.numel() for p in m.parameters())
# ---- ViT-shaped config: 224x224 image, 16x16 patches, width 768, 12 layers, 12 heads, MLP 3072
H = 224; P = 16; D = 768; L = 12; HEADS = 12; MLP = 3072
n_patches = (H // P) ** 2
n_tokens = n_patches + 1 # + one classification token
patch_embed = nn.Conv2d(3, D, kernel_size=P, stride=P)
layer = nn.TransformerEncoderLayer(D, HEADS, MLP, dropout=0.0, activation="gelu",
batch_first=True, norm_first=True)
vit_params = count_params(patch_embed) + L * count_params(layer) + n_tokens * D + D \
+ 2 * D + D * 1000 + 1000
# MACs (multiply-accumulates) per layer for n tokens, width d
def vit_macs(n, d, mlp, layers):
patches = n - 1 # one token per patch, plus the classification token
qkv_proj = 4 * n * d * d # Q, K, V and output projection
attn = 2 * n * n * d # QK^T and weights @ V, summed over heads
ffn = 2 * n * d * mlp
return layers * (qkv_proj + attn + ffn) + patches * (3 * P * P) * d # last term: the patch embedding
print("tokens at 224:", n_tokens)
print("ViT-shaped params (M):", round(vit_params / 1e6, 1))
print("ViT-shaped GMACs at 224:", round(vit_macs(n_tokens, D, MLP, L) / 1e9, 1))
n384 = (384 // P) ** 2 + 1
print("tokens at 384:", n384, "GMACs:", round(vit_macs(n384, D, MLP, L) / 1e9, 1))
print("attention score entries per head per layer, 224 vs 384:", n_tokens ** 2, n384 ** 2)
# one layer at 224, term by term (n tokens, width d, feed-forward width d_ff)
proj, attn, ffn = 4 * n_tokens * D * D, 2 * n_tokens ** 2 * D, 2 * n_tokens * D * MLP
print("one layer at 224, millions of MACs: projections", round(proj / 1e6, 1), "| attention", round(attn / 1e6, 1),
"| feed-forward", round(ffn / 1e6, 1), "| total", round((proj + attn + ffn) / 1e6, 1))
n = 4 * n384 * D * D, 2 * n384 ** 2 * D, 2 * n384 * D * MLP
print("one layer at 384, millions of MACs: projections", round(n[0] / 1e6, 1), "| attention", round(n[1] / 1e6, 1),
"| feed-forward", round(n[2] / 1e6, 1), "| attention share", round(n[1] / sum(n), 3))
# ---- ResNet-18-shaped CNN built here, MACs counted with hooks
class Block(nn.Module):
def __init__(s, i, o, stride):
super().__init__()
s.c1 = nn.Conv2d(i, o, 3, stride, 1, bias=False); s.b1 = nn.BatchNorm2d(o)
s.c2 = nn.Conv2d(o, o, 3, 1, 1, bias=False); s.b2 = nn.BatchNorm2d(o)
s.sk = None if (stride == 1 and i == o) else nn.Sequential(
nn.Conv2d(i, o, 1, stride, bias=False), nn.BatchNorm2d(o))
def forward(s, x):
y = s.b2(s.c2(torch.relu(s.b1(s.c1(x)))))
return torch.relu(y + (x if s.sk is None else s.sk(x)))
def make_cnn():
layers = [nn.Conv2d(3, 64, 7, 2, 3, bias=False), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(3, 2, 1)]
ch = 64
for o, st in [(64, 1), (128, 2), (256, 2), (512, 2)]:
layers += [Block(ch, o, st), Block(o, o, 1)]; ch = o
layers += [nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(512, 1000)]
return nn.Sequential(*layers)
cnn = make_cnn().eval()
macs = [0]
def hook(m, inp, out):
if isinstance(m, nn.Conv2d):
macs[0] += out.numel() * m.in_channels * m.kernel_size[0] * m.kernel_size[1] // m.groups
elif isinstance(m, nn.Linear):
macs[0] += m.in_features * m.out_features
for m in cnn.modules():
if isinstance(m, (nn.Conv2d, nn.Linear)): m.register_forward_hook(hook)
with torch.no_grad(): cnn(torch.zeros(1, 3, 224, 224))
print("CNN-shaped params (M):", round(count_params(cnn) / 1e6, 1))
print("CNN-shaped GMACs at 224:", round(macs[0] / 1e9, 2))
cnn224 = macs[0]
macs[0] = 0
with torch.no_grad(): cnn(torch.zeros(1, 3, 384, 384))
print("CNN-shaped GMACs at 384:", round(macs[0] / 1e9, 2))
# ---- patch embedding is a strided convolution = flatten each patch then one linear layer
x = torch.randn(1, 3, H, H)
a = patch_embed(x).flatten(2).transpose(1, 2) # (1, 196, 768)
patches = x.unfold(2, P, P).unfold(3, P, P).permute(0, 2, 3, 1, 4, 5).reshape(1, n_patches, 3 * P * P)
b = patches @ patch_embed.weight.reshape(D, -1).T + patch_embed.bias
print("patch embedding shapes:", tuple(a.shape), tuple(b.shape), "match:", torch.allclose(a, b, atol=1e-5))
# ---- what the GMACs mean in time, for a HYPOTHETICAL device that sustains 1e12 MACs per second (ideal: ignores memory traffic)
SPEED = 1e12
for name, g in (("ViT-shaped", vit_macs(n_tokens, D, MLP, L)), ("CNN-shaped", cnn224)):
print(f"{name}: {g / SPEED * 1000:.1f} ms per image, {1_000_000 * g / SPEED / 3600:.2f} hours for one pass over 1,000,000 images")
Output:
tokens at 224: 197
ViT-shaped params (M): 86.6
ViT-shaped GMACs at 224: 17.6
tokens at 384: 577 GMACs: 55.5
attention score entries per head per layer, 224 vs 384: 38809 332929
one layer at 224, millions of MACs: projections 464.8 | attention 59.6 | feed-forward 929.6 | total 1454.0
one layer at 384, millions of MACs: projections 1361.3 | attention 511.4 | feed-forward 2722.6 | attention share 0.111
CNN-shaped params (M): 11.7
CNN-shaped GMACs at 224: 1.81
CNN-shaped GMACs at 384: 5.33
patch embedding shapes: (1, 196, 768) (1, 196, 768) match: True
ViT-shaped: 17.6 ms per image, 4.88 hours for one pass over 1,000,000 images
CNN-shaped: 1.8 ms per image, 0.50 hours for one pass over 1,000,000 images
Reading the output. At 224 the ViT-shaped model sees 197 tokens (196 patches plus one classification token), has 86.6M parameters and about 17.6 GMACs per image (1 GMAC is a billion MACs). The CNN-shaped model has 11.7M parameters and about 1.81 GMACs. At 384 the ViT cost grows to 55.5 GMACs (577 tokens, and the attention score table per head grows from 38,809 to 332,929 entries), while the CNN grows to 5.33 GMACs, roughly in proportion to pixel count.
The term-by-term lines carry a lesson that is easy to miss. At 224 the quadratic attention term is 59.6 million MACs in a layer of 1,454.0 million, only about 4 percent: the ViT's higher cost at this size comes mainly from the projections and feed-forward blocks, because the model is wide. At 384 attention is 511.4 of 4,595.3 million, 11.1 percent, and it keeps growing faster than the rest as resolution rises. So "ViTs are expensive because of quadratic attention" is true of high-resolution input, not of 224.
What the GMACs mean in time. The last two lines use a hypothetical device that sustains one trillion MACs per second, an ideal that ignores memory traffic. On it the ViT-shaped model takes 17.6 ms per image and a pass over a million images 4.88 hours; the CNN-shaped model takes 1.8 ms and 0.50 hours. A real device will not reach that rate and the absolute numbers will differ, but the ratio, about ten to one here, is what carries over to a first estimate of the training and serving bill, and measuring on the real hardware replaces it.
Decision by the four axes asked
- Transfer learning. The question to ask is which pretrained weights match the domain. Fine-tuning from pretrained weights beats scratch training for both families at this data size. Natural photos: strong pretrained weights exist for both. Medical, satellite, industrial or microscopy images: the pretraining gap shrinks, and the CNN's locality bias helps more when you must train much of the network. Fine-tune with a smaller learning rate (the step size of each weight update) for the backbone (the pretrained feature extractor) than for the new classification head, and compare against a linear probe: freeze the backbone, train only one linear classifier on its output features, and see how much accuracy that alone reaches. If the probe is already close to full fine-tuning, the pretrained features fit your domain; a large gap means much adaptation is needed.
- Robustness. Do not assume either family is more robust. Build a test set with the shifts you expect in production (blur, lighting, crops, a new camera) and report accuracy on it next to clean accuracy for both. Pretraining scale and augmentation (random changes to training images, such as crops, flips and colour jitter, that teach the model to ignore nuisance variation) usually move robustness more than the architecture label.
- Training cost. Fine-tuning cost per epoch scales with the MACs above, so the base-shaped ViT costs roughly ten times the CNN per image here (17.6 vs 1.81). Memory also differs: the n-by-n attention scores are activations stored for the backward pass (the intermediate results backpropagation needs to compute gradients), unless a memory-efficient attention kernel is used, meaning an implementation that computes attention in small blocks so the full score table is never held in memory.
- Inference cost. Latency and throughput are set by MACs, memory traffic and hardware support. The CNN is cheaper at 224 by the numbers above, and the gap widens with resolution. If the product needs high resolution (small defects), this axis alone can decide it.
Recommendation and what flips it
Commit to a pretrained CNN as the production candidate: lowest serving cost, easy multi-scale features, stable fine-tuning recipes. Run the pretrained ViT with the same augmentation and schedule; switch only if it wins on the shifted test set by more than the seed-to-seed spread (how much the score changes just from re-running training with a different random seed; train at least 3 seeds each) and the serving budget absorbs the extra cost. Flip toward the ViT if strong in-domain pretrained ViT weights exist and the latency budget is loose. Flip toward a small CNN if the model runs on a phone or camera, or the input resolution is high.
Common mistakes
- Comparing a ViT fine-tuned from large-scale pretraining against a CNN trained from scratch, then calling it an architecture result.
- Comparing at equal parameter count instead of equal MACs or equal latency on the target hardware.
- Reporting one run: the difference between two good models is often smaller than the seed spread.
- Judging only clean accuracy and finding the shift problem after launch.
Unlock Full Question Bank
Get access to all 15 Computer Vision interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.