Convolutional Neural Networks

How AlexNet learned to see

Mikhail Mikhasenko · Lecture 3B

From numbers to pictures

A colour image is a tensor of pixel intensities: height × width × 3 channels (red, green, blue).

AlexNet reads a 224 × 224 × 3 tensor, 150 528 numbers, and returns 1000 probabilities, one per ImageNet class.

Inside there is nothing but the neurons of Lecture 3A: weighted sums, ReLUs, and a softmax at the end.

The new idea is how the weights are arranged.

Close-up photo of a tabby cat

224 × 224 × 3 → AlexNet →
class probability
Egyptian cat 0.80
tiger cat 0.13
tabby 0.07

MNIST: the classic benchmark

  • 28 × 28 pixels, grey scale from 0 (black) to 255 (white)
  • 60 000 training and 10 000 test images
  • 10 classes: the digits 0–9
  • Collected by LeCun, Cortes and Burges (1998) from US census and school handwriting

Small enough for a laptop, hard enough to separate methods.

A grid of handwritten digits, twenty examples of each class

MNIST: error rates

Model Details Test error
Linear classifier pairwise, deskewed inputs 7.6 %
Random forest fast unified random forests 2.8 %
Boosted stumps on Haar features 0.87 %
Support-vector machine degree-9 polynomial, jittered 0.56 %
Neural network 784–800–10, no distortions 1.6 %
Deep neural network 784–2500–2000–1500–1000–500–10, elastic distortions 0.35 %
Convolutional network committee of 35 CNNs 0.23 %
Convolutional network ensemble of 3 CNNs, augmentation 0.09 %

Dense networks need hand-made distortions to compete. Convolutional networks build in what images are like.

Why not a dense network?

Too many weights

One dense layer from a 224 × 224 × 3 image to 4096 units:

150528×4096≈6.2×108weights150\,528\times4096\approx6.2\times10^{8}\ \text{weights}

Wrong assumptions

A dense unit treats pixel 17 and pixel 17 000 as unrelated inputs. Shift the cat by a few pixels and every input changes.

What we know about images

Locality: nearby pixels belong together; an edge is a local pattern.

Translation: a pattern means the same thing anywhere in the image.

So: use small detectors, and apply the same detector at every position.

A kernel is a template

Slide a small grid of weights, the kernel, over the image. At each position take the dot product of kernel and patch:

s=∑iwixi=‖𝐰‖‖𝐱‖cosθs=\sum_i w_i\,x_i=\lVert\mathbf w\rVert\,\lVert\mathbf x\rVert\cos\theta

Large when the patch looks like the kernel: a similarity score.

AlexNet first-layer kernel 9, a grey image containing its stripe pattern upright and rotated by 90 degrees, and the resulting activation map

AlexNet kernel 9 (left) slid over an image that contains its own pattern, upright and rotated by 90°. Activation map (right): peak 9.0 on the upright copy, 0.0 on the rotated copy.

Convolution

For one kernel WW of size K×KK\times K, bias bb, stride SS and padding PP:

aij=h(b+∑u=0K−1∑v=0K−1WuvxiS+u−P,jS+v−P)a_{ij}=h\!\left(b+\sum_{u=0}^{K-1}\sum_{v=0}^{K-1}W_{uv}\;x_{iS+u-P,\;jS+v-P}\right)

Output size for an N×NN\times N input:

N′=⌊N+2P−KS⌋+1N'=\left\lfloor\frac{N+2P-K}{S}\right\rfloor+1

  • Local: each output looks at a K×KK\times K patch.
  • Shared: the same K2+1K^2+1 numbers are used at every position.
  • Stride SS skips positions; padding PP adds a border of zeros.

AlexNet conv1: ⌊(224+4−11)/4⌋+1=55\lfloor(224+4-11)/4\rfloor+1=55.

Deep-learning “convolution” does not flip the kernel; mathematicians call it cross-correlation.

Sliding a kernel over an image

Channels: stack and repeat

An input tensor with a kernel spanning its full depth; each kernel produces one activation map; the maps stack into the output tensor

A kernel always spans all input channels: K×K×CinK\times K\times C_{\mathrm{in}} weights.

CoutC_{\mathrm{out}} kernels give CoutC_{\mathrm{out}} activation maps. Stacked, they form a new tensor H′×W′×CoutH'\times W'\times C_{\mathrm{out}}.

The next layer processes it exactly like an image, only with CoutC_{\mathrm{out}} “colours”.

Parameters: K2CinCout+CoutK^2\,C_{\mathrm{in}}\,C_{\mathrm{out}}+C_{\mathrm{out}}.

Counting parameters

Weights Share of AlexNet
conv1: 64 kernels of 11 × 11 × 3, plus biases 23 296
a dense layer with the same 55 × 55 × 64 outputs 2.9×10102.9\times10^{10}
all 5 convolutional layers 2.5 M 4 % of weights, 92 % of computation
the 3 dense layers 58.6 M 96 % of weights, 8 % of computation

Weight sharing cuts conv1 by a factor of a million. The convolutional layers are cheap to store but expensive to run: every weight is used at thousands of positions.

Pooling

Max pooling keeps the largest value in each window:

1 3 2 0
4 2 1 5
0 1 3 2
2 6 1 0
→
4 5
6 3

2 × 2 window, stride 2: a quarter of the values survive.

  • Smaller maps: less computation in later layers.
  • Tolerance to small shifts: the maximum barely moves.
  • Larger receptive fields: later kernels see more of the image.

No weights to learn. AlexNet uses overlapping 3 × 3 windows with stride 2.

Stack and repeat: from edges to corners

A convolutional network

Blocks

[conv→ReLU→pool]×n→\big[\,\text{conv}\to\text{ReLU}\to\text{pool}\,\big]\times n\ \to flatten →\to dense layers →\to softmax

Features first, then a classifier: the dense end is the MLP of Lecture 3A.

LeNet-5 (LeCun et al., 1998)

32 × 32 digit → 6 maps 28 × 28 → pool → 16 maps 10 × 10 → pool → 120 → 84 → 10. About 60 000 parameters; read bank cheques in the 1990s.

Receptive fields grow
AlexNet layer pixels seen by one unit
conv1 11 × 11
conv2 51 × 51
conv3 99 × 99
conv5 163 × 163

Deep units see large parts of the 224 × 224 image.

Train a network, then draw for it

Shift the digits

MNIST digits are centred. Move every test image a few pixels to the right and measure again.

shift 0 px 2 px 3 px
dense 784–128–10 96 % 75 % 47 %
boosted trees (JLBoost) 90 % 69 % 51 %
CNN 97 % 91 % 74 %

Trees and dense networks see each pixel as a fixed input. The CNN applies the same kernels everywhere and pools.

ImageNet

ILSVRC 2010–2017: 1.2 million training images, 1000 classes. Score: top-5 error, the fraction of images whose true class is not among the five best guesses.

Before 2012: hand-designed features (SIFT, Fisher vectors) and linear classifiers.

2012, AlexNet (Krizhevsky, Sutskever, Hinton): 16.4 %, against 26.2 % for the runner-up.

After 2012 every winner was a deep convolutional network.

Top-5 error of ILSVRC winners from 28.2 percent in 2010 to 2.3 percent in 2017, compared with a human estimate of 5.1 percent

AlexNet

AlexNet as a sequence of tensors: input 224 by 224 by 3, five convolutional layers with three pooling steps, and three dense layers ending in 1000 classes

(CONV → RN → MP)² → CONV³ → MP → (FC → DO)² → Linear → softmax

CONV: convolution + ReLU · RN: local response normalization · MP: max pooling · FC: dense + ReLU · DO: dropout

What made AlexNet work

  • ReLU activations: several times faster training than tanh
  • Dropout (p = 0.5) in the two big dense layers
  • Data augmentation: random 224 × 224 crops of 256 × 256 images, horizontal flips, colour shifts
  • SGD with momentum 0.9, weight decay 0.0005, batch 128
  • Two GTX 580 GPUs (3 GB each), five to six days of training
  • 60 million parameters, 650 000 neurons
  • ImageNet: the first labelled image set large enough to feed such a model

The algorithms were from the 1980s. The scale of data and compute was new.

Layer 1: what did AlexNet learn?

The 64 learned 11 by 11 by 3 kernels of AlexNet's first layer shown as small colour images

Each first-layer kernel has depth 3, like the image, so it is a tiny RGB picture.

  • edge detectors at many angles and frequencies
  • colour blobs and colour-opponent edges

Every kernel started as random numbers. These patterns were learned from labelled photos alone.

Activation maps

Sixty-four 55 by 55 activation maps of AlexNet's first layer for a photo of a cat

Input photo of a cat

Sliding each of the 64 kernels over the photo gives 64 activation maps (55 × 55 after ReLU).

A map is bright where the image looks like its kernel: whiskers, eye outlines, fur texture, the pink nose.

Layer 2: combining edges

Input: a white square on a dark background

input: a sheet of paper

All 192 activation maps of AlexNet's second layer for the white square; channel 94 is outlined

all 192 conv2 maps

Channel 94 of conv2: bright spots at the corners of the square

channel 94: corners

Layer-2 kernels are 5 × 5 × 64: we cannot draw them, but we can watch what they respond to. Most maps trace edges of the square; channel 94 fires almost only at its corners.

Layer 5: a face detector nobody asked for

Conv5 channel 174 overlaid on four images: strong on the astronaut's face, silent when the face is covered, strong on the cameraman's face, weak on a cat

conv5, channel 174 · peak activation 14.5 on the astronaut’s face, 0.8 with the face covered, 14.5 on the cameraman, 5.8 on the cat’s nose. ImageNet has no “face” or “person” class.

What does a unit want to see?

Synthetic images that maximize six AlexNet units, from vertical stripes in conv1 to goldfish-like shapes for the goldfish class

conv1 · 9
stripes
conv2 · 94
corners
conv3 · 150conv4 · 60conv5 · 174
eyes, nose
fc8 · goldfish

Start from noise and change the image by gradient ascent until one unit is as active as possible; the weights stay fixed. Deeper units prefer textures, patterns, object parts.

What AlexNet says, and why

image top prediction
espresso 0.97
tripod 0.72
mosque 0.63
dumbbell 0.27

There is no “rocket” or “astronaut” class. A classifier always picks one of its labels.

Cat photo with a grey patch, and a map of the Egyptian-cat probability for every patch position

Occlusion: grey out a patch, record p(Egyptian cat). Covering the eyes hurts most (0.80 → 0.51).

The embedding space

Cosine-similarity matrices of 24 images, original, flipped and cropped copies of eight photos, in raw pixels and in AlexNet's fc7 embedding

Stop before the classifier: every image becomes a point in a 4096-dimensional space (fc7). Flipped and cropped copies of the same photo: similarity 0.34 in pixels, 0.83 in the embedding.

AlexNet under the hood: marimo notebook

AlexNet_under_the_hood.py loads the pretrained network and lets you

  1. classify the samples or your own photo
  2. browse the 64 layer-1 kernels and their maps
  3. open the activation maps of any layer and channel
  4. run the occlusion experiment
  5. visualize what a unit wants to see
  6. place your image in the embedding space

From the Lecture_3B folder:

python3.12 -m venv .venv
.venv/bin/python -m pip install -r requirements.txt
.venv/bin/marimo edit AlexNet_under_the_hood.py

Runs on a laptop CPU; the first start downloads the weights (~240 MB).

Static export of the notebook

After AlexNet: deeper

VGG (2014): only 3 × 3 kernels, 16–19 layers. Two 3 × 3 layers see 5 × 5 with fewer weights.

GoogLeNet (2014): 22 layers of parallel “inception” branches.

ResNet (2015): 152 layers, 3.6 % top-5 error. Each block learns a correction to its input: 𝐲=𝐱+F(𝐱)\mathbf y=\mathbf x+F(\mathbf x)

The skip connection gives gradients a direct path back through many layers: the vanishing-gradient problem of Lecture 3A, solved by architecture.

Since 2020, vision transformers cut images into patches and treat them like words, using the same blocks as language models. Their “Add & Norm” is ResNet’s skip connection.

Scale

LeNet-5 AlexNet GPT-3
Year 1998 2012 2020
Data MNIST: 60 000 images, 10 classes ImageNet: 1.2 M images, 1000 classes ~300 billion tokens of text
Compute one CPU two gaming GPUs thousands of data-centre GPUs
Parameters ~60 000 ~60 million 175 billion
Layers 5 8 96
Key parts convolutions, tanh convolutions, ReLU, dropout transformer blocks with dense layers

The same building blocks, scaled up by factors of a thousand at every step.

End

Thank you for the attention