Simple Algorithm
Artificial Intelligence · Hidden Layer · 22 min

Computer Vision

Images as tensors, filters, recognition and detection.

A modern vision system is a pipeline: a tensor of pixels goes in, a pretrained backbone turns it into features, and a small head turns the features into a label, a set of boxes or a mask per pixel. Each stage has a precise recipe, from the loss to the augmentations, and each fails in characteristic ways, sometimes under a perturbation too small to see.

What you’ll learn

  • Describe the image-classification pipeline as tensors, layers and losses, and count the parameters of its head.
  • Explain data augmentation as a symmetry prior, and prove that averaging a predictor over a symmetry group cannot increase a convex loss.
  • Compare linear probing and fine-tuning for transfer learning.
  • Compute IoU, run non-maximum suppression, and explain adversarial fragility with the linear bound ε∥w∥1\varepsilon\norm{\mathbf w}_1.

The classification pipeline

An RGB image is a tensor x∈R3×H×W\mathbf x\in\R^{3\times H\times W}, and a mini-batch is N×3×H×WN\times3\times H\times W (PyTorch's channels-first layout). Pixels are scaled to [0,1][0,1] and standardized per channel, (x−μc)/σc(x-\mu_c)/\sigma_c, with the training set's statistics.

For two decades computer vision then extracted hand-designed features, such as SIFT descriptors (Lowe, 2004) or histograms of oriented gradients (Dalal & Triggs, 2005), and fed them to a linear classifier. Since AlexNet (2012), a convolutional network learns the features end to end (CNNs, RNNs & Residual Networks covers its layers):

x → backbone  F∈RC×h×w → global average pool  f∈RC → W, b  z∈RK → softmax⁡  p,L=−log⁡py,∂L∂z=p−ey\mathbf x\ \xrightarrow{\ \text{backbone}\ }\ F\in\R^{C\times h\times w}\ \xrightarrow{\ \text{global average pool}\ }\ \mathbf f\in\R^{C}\ \xrightarrow{\ W,\,\mathbf b\ }\ \mathbf z\in\R^{K}\ \xrightarrow{\ \softmax\ }\ \mathbf p,\qquad\loss=-\log p_y,\quad\frac{\partial\loss}{\partial\mathbf z}=\mathbf p-\mathbf e_y
For ResNet-50 on a 224×224224\times224 input the backbone outputs 2048×7×72048\times7\times7, with about 25 million parameters and 4 billion multiply–adds per image (He et al., 2016). The gradient of softmax cross-entropy with respect to the logits is simply predicted minus true.

Global average pooling (Lin, Chen & Yan, 2014) averages each channel over all positions, fc=1hw∑u,vFc,u,vf_c=\frac1{hw}\sum_{u,v}F_{c,u,v}. Earlier networks flattened the feature map into a huge fully connected layer instead. Pooling makes the head work for any input size and indifferent to where in the map a feature fired, and it removes most of the head's parameters. The computation, meanwhile, lives in the convolutions: a layer with CinC_{\text{in}} input and CoutC_{\text{out}} output channels, k×kk\times k kernels and an H′×W′H'\times W' output performs H′W′CoutCink2H'W'C_{\text{out}}C_{\text{in}}k^2 multiply–adds.

Predict before you look

A backbone outputs a 2048×7×72048\times7\times7 feature map and the task has 1,000 classes. How many times more weights does a "flatten, then fully connected" head have than a "global average pool, then fully connected" head?

Show the answer

49 ×

Flattening gives 2048×49=100,3522048\times49=100{,}352 inputs, so about 10810^8 weights, against 2048×1000≈2×1062048\times1000\approx2\times10^6 after pooling: a factor of 7×7=497\times7=49. VGG-16's flattened fully connected layers hold about 124 of its 138 million parameters.

Data augmentation as a symmetry prior

A cat shifted, mirrored or slightly brightened is still a cat. Data augmentation trains on random label-preserving transformations of each image. Standard choices are random resized crops, horizontal flips and color jitter; stronger policies such as RandAugment (Cubuk et al., 2020) compose many transformations. Label-mixing methods go further: mixup (Zhang et al., 2018) trains on λxi+(1−λ)xj\lambda\mathbf x_i+(1-\lambda)\mathbf x_j with label λyi+(1−λ)yj\lambda\mathbf y_i+(1-\lambda)\mathbf y_j, λ∼Beta(α,α)\lambda\sim\mathrm{Beta}(\alpha,\alpha), and CutMix (Yun et al., 2019) pastes a patch of one image into another and mixes the labels by area. AlexNet already relied on random crops, flips and color perturbations, and averaged its predictions over ten crops at test time.

Why does it help? Suppose a group GG of transformations (flips, shifts) leaves the data distribution unchanged: (gx,y)(g\mathbf x,y) has the same distribution as (x,y)(\mathbf x,y) for every g∈Gg\in G. Then averaging any predictor over GG can only help:

DerivationProof
  1. fˉ(hx)=1∣G∣∑g∈Gf(gh x)=1∣G∣∑g′∈Gf(g′x)=fˉ(x)\bar f(h\mathbf x)=\frac1{|G|}\sum_{g\in G}f(gh\,\mathbf x)=\frac1{|G|}\sum_{g'\in G}f(g'\mathbf x)=\bar f(\mathbf x)

    Invariance: replacing x\mathbf x by hxh\mathbf x only permutes the terms of the average, because g↦ghg\mapsto gh is a bijection of GG:

  2. R(fˉ)=E ℓ(1∣G∣∑gf(gx), y)≤1∣G∣∑gE ℓ(f(gx),y)=1∣G∣∑gR(f)=R(f)R(\bar f)=\E\,\ell\Big(\frac1{|G|}\sum_gf(g\mathbf x),\,y\Big)\le\frac1{|G|}\sum_g\E\,\ell\big(f(g\mathbf x),y\big)=\frac1{|G|}\sum_gR(f)=R(f)

    Risk: Jensen's inequality for the convex loss, then distributional invariance, which makes every term equal to R(f)R(f):

  3. The middle expression is exactly the risk that augmented training minimizes. Under exact invariance it equals the plain risk, so augmentation does not change the population objective; its benefit is statistical, an averaging over orbits that reduces the variance of what is learned from a finite sample, and a bias toward invariant predictors, which the theorem says lose nothing. Test-time augmentation, averaging predictions over flips and crops, is a Monte Carlo estimate of fˉ\bar f.

Check your understanding

You are training a handwritten-digit classifier. Which augmentation violates the theorem's assumption, and can hurt?

  1. Shifting the digit by a pixel or two
  2. Small changes of brightness and contrast
  3. Rotating the image by 180°
  4. Adding faint Gaussian noise
Show the answer

C. Rotating the image by 180°

A 6 rotated by 180° looks like a 9: the transformation changes the label, so (gx,y)(g\mathbf x,y) no longer has the distribution of (x,y)(\mathbf x,y), and augmenting with it teaches the network to confuse the two classes. Likewise, horizontal flips are harmless for cats and harmful for text.

Transfer learning: features that travel

Few applications have a million labeled images. Transfer learning reuses a backbone pretrained on a large dataset such as ImageNet, or pretrained without labels (Vision Transformers). Yosinski et al. (2014) showed why it works: first-layer features are generic, oriented edges and color blobs much like the Gabor filters of classical vision, while the top layers specialize to the pretraining classes, and transferability falls as the tasks grow apart.

StrategyWhat trainsWhen it fits
Linear probea new linear head on frozen features: convex logistic regressionlittle data; a target close to the pretraining domain; a quick test of feature quality
Fine-tuningevery weight, usually with a smaller learning rate than the new headmore data, or a target domain that differs (medical, satellite, microscopy)
Partial fine-tuning, adaptersthe top blocks, or small inserted modulesin between, or many tasks sharing one backbone
Probing first and then fine-tuning (LP-FT) often beats fine-tuning from a random head on out-of-distribution tests, because a random head's large early gradients distort the pretrained features (Kumar et al., 2022).
python
import torch
import torchvision

num_classes = 10
model = torchvision.models.resnet50(weights="IMAGENET1K_V2")    # pretrained backbone
for p in model.parameters():
    p.requires_grad = False                                      # freeze it: a linear probe
model.fc = torch.nn.Linear(model.fc.in_features, num_classes)    # new 2048 -> K head, trainable
opt = torch.optim.AdamW(model.fc.parameters(), lr=1e-3)

model.eval()                    # also keep the batch-norm statistics frozen
for x, y in loader:             # x: (N, 3, 224, 224), standardized with ImageNet statistics
    loss = torch.nn.functional.cross_entropy(model(x), y)
    opt.zero_grad()
    loss.backward()
    opt.step()

A linear probe in PyTorch; loader yields batches of the target task. To fine-tune instead, leave every parameter trainable and give the backbone a smaller learning rate than the head.

Better pretrained models tend to transfer better: across many architectures, ImageNet accuracy correlated strongly with accuracy after transfer (Kornblith, Shlens & Le, 2019). Pretraining is not always necessary, though: with enough target data and longer training, detectors trained from scratch on COCO matched ImageNet-pretrained ones (He, Girshick & Dollár, 2019). Pretraining mainly buys faster convergence, and accuracy when labels are scarce.

From labels to boxes: IoU and non-maximum suppression

Object detection outputs a set of triples (box, class, score); semantic segmentation labels every pixel; instance segmentation outputs one mask per object. A box is written (x1,y1,x2,y2)(x_1,y_1,x_2,y_2), and two boxes are compared by their intersection over union:

IoU(A,B)=∣A∩B∣∣A∪B∣,∣A∩B∣=[min⁡(x2A,x2B)−max⁡(x1A,x1B)]+⋅[min⁡(y2A,y2B)−max⁡(y1A,y1B)]+\mathrm{IoU}(A,B)=\frac{|A\cap B|}{|A\cup B|},\qquad|A\cap B|=\big[\min(x_2^A,x_2^B)-\max(x_1^A,x_1^B)\big]_+\cdot\big[\min(y_2^A,y_2^B)-\max(y_1^A,y_1^B)\big]_+
[u]+=max⁡(u,0)[u]_+=\max(u,0) and ∣A∪B∣=∣A∣+∣B∣−∣A∩B∣|A\cup B|=|A|+|B|-|A\cap B|. A detection usually counts as correct when its IoU with a not-yet-matched ground-truth box of the same class is at least 0.5.
Predict before you look

Two 10×1010\times10 boxes, one shifted 2 pixels right and 2 pixels down from the other. What is their IoU, in percent?

Show the answer

47 %

The intersection is 8×8=648\times8=64 and the union 100+100−64=136100+100-64=136, so IoU ≈0.47\approx0.47. A shift of a fifth of the box size in both directions already falls below the usual 0.5 threshold: IoU is a strict criterion, especially for small objects.

The oldest detector is a classifier slid over every position and scale. If the classifier is linear, its score map is a convolution of the image with a template; OverFeat (Sermanet et al., 2014) showed that a whole CNN classifier can be slid efficiently by computing its fully connected layers as convolutions. Every window that overlaps an object scores high, so each object produces a cluster of detections:

Non-maximum suppression turns each cluster into one detection: keep the highest-scoring box, discard every remaining box of the same class whose IoU with it exceeds a threshold τ\tau (often 0.5), and repeat.

text
NMS(boxes B, scores s, threshold τ):           # run separately for each class
    keep ← empty list
    sort B by score, highest first
    while B is not empty:
        b ← remove the first box of B;  append b to keep
        remove from B every box c with IoU(b, c) > τ
    return keep                                # O(n²) IoU computations in the worst case

Modern detectors differ in where candidate boxes come from. Two-stage detectors (the R-CNN family) propose regions, then classify and refine them; one-stage detectors (YOLO, SSD, RetinaNet) predict boxes densely in a single pass; set-based detectors (DETR) predict a fixed-size set and need no NMS at all. All are scored by mean average precision: for each class, the area under the precision–recall curve of its ranked detections, averaged over classes (precision and recall as in Evaluating Models).

Fragile features: adversarial examples and shortcuts

Classifiers that rival people on clean test images can be fooled by perturbations far too small to see: adversarial examples (Szegedy et al., 2014). Goodfellow, Shlens & Szegedy (2015) argued that the cause is not exotic nonlinearity but too much linearity in high dimensions:

DerivationThe linear explanation
  1. max⁡∥η∥∞≤εw⊤η=ε∥w∥1=ε∑i=1d∣wi∣\max_{\norm{\boldsymbol\eta}_\infty\le\varepsilon}\mathbf w^\top\boldsymbol\eta=\varepsilon\norm{\mathbf w}_1=\varepsilon\sum_{i=1}^d|w_i|

    For a linear score s(x)=w⊤x+bs(\mathbf x)=\mathbf w^\top\mathbf x+b and a perturbation with ∥η∥∞≤ε\norm{\boldsymbol\eta}_\infty\le\varepsilon (no pixel moves by more than ε\varepsilon), the largest change comes from η=εsign⁡(w)\boldsymbol\eta=\varepsilon\sign(\mathbf w), the FGSM direction:

  2. Var⁡(w⊤η)=ε∥w∥2,1≤∥w∥1∥w∥2≤d\sqrt{\Var\big(\mathbf w^\top\boldsymbol\eta\big)}=\varepsilon\norm{\mathbf w}_2,\qquad1\le\frac{\norm{\mathbf w}_1}{\norm{\mathbf w}_2}\le\sqrt d

    That grows linearly with the dimension dd while each pixel changes by only ε\varepsilon. Random signs, η=εξ\boldsymbol\eta=\varepsilon\boldsymbol\xi with independent ξi=±1\xi_i=\pm1, change the score by zero on average, with standard deviation

  3. So an aligned perturbation can be up to d\sqrt d times more effective than random noise of the same size. For a deep network, FGSM linearizes the loss around the input: η=εsign⁡(∇xL)\boldsymbol\eta=\varepsilon\sign\big(\nabla_{\mathbf x}\loss\big).

Robustness to worst-case perturbations is trained by adversarial training, min⁡θEmax⁡∥δ∥≤εL(x+δ,y;θ)\min_\theta\E\max_{\norm{\boldsymbol\delta}\le\varepsilon}\loss(\mathbf x+\boldsymbol\delta,y;\theta) (Madry et al., 2018), at a cost in clean accuracy and compute; Adversarial Examples & Robustness covers attacks and defenses. A broader fragility is shortcut learning (Geirhos et al., 2020): networks exploit whatever cue separates the training classes, such as texture rather than shape (ImageNet-trained CNNs labeled a cat-shaped image with elephant-skin texture an elephant; Geirhos et al., 2019), backgrounds, or hospital-specific markings on X-rays. Shortcuts fail under distribution shift (Distribution Shift & Robustness).

Key takeaways

  • Classification pipeline: standardized tensor → backbone → global average pooling → linear head → softmax cross-entropy, with gradient p−ey\mathbf p-\mathbf e_y; pooling divides the head's weights by the feature map's area.
  • Augmentation encodes symmetries: if GG preserves the data distribution, the orbit-averaged predictor is invariant and has no larger convex risk, and test-time augmentation estimates it.
  • Transfer learning reuses pretrained features: linear probes for little data, fine-tuning for larger or more distant tasks.
  • Detectors output boxes compared by IoU; overlapping windows fire together, so NMS keeps local maxima, at the cost of suppressing genuinely overlapping objects.
  • An ℓ∞\ell_\infty perturbation of size ε\varepsilon moves a linear score by up to ε∥w∥1\varepsilon\norm{\mathbf w}_1, up to d\sqrt d times more than random noise of the same size: in high dimensions, tiny aligned changes add up.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

For softmax cross-entropy, what is ∂L/∂zk\partial\loss/\partial z_k for a wrong class k≠yk\neq y?

  1. −pk-p_k
  2. pkp_k
  3. 1−pk1-p_k
  4. log⁡pk\log p_k
Show the answer

B. pkp_k

∂L/∂z=p−ey\partial\loss/\partial\mathbf z=\mathbf p-\mathbf e_y: for k≠yk\ne y the component is pkp_k, so gradient descent lowers each wrong logit in proportion to the probability it receives, while the true class's component is py−1<0p_y-1<0.

Question 2

Under exact distributional invariance, augmented training minimizes a population risk equal to the plain one. Why does augmentation still help?

  1. It increases the network's capacity
  2. It corrects mislabeled training examples
  3. It does not help; reported gains are noise
  4. It averages the training signal over symmetric copies, reducing the variance of what is learned from finite data, and favors invariant predictors, which lose nothing in risk
Show the answer

D. It averages the training signal over symmetric copies, reducing the variance of what is learned from finite data, and favors invariant predictors, which lose nothing in risk

With finitely many examples, the augmented empirical risk averages over each example's orbit, a lower-variance estimate of the same objective, and the symmetrized predictor is never worse for a convex loss. The gains are real and well documented; they depend on the transformations preserving labels.

Question 3

You have 500 labeled photos for a new set of categories similar to ImageNet's. What is the safest first approach?

  1. A linear probe on a pretrained backbone, possibly followed by gentle fine-tuning
  2. Train a ResNet-50 from scratch
  3. Fine-tune all layers from a random head with a large learning rate
  4. Retrain only the first convolutional layer
Show the answer

A. A linear probe on a pretrained backbone, possibly followed by gentle fine-tuning

With little data and a nearby domain, frozen pretrained features plus a convex linear head are hard to beat and cannot overfit much; LP-FT then adapts the backbone gently.

Question 4

Two pedestrians overlap heavily, and their correct boxes have IoU 0.6. The detector finds both, and NMS runs with threshold τ=0.5\tau=0.5. What happens?

  1. Both boxes are kept
  2. Both boxes are suppressed
  3. The lower-scoring pedestrian's box is suppressed: a missed detection
  4. The two boxes are merged into their average
Show the answer

C. The lower-scoring pedestrian's box is suppressed: a missed detection

NMS cannot tell a duplicate from a second object that overlaps the first: 0.6>0.50.6>0.5, so the weaker true detection is removed. Raising τ\tau admits more duplicates; Soft-NMS decays scores instead of deleting boxes, and set-based detectors such as DETR avoid NMS altogether.

Question 5

A linear classifier on d=10,000d=10{,}000 pixels has weights of roughly equal magnitude, ∣wi∣≈0.01|w_i|\approx0.01. By how much can an FGSM perturbation with ε=0.01\varepsilon=0.01 change its score?

  1. About 0.0001
  2. About 0.01
  3. About 1
  4. About 100
Show the answer

C. About 1

ε∥w∥1=0.01×10,000×0.01=1\varepsilon\norm{\mathbf w}_1=0.01\times10{,}000\times0.01=1, enough to flip many decisions, while random signs of the same size move the score by only about ε∥w∥2=0.01\varepsilon\norm{\mathbf w}_2=0.01.

Go deeper

Further reading

  • R. Szeliski, Computer Vision: Algorithms and Applications (Springer, 2nd ed., 2022).
  • A. Krizhevsky, I. Sutskever & G. E. Hinton, "ImageNet classification with deep convolutional neural networks," NeurIPS (2012).
  • J. Yosinski, J. Clune, Y. Bengio & H. Lipson, "How transferable are features in deep neural networks?," NeurIPS (2014).
  • I. J. Goodfellow, J. Shlens & C. Szegedy, "Explaining and harnessing adversarial examples," ICLR (2015).