IMAGE CLASSIFICATION · LECTURE 4

Image Classification

CNN architectures and Vision Transformers

CIFAR-10 images from ten object classes

What Is a Trainable Parameter?

Count the numbers the model can learn independently.

Input dataLearnable weightsx₁1x₂2x₃0x₄3w₁ = 2w₂ = -1w₃ = 1w₄ = 1Σb = 1Computed output4z
z=∑i=14wixi+bz=\sum_{i=1}^{4}w_i x_i+b2(1) − 1(2) + 1(0) + 1(3) + 1 = 4
Parameter bankOne box = one
parameter
w₁2
w₂−1
w₃1
w₄1
b1
Parameters counted54 weights + 1 bias

Reveal the weights, then the bias. Count each box once.

Inputs and computed outputs do not add trainable parameters.

Predict, then click a question to reveal its answer

MLP: One Dense Layer

One dense layer: 16 input values and 4 output values.

0 of 4 rows flattened · 0 of 16 inputs
Input: 4 × 4 pixelsFour output valuesDistinct learned coefficientsx1x2x3x4x5x6x7x8x9x10x11x12x13x14x15x16flattenSame 16 values0 parametersy1Independent weight w_1,1Independent weight w_1,2Independent weight w_1,3Independent weight w_1,4Independent weight w_1,5Independent weight w_1,6Independent weight w_1,7Independent weight w_1,8Independent weight w_1,9Independent weight w_1,10Independent weight w_1,11Independent weight w_1,12Independent weight w_1,13Independent weight w_1,14Independent weight w_1,15Independent weight w_1,16y1y2Independent weight w_2,1Independent weight w_2,2Independent weight w_2,3Independent weight w_2,4Independent weight w_2,5Independent weight w_2,6Independent weight w_2,7Independent weight w_2,8Independent weight w_2,9Independent weight w_2,10Independent weight w_2,11Independent weight w_2,12Independent weight w_2,13Independent weight w_2,14Independent weight w_2,15Independent weight w_2,16y2y3Independent weight w_3,1Independent weight w_3,2Independent weight w_3,3Independent weight w_3,4Independent weight w_3,5Independent weight w_3,6Independent weight w_3,7Independent weight w_3,8Independent weight w_3,9Independent weight w_3,10Independent weight w_3,11Independent weight w_3,12Independent weight w_3,13Independent weight w_3,14Independent weight w_3,15Independent weight w_3,16y3y4Independent weight w_4,1Independent weight w_4,2Independent weight w_4,3Independent weight w_4,4Independent weight w_4,5Independent weight w_4,6Independent weight w_4,7Independent weight w_4,8Independent weight w_4,9Independent weight w_4,10Independent weight w_4,11Independent weight w_4,12Independent weight w_4,13Independent weight w_4,14Independent weight w_4,15Independent weight w_4,16y4Row 1, column 1: x1 becomes input 1. The value is unchanged.x1Row 1, column 2: x2 becomes input 2. The value is unchanged.x2Row 1, column 3: x3 becomes input 3. The value is unchanged.x3Row 1, column 4: x4 becomes input 4. The value is unchanged.x4Row 2, column 1: x5 becomes input 5. The value is unchanged.x5Row 2, column 2: x6 becomes input 6. The value is unchanged.x6Row 2, column 3: x7 becomes input 7. The value is unchanged.x7Row 2, column 4: x8 becomes input 8. The value is unchanged.x8Row 3, column 1: x9 becomes input 9. The value is unchanged.x9Row 3, column 2: x10 becomes input 10. The value is unchanged.x10Row 3, column 3: x11 becomes input 11. The value is unchanged.x11Row 3, column 4: x12 becomes input 12. The value is unchanged.x12Row 4, column 1: x13 becomes input 13. The value is unchanged.x13Row 4, column 2: x14 becomes input 14. The value is unchanged.x14Row 4, column 3: x15 becomes input 15. The value is unchanged.x15Row 4, column 4: x16 becomes input 16. The value is unchanged.x1616 weights for each outputOne cell = one stored scalar weightWeights0Biases0Total0+ one bias per output: b₁, b₂, b₃, b₄

16 weights will connect to each output.

The input values are data. The connection weights are trainable.

Dense layer: input count × output count + one bias per output.

Local Connections with Separate Weights

Keep 16 inputs and 4 outputs. Give each output a separate 2 × 2 region.

0 of 4 outputs connected
Input: 4 × 4 pixelsFour output valuesDistinct learned coefficientsx1x2x3x4x5x6x7x8x9x10x11x12x13x14x15x16y1Independent weight w_1,1Independent weight w_1,2Independent weight w_1,3Independent weight w_1,4y1y2Independent weight w_2,1Independent weight w_2,2Independent weight w_2,3Independent weight w_2,4y2y3Independent weight w_3,1Independent weight w_3,2Independent weight w_3,3Independent weight w_3,4y3y4Independent weight w_4,1Independent weight w_4,2Independent weight w_4,3Independent weight w_4,4y4Each output sees one 2 × 2 regionEach region has its own weight set4 weights for each outputOne cell = one stored scalar weightWeights0Biases0Total0+ one bias per output: b₁, b₂, b₃, b₄

4 weights will connect to each output.

The input values are data. The connection weights are trainable.

Locality reduces the number of connections. These four weight sets are still independent.

CNN: One Filter, Shared Weights

Channels, Filters and Parameter Counts

RGB input · two 2 × 2 filters · stride 2 · no padding · bias enabled

Each filter spans all input channels and produces one output map.

Input: 4 × 4 × 3R, G, B at the same coordinatesFilter 1: 2 × 2 × 312 weights + 1 biasFilter 2: 2 × 2 × 312 weights + 1 biasMap 1Map 2One filter combines all input channels into one map.Output: 2 × 2 × 2
Drag to rotate
Sum across input channels, then add one bias.One filter gives one map; two filters give two maps.
2 × (2 × 2 × 3 + 1) = 26trainable parameters2 × 2 × 2 = 8 output values

H × W = image positions. C = channels at each position.

Inductive Biases: Locality and Sharing

Why do we need assumptions?

The dark dots are three observed examples. Predict the output at x = 3.

Unseen input0369y0123x(0, 0)(1, 1)(2, 2)
Start with the observed examples.

AlexNet: Architecture and Historical Context

ImageNet · 2012 · ReLU in hidden layers · no BatchNorm

Conv 111 × 1196 channelsConv 25 × 5256 channelsMax pool3 × 3 · stride 2Max pool3 × 3 · stride 2Conv 33 × 3384 channelsConv 43 × 3384 channelsConv 53 × 3256 channelsMax pool3 × 3 · stride 2FC: 4,096FC: 4,096FC: 1,000 scoresDropout during training

5 convolutional + 3 fully connected weighted layers. LRN follows conv 1 and 2.

Original two-GPU designGPU 1: 48GPU 2: 48← conv 1’s 96 channelsConv 2, 4 and 5 connect within GPU groups; conv 3 mixes across both.
Explore AlexNet in 3D Pretrained torchvision variant · actual filters, activations and predictions

AlexNet: What Changed and Why It Worked

From AlexNet to VGG: Does Depth Help?

AlexNet showed that learned CNN features can succeed at ImageNet scale.

AlexNet8

weighted layers

5 conv + 3 FC
VGG’s question

Does greater network depth
improve image recognition?

Depth = the number of layers with trainable weights.
Test a family of deeper networksSame design rules; add convolutional layers.
11weighted layers

8 conv + 3 FC

Configuration A
13weighted layers

10 conv + 3 FC

Configuration B
16weighted layers

13 conv + 3 FC

Configuration D · VGG-16
19weighted layers

16 conv + 3 FC

Configuration E · VGG-19

Use small 3 × 3 filters, the same channel stages and the same three-layer classifier.

Question · 1 / 6

VGG’s Design: Larger Context, More Processing

Blue area: input pixels that can affect one output position

One 3 × 3 layer
3×33\times3
Two 3 × 3 layers
5×55\times5
Three 3 × 3 layers
7×77\times7
27C227C^2
stacked 3 × 3
49C249C^2
one 7 × 7weights

CC: channels in every layer · stride 1 · no pooling between layers · biases excluded

Same receptive-field extent; fewer weights and more nonlinearities under these assumptions.

Input region

VGG’s Answer: Deeper Helped, up to a Point

Return to the question: does greater depth reduce recognition errors?

11 layers VGG-A 13 layers VGG-B 16 layers VGG-D 19 layers VGG-E 26 27 28 29 30 Top-1 validation error (%) 29.6% 28.7% 27.0% 27.3%

ImageNet validation · train/test scale 256 · dense evaluation + horizontal flip

11 → 16 layers: 2.6 percentage points less error.19 layers does not improve this fixed-scale result.

Historical outcomeVGG’s 2014 entry: 2nd in classification · 1st in localisation.

VGG’s Cost: Reusing Weights Still Takes Work

VGG-16 · one 3 × 3 convolution · 64 → 64 channels

Stored once

3 × 3 × 64 × 64
36,864weights
×

Reused at

50,176positions · 224 × 224
≈

Work per image

1.85billion
MACs*1 MAC = one multiply + add
Try a smaller grid:

1 / 5

Inception: Why Use Parallel Paths?

VGG and Inception explored different questions in 2014.

2014
AlexNet2012VGGDoes greater depth help?3 × 33 × 33 × 3InceptionDifferent filter sizes, within budget?1 × 13 × 35 × 5

1 × 1 Convolution: Mix Channels at One Position

Toy: 3 input channels, 1 × 1 filters

Toy: 3 → 2 channels · stride 1, padding 0 · before activation

A 1 × 1 filter mixes channels at the same pixel. H and W stay unchanged.

At one (h, w) coordinatex = [2, 3, 1]Input: 4 × 4 × 3Filter A[1, 2, −1] · x + 1 = 8Filter B[−1, 1, 2] · x − 1 = 26 weights + 2 biases = 8y = [8, 2]Output: 4 × 4 × 2The same two filters are reused at every pixel.
Drag to rotate
At one pixel: [2, 3, 1] → [8, 2]Filter A: 2 + 6 − 1 + 1 = 8. Filter B: −2 + 3 + 2 − 1 = 2.
2 × (1 × 1 × 3 + 1) = 8trainable parameters4 × 4 × 3 → 4 × 4 × 2

Inception: Make the Large Filters Affordable

Can the 5 × 5 branch start with fewer channels?

Direct192 channels5 × 532 channelsReduce first192 channels1 × 116 channels5 × 532 channels
Direct
120.4M
Reduce first
12.4M
2.4M reduction+10.0M for 5 × 59.7× fewer MACs
Try another reduction:192 → 16 stays fixed

28 × 28 at every step · convolution MACs

GoogLeNet: Build a Network from Inception Modules

GoogLeNet stacks nine Inception modules.

224 × 224 RGB → initial convolutions + pooling → 28 × 28 × 192We just built 3a2 Inception modules3a3b28 × 28 × 480Max poolstride 25 Inception modules4a4b4c4d4e14 × 14 × 832Max poolstride 22 Inception modules5a5b7 × 7 × 1,0243a output: 28 × 28 × 256

Within a module: keep spatial size. Between groups: downsample.

GoogLeNet: Finish with a Compact Classifier

Summarize each feature map with one average.

One of 1,024 maps · 7 × 7
0000000111111122222223333333444444455555556666666
Illustrative activation values
→
Sum ÷ 49 positions147 ÷ 49 = 3One value for this channel

Repeat for every channel: 7 × 7 × 1,024 → 1 × 1 × 1,024

Global average pooling · no trainable parameters

Deeper Networks: What Makes Learning Difficult?

Earlier weights shape what later layers receive.

Same batch2 imagesEarlier layersCurrent weights1357Next layerOne channel: four valuesMean 4 · variance 5

What happens here when the earlier weights are updated?

Toy example · one channel · 2 images, 2 values each

BatchNorm: Normalize, Scale and Shift

Measure → normalize → apply learned scale and offset.

Convolution → BatchNorm → ReLU

One channel · two images
Image 1
13
Image 2
57
Mean 4Variance 5
↓a^=(a−μ)/σ2+ϵ\hat a=(a-\mu)/\sqrt{\sigma^2+\epsilon}
−1.342−0.4470.4471.342

1 / 4

BatchNorm: What Changes at Evaluation?

Same operation. Different source of statistics.

Training

Current batch

μB, σB2\mu_{\mathcal B},\ \sigma^2_{\mathcal B}

Update running estimates →

Evaluation

Stored training estimates

μrunning, σrunning2\mu_{\mathrm{running}},\ \sigma^2_{\mathrm{running}}

Keep estimates fixed

γ,β\gamma,\beta: learned per channel · used in both modes

CC channels → 2C2C trainable parameters

BatchNorm: Did It Help Training?

How many training steps to reach the same 72.2% accuracy?

ImageNet · single-crop top-1 validation accuracy · 2015 Inception variant

0 10 20 30 Training steps (millions) · lower is better Without BN With BN 31.0 M 13.3 M

Without BatchNorm: 31.0 million steps.

Even with BatchNorm: Can More Layers Train Worse?

ImageNet · plain CNNs · both networks already use BatchNorm

Reported training-error ordering18layers34layers34 layers: higher training errorPublished finding; schematic,not numerical measurements

Can adding layers make the training fit worse?

Optimization difficulty

The extra capacity has not produced a better training fit.

Residual Connections

Extra layers should be able to keep a useful representation.

Desired mappingInput x[2, 1]Extra layerscould they just copy x?Output x[2, 1]A shortcut supplies the copy. The branch can learn F(x) = 0.

Make “keep what already works” easy to represent.

Identity is an available option; training still has to find useful weights.

Residual Networks: Training Results

ImageNet · same 18-layer and 34-layer comparison

Reported training-error ordering18layers34layers34 layers: higher training errorPublished finding; schematic,not numerical measurements
Plain networks · training error
Reported training-error ordering18layers34layers34 layers: lower training errorPublished finding; schematic,not numerical measurements
Residual networks · training error
Top-1 validation error (%)0102030Plain27.94%18 layers28.54%34 layersResidual27.88%18 layers25.03%34 layers

Table 2 · ten-crop validation · parameter-free shortcuts (option A)

Here, residual connections improved training and validation error.

Local or Global: Who Can Exchange Information?

Convolution applies the same learned kernel to a local neighborhood.

Local convolutionLocal neighborhoodSame kernel at every locationClick a region · lines show allowed connections
Local convolution · 1 / 4

An Image Becomes a Row of Patch Vectors

Start with one image.

e1e2e3e4e5e6e7e8e9e10e11e12e13e14e15e164 × 4 teaching grid · the numbered patches move intact
The image · 1 / 15

Give Every Token Its Image Position

Attention needs position information to distinguish image locations.

e1p1e2p2e3p3e4p4e5p5e6p6e7p7e8p8e9p9e10p10e11p11e12p12e13p13e14p14e15p15e16p16Content alone does not say “left”, “right” or “above”.CLSVector colors are schematic · original image positions stay with their patches
Content vectors · 1 / 5

One Token Becomes a Query, Key and Value

A token is a feature vector. Select a token to inspect its features.

Token 1[1, 0]Token 2[0, 1]Token 3[1, 1]WQQuery q₁[1, 0]WKKey k₁[1, 0]WVValue v₁[1, 2]Three toy tokens · two features per token
Start with token features · 1 / 5

Attention: Compare, Weight, Mix

One query compares with every key, including its own token’s key.

Query q₁[1, 0]Same q₁[1, 0]Key k₁[1, 0]Value v₁[1, 2]Same q₁[1, 0]Key k₂[0, 1]Value v₂[0, 1]Same q₁[1, 0]Key k₃[1, 1]Value v₃[1, 3]Attention output y₁[0.802, 2.203]
One query, every key · 1 / 5

Calculate One Token’s Attention

Choose a query and work through its calculation.

Query q₁[1, 0]Key k₁[1, 0]Value v₁[1, 2]Key k₂[0, 1]Value v₂[0, 1]Key k₃[1, 1]Value v₃[1, 3]Attention output y₁[0.802, 2.203]Same toy: Q = K = X. The value vectors came from XWV.
Choose a query · 1 / 6

Every Token, Several Attention Heads

One query produces one output vector.

QueryWeights over keysAttention outputq₁[1, 0]Query 10.401 0.198 0.401y₁[0.802, 2.203]q₂[0, 1]Query 20.198 0.401 0.401y₂[0.599, 2]q₃[1, 1]Query 30.248 0.248 0.503y₃[0.752, 2.255]Same input token sequenceHead 1Head 1Head 2Head 2Head 3Head 3Wᴼ
One query gives one mixture · 1 / 5

The Encoder Block: Mix, Add, Refine

Each token enters with D features.

T × DSame T × DLayerNormper tokenAttentionacross tokensLayerNormper tokenShared MLPD → 4D → D++
Input tokens · 1 / 5

From the Image to a Class Prediction

Follow the same image all the way to the classifier.

CLSTransformer encoder12 blocks · ViT-B/16197 tokens × 768 features16-patch teaching grid · the same patch identities travel forward
Image · 1 / 7

Inductive Biases: MLP, CNN and ViT

Inductive bias: built-in assumptions that guide learning.

Image MLPCNNVision Transformer
ConnectionsDense pixel connectionsLocal, shared filtersGlobal token attention
PositionFixed input slots2D feature gridAdded position vectors

ViT still builds in patches, shared operations and position vectors.

Smaller Patches, More Attention Scores

Keep the image size fixed. Change the patch width.

Input stays 224 × 224
CIFAR image resized to illustrate patch divisions
14 × 14 patch grid

Patch tokens196

With class token197

38,809scores per head: T × T

One score for each query and key pair.

Half the patch width → about 4× tokens → about 16× attention scores.

Compare patch widths · 1 / 3

Pretraining Gives Us a Starting Point

Learn on an earlier dataset. Then adapt to the target task.

Original ViT Appendix Table 5: ImageNet top-1 accuracy at 384 resolution. ViT-B/16: 77.91, 83.97, 84.15 percent; ViT-L/16: 76.53, 85.15, 87.12 percent across ImageNet-1k, ImageNet-21k and JFT-300M pretraining.

ImageNet top-1 accuracy after transfer · 384-pixel evaluation · original ViT study

In this study, larger pretraining regimes especially help ViT-L.

Read the published comparison · 1 / 3

Adapt a Pretrained Classifier

Keep the feature extractor. Add a classifier for your classes.

Example backbone

Illustrative CIFAR-10 adaptation · 10 classes

Reuse a representation · 1 / 4

Set Up a Fair Experiment

Decide the split and selection rule before comparing models.

Training

Fit weights

45,000 images

Validation

Choose the recipe

5,000 images

Test

Assess the final model

Keep separate until the end

Course CIFAR-10 split: training and validation come from the original training set.

Which choice uses test information too early?

Fit the parameters · 1 / 4

Recognize Overfitting in the Learning Curves

Measured CIFAR-10 MLP · 45,000 training / 5,000 validation images

Cross-entropy loss0123110203040EpochTrainingValidationTraining loss ↓Validation loss ↑

Training loss falls while validation loss rises.

Read the axes · 1 / 4

A Weight Penalty Can Improve Generalization

Penalty strength λ: none, moderate, strong.

Small teaching experiment · two coordinates → 20 hidden units → two classes

80 training examples

λ=0\lambda=0
-1012-101
x1x_1
x2x_2
Class 0Class 1Background: predicted class

No penalty

Same architecture · same training setup

Training loss0.233

Validation loss0.681

Mean binary cross-entropy
Weight penalty excluded

Training loss is low. Validation loss is higher.

p≥0.5p\ge0.5 → class 1
p<0.5p<0.5 → class 0

No penalty · 1 / 4

Augmentation Must Preserve the Target

Change the image while keeping useful evidence for its class.

CIFAR-10 validation image of a horse
Original · horse
→
CIFAR-10 validation image of a horse
Original · 32×3232\times32 pixels

Can we still justify the label “horse”?

Measured recipe: random 32 × 32 crop after 4-pixel padding + horizontal flip.

Validate the transformation on the task.

Did Augmentation Help on Shifted Images?

During training

Same MLP, split, start and 40 epochs

No augmentationRandom crop + flip

At validation

Freeze each selected checkpoint

5,000 images in each condition

Original CIFAR-10 horse
Original
The same image shifted four pixels right with mean fill
Right 4 px
35 40 45 50 55 Validation accuracy (%) Original images Shifted right by 4 pixels 54.08% 54.56% +0.48 pp 39.54% 47.10% +7.56 pp No augmentation Crop + flip Gain

This paired run gains 0.48 pp on original images and 7.56 pp after the shift.

The comparison · 1 / 6

Switch to Evaluation Before Measuring

Before reading validation results, check the evaluation setup.

OperationTrainingEvaluation
Input pipelineRandom crop + flipFixed preprocessing
BatchNormUse batch statisticsUse stored training statistics
DropoutMask + rescalePass activations unchanged
ParametersCompute gradients and updateKeep parameters fixed

Set layer mode, preprocessing and gradient tracking separately.

Evaluation setup · 1 / 6

Where Does the Classifier Make Mistakes?

Show
true ↓ / predicted →0123456789
0 airplane
1 automobile
2 bird
3 cat
4 deer
5 dog
6 frog
7 horse
8 ship
9 truck

CIFAR-10 · 5,000 validation images · CNN

Select a cell. The diagonal counts correct predictions.

Precision and Recall Ask Different Questions

For one class, separate correct predictions, false alarms and misses.

Compare this class with all other classes.
Read the counts · 1 / 4

Look at the Mistakes

Look at the image before seeing the model’s answer.

Inspect case 1 · 1 / 4

Choose a Model. Name the Evidence.

Use validation evidence to choose the next model to test.

Compare measured recipes · 1 / 3