ECE571 / Week 14 · Convolutional neural networks

Week 14 · Convolutional neural networks

Convolutional neural networks

An MLP treats an image as a long list of unrelated numbers. A CNN slides one small set of weights over the image instead, so it can spot a pattern wherever it appears while using far fewer parameters.

~35 min read 10 practice questions + 2 problems Reading: Géron Ch. 14; Bishop §5.5.6
The big picture

Last week's multilayer perceptron (MLP) takes a vector. To feed it an image you flatten the pixels into one long vector (the week 4 digits became 256 numbers), and the network then has to learn separately that a "5" in the top-left and a "5" in the bottom-right are the same thing. A convolutional neural network (CNN) is built for grid-shaped data such as images. Each neuron looks at only a small patch, and the same small set of weights (a kernel) is slid across the whole image. That one change cuts the parameter count by orders of magnitude and lets a pattern be detected anywhere. Stack a few convolution + ReLU + pooling stages, finish with an ordinary MLP classifier, and you have the architecture behind almost all image classification since AlexNet (2012).

After this you can
Section 1

Why images need a different network

Lecture 00:02–13:30Slides 2–11Géron Ch. 14 intro; Bishop §5.5.6

CNNs are the default tool whenever the input is an image, or anything else laid out on a grid. The lecture opens with examples: predicting a person's age from a face photo, classifying skin cancer from medical images, object detection (drawing a box around every car, truck and person) and object segmentation (labeling which pixels belong to each object). Video works too: it's a stack of images over time, so you can run a CNN on each frame or use 3-D convolutions over the whole block. The professor's rule (01:28): "if you have image data, then the convolutional neural network is the network you should use."

What makes image classification hard

The same object can look very different: front, side or back view, bright or dark lighting, different contrast, and different position, rotation and scale in the frame. The position problem alone breaks an MLP. Flatten an image of a "5" and the pixels that make up the 5 land at certain entries of the vector. Shift the 5 a few pixels and those pixels land at completely different entries. To the MLP these are unrelated inputs, so it has to learn separate weights for every position the 5 might appear in, even though it's the same shape.

Before CNNs, the fix was to engineer the input by hand:

  • Hand-crafted features such as SIFT (scale-invariant feature transform) or HOG (histogram of oriented gradients): find a region of interest, summarize it as one feature vector, and feed that vector to a classifier such as an SVM (week 5).
  • Landmarks for well-structured objects like faces: detect key points (eye corners, nose tip) and match them against a template.
  • Preprocessing: crop and center the object (e.g. cut a patch around a small cat) before classifying it.

The two ideas behind a CNN

A CNN replaces the hand engineering with two structural assumptions (slide 11):

  • Sparse connectivity. Each output neuron is connected only to a small patch of the input (say 3×3 pixels), not to every pixel as in an MLP's fully connected layer. Nearby pixels are strongly related; far-apart pixels much less so (Bishop's motivation).
  • Parameter sharing. The same weights are used for every patch. A detector that finds a vertical edge in one place is just as useful everywhere else.
fully connected 15 separate weights convolution 3 weights, reused
Same 5 inputs and 3 outputs; 15 weights versus 3. In the fully connected layer every line is its own weight. In the convolution each output sees only 3 neighboring inputs, and the lines with the same color share one weight (left, middle, right position in the kernel).

The professor names the payoff of each (12:30): sparse connections make the computation faster, and sharing makes the model smaller (fewer parameters to learn). Later we'll see that in a classic CNN, most of the parameters actually sit in the fully connected layers at the end.

A 28×28 grayscale image goes into a layer whose 26×26 outputs each look at a 3×3 patch. How many weights (ignoring biases) does it have with sharing, and without sharing?

With sharing: one 3×3 kernel, so 9 weights. Without sharing (each output neuron with its own 3×3 weights): . A fully connected layer to the same 676 outputs would need .

Section 2

The convolution operation

Lecture 16:10–22:58, 28:58–31:30, 49:38–51:34Slides 14–17, 21, 38–40Géron Ch. 14 "Convolutional Layers", "Filters"

A kernel (also called a filter or feature detector) is a small grid of weights, typically 3×3 or 5×5; 3×3 is the most common. To apply it, place it over a patch of the image, multiply each weight by the pixel under it, add everything up, and write the sum into one cell of the output. Then slide the kernel one step and repeat. This is the sliding window. The grid of outputs is called a feature map (or activation map), and the patch of input pixels that one output cell depends on is that cell's receptive field. The kernel size sets how big the receptive field is.

input pixel in row , column
kernel weight at row , column of a kernel
one bias for the whole feature map
feature-map value at row , column (before the activation)

This is exactly a perceptron's (weeks 3 and 13) applied to one patch. The slide writes it as for a 3×3 patch. As with any layer, a nonlinear activation follows: the feature map you pass on is , usually with ReLU. The professor stresses (30:52) that the slides' diagrams don't draw it, but it is always there.

Worked example: a vertical edge detector

The image below is dark (1) on the left and bright (7) on the right, with the boundary jogging one column left in the bottom two rows. The kernel has a column of +1s, a column of 0s and a column of −1s: it computes "left column minus right column", the classic vertical edge filter from slides 38–39.

1 1 1 7 7 1 1 1 7 7 1 1 1 7 7 1 1 7 7 7 1 1 7 7 7 1 0 −1 1 0 −1 1 0 −1 0 −18 −18 −6 −18 −12 −12 −18 −6 input X (5×5) kernel W feature map ⋆ = vertical edge 3×3 output
One window position gives one output number. The highlighted window (rows 3–5, columns 1–3) holds rows (1, 1, 1), (1, 1, 7), (1, 1, 7). Row by row: , , , total −12, written to output row 3, column 1. Sliding over all 3 × 3 positions fills the map. It is 0 on flat regions and strongly negative wherever brightness jumps from left to right.
  1. Output size: a 3×3 window fits in 5 − 3 + 1 = 3 positions across and 3 down, so the map is 3×3.
  2. Top-left window (columns 1–3, rows 1–3) is all 1s: each row gives , so . Flat region, no edge.
  3. Top-middle window (columns 2–4, rows 1–3): every row is (1, 1, 7), giving three times, so . The window straddles the edge in all three rows.
  4. Bottom-right window (columns 3–5, rows 3–5): rows (1, 7, 7), (7, 7, 7), (7, 7, 7) give , so . Only one row still sees the edge.
  5. Full map: . The big magnitudes trace the edge, including its jog. (Checked with scipy.signal.correlate2d.)

The sign tells you the direction of the edge: this kernel gives negative values for dark-to-bright (left to right) and positive values for bright-to-dark. After a ReLU, only the positive responses survive, so a network that wants dark-to-bright edges simply learns the mirrored kernel. The horizontal version, rows (1, 1, 1), (0, 0, 0), (−1, −1, −1), responds to top-versus-bottom changes (slide 40). Run on a handwritten digit, the vertical filter lights up the left and right sides of each stroke, and the horizontal one the tops and bottoms.

Heads up: it's cross-correlation, not convolution (lecture 21:01)

The handwriting on slide 15 says "2D convolution", but the formula above, and what PyTorch's Conv2d and Keras's Conv2D compute, is cross-correlation: the kernel is used as is. A true mathematical convolution flips the kernel first ( instead of ). For our edge kernel, flipping swaps the +1 and −1 columns, so true convolution would give the same map with every sign reversed (0, 18, 18, …). The professor says it correctly: formally it's correlation, but deep learning uses the two words interchangeably. Géron's footnote says the same. It doesn't matter in practice because the kernel is learned: the network just learns the flipped version.

Where do kernels come from? In classical image processing you design them by hand (edge filters, Sobel filters). In a CNN they're learned by gradient descent. "A CNN can learn whatever it finds best based on optimizing the objective" (slide 40). Remarkably, the first layer of a trained CNN ends up looking like a bank of edge and color-blob detectors (Section 9).

Apply the horizontal kernel (rows +1, 0, −1) to the top-left window of the worked example (all 1s) and to a window whose rows are (1, 1, 1), (1, 1, 7), (1, 1, 7).

All 1s: top row sum 3, bottom row sum 3, so .

Second window: top row sum , bottom row sum , so . This matches row 3, column 1 of the full horizontal map ( in the first row, below), computed by the same script.

Section 3

Padding, stride and the output size

Lecture 23:46–27:34, 31:30–31:58Slides 19, 22Géron Ch. 14 "Convolutional Layers", "TensorFlow Implementation"

Two settings control how the kernel moves:

  • Padding : add a border of extra pixels around the image before sliding. Usually the border is zeros (zero padding); mirroring the edge pixels also works. The professor notes the choice makes only a marginal difference to accuracy. Padding lets the kernel center on edge pixels, so the map doesn't shrink.
  • Stride : how many pixels the window jumps between positions. Stride 1 visits every position; stride 2 skips every other one and roughly halves the width and height.

input width (do the same for the height)
kernel width
padding added on each side (hence )
stride
output (feature-map) width

Why it works: after padding there are pixels, the kernel's left edge can sit at positions as long as it stays at most , and counting those positions gives the formula.

padding p = 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 out = (5 + 2 − 3)/1 + 1 = 5 stride s = 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ⌊(5 + 2 − 3)/2⌋ + 1 = 3
Padding keeps the size; stride shrinks it. Gray cells are the zero border around a 5×5 image, dots are the window centers. Left: with the 3×3 window can center on the corner pixel, so all 25 pixels get an output (5×5 → 5×5). Right: with the window jumps two cells, so only 3 positions fit per row (5×5 → 3×3).
Worked examples

LeNet's first layer (lecture 27:02): 32×32 input, 5×5 kernel, no padding, stride 1: , so 28×28. That's the "28" in "6@28×28".

Slide 22's question ("what is the output size for this 28×28 image?" with a 5×5 kernel, stride 1): , so 24×24, as the professor wrote on the slide.

"Same" padding for a 3×3 kernel: gives . In general, with stride 1 keeps the size for odd .

Stride that doesn't divide evenly: 6×6 input, 3×3 kernel, , : , floor to 1, plus 1 gives 2. The last column and row are never reached by a window.

Heads up: slide 19 leaves out the floor

Slide 19 writes with no rounding. That only works when divides . Otherwise the fraction isn't an integer, and frameworks round down (PyTorch's Conv2d docs use the floor; Géron calls the leftover rows and columns "ignored" under "valid" padding). Use the floored version. (Géron's "same" padding with stride rounds the other way, , because it adds just enough padding to make that true.)

Stride versus pooling. The professor points out (26:20) that a stride-2 convolution already halves the map, so you may not need a separate pooling layer to shrink it. Many modern networks do exactly that.

An input is 7×7. What is the output size with a 3×3 kernel and (a) P = 0, S = 1; (b) P = 1, S = 1; (c) P = 0, S = 2; (d) P = 1, S = 2?

(a) . (b) ("same"). (c) . (d) .

Section 4

Channels and parameter counts

Lecture 22:26–23:46, 31:30–31:58, 46:46–49:38Slides 18, 22, 34–37Géron Ch. 14 "Stacking Multiple Feature Maps", "Memory Requirements"

One kernel finds one kind of pattern, so a layer uses many kernels. Each kernel produces its own feature map, and the maps are stacked; each one is called a channel. "6@28×28" on the LeNet diagram means 6 kernels, so 6 channels, each 28×28.

Images have channels too: a grayscale image has one, a color image has three (red, green, blue). When the input has channels, each kernel is a block. It covers the patch in every input channel at once and adds everything into one number. So a layer's weights form a 4-D array:

channels coming in (3 for RGB, or the previous layer's number of kernels)
number of kernels in this layer = channels going out
which output channel (which kernel)
one bias per kernel, the in

The count does not depend on the image size at all. That's weight sharing at work.

input H × W × 3 1 kernel 3 × 3 × 3 ⋆ 1 map Σ channels+ bias C_out maps one perkernel every kernel spans all input channels
Each kernel spans all input channels and produces one map. A 3×3×3 kernel on an RGB image multiplies 27 numbers per position, sums them with one bias, and writes one value. kernels give stacked maps, which are the next layer's input channels.
Worked examples from the slides

Slide 22 (Conv2d(in_channels=1, out_channels=8, kernel_size=5)): weight shape [8, 1, 5, 5], bias shape [8], so parameters.

Slides 36–37: RGB input, 5×5 kernels, 5 output channels: parameters.

Slide 37, the same job with a fully connected layer: 128×128 RGB image in, and (with "same" padding) a 128×128×5 output. Every one of the outputs connects to all inputs:

About four billion parameters versus 380, for the same output shape. (Verified.)

Heads up: slide 34 and lecture 47:16 on tensor layout

The slide and lecture say CUDA and PyTorch use "NCWH". PyTorch's actual layout is NCHW: batch, channels, height, then width (that's why slide 22 shows (1, 28, 28) and a weight of [out, in, kH, kW]). TensorFlow/Keras default to NHWC (Géron: [mini-batch size, height, width, channels]). For square images you won't notice, but for a 640×480 image the order matters.

A layer takes 64 channels in and uses 128 kernels of size 3×3. How many parameters? How many if the input image doubles in size?

. Unchanged if the image doubles: the count depends only on , , . (The amount of computation and memory does grow with the image.)

Section 5

Pooling

Lecture 34:08–40:40Slides 26–28Géron Ch. 14 "Pooling Layers"; Bishop §5.5.6

A pooling layer shrinks each feature map by summarizing small blocks. The older name, used on the LeNet diagram, is subsampling. Slide the pooling window as in a convolution (most often 2×2 with stride 2) and replace each block with one number:

  • Max pooling: keep the largest value in the block. The most common choice.
  • Mean (average) pooling: keep the average.

Pooling works on each channel separately, so the number of channels doesn't change, and the output size follows the same formula as convolution.

1 3 2 0 4 6 1 1 0 2 5 7 3 1 8 2 4×4 feature map max 6 2 3 8 average 3.5 1 1.5 5.5 2×2, s=2 no weights: a fixed rule
2×2 pooling with stride 2 turns 4×4 into 2×2. Each colored block becomes one number. Max keeps the bold value (6, 2, 3, 8); average gives , , , . Three quarters of the values are discarded.

Slides 27–28 show the same thing with 3×3 blocks and stride 3 on a 6×6 map: max gives (8, 5 / 6, 3) and mean gives (3.78, 2.33 / 3, 1.22). I re-checked those numbers; they're right.

What pooling is for

  • Less computation and memory: each 2×2 pool cuts the number of values by 4.
  • Tolerance to small shifts: if a strong response moves by a pixel but stays inside the same pooling block, the max doesn't change.
  • A pyramid of scales: repeated pooling views the image at coarser and coarser resolution, which the professor says (37:40) gives some ability to handle scale.
feature map after max pool A 9 0 0 0 9 0 same B 0 9 0 0 9 0 same C 0 0 9 0 0 9 moved
Max pooling forgives small shifts, not big ones. A strong response (9) moves one position (A → B) and stays inside the first pooling block: the pooled output is unchanged. Move it once more (C) and it crosses into the next block, so the output moves too. This is Géron's Figure 14-9 idea in 1-D.

Downsides (slide 27): information is lost. That may be fine for classification ("is there a cat?"), but hurts tasks where exact positions matter, such as face recognition (relative positions of eyes and mouth) or segmentation. Rotation is another weak spot (37:57): a kernel isn't rotation-invariant, so rotating a patch changes its response, and plain CNNs don't handle rotation unless specially designed or trained on rotated examples. The slide's practical advice: "some image preprocessing still recommended".

No learnable parameters (slide 28, lecture 39:44): max and mean are fixed rules. People have tried learnable pooling; it's slower and hasn't paid off, so today almost nobody uses it.

Heads up: "CNNs handle translation" needs care (lecture 34:08 vs slide 26)

The lecture says CNNs have "a better capability to deal with translation, location and scaling". Slide 26 says the opposite-sounding thing: "CNNs are not really invariant to scale, rotation, translation, etc. The activations are still dependent on the location." Both are true once you separate two words. A convolution is equivariant to shifts: shift the input and the feature map shifts by the same amount (Bishop §5.5.6 puts it this way). It is not invariant: the output does change. Pooling adds a little real invariance, for shifts smaller than a pooling block. Géron notes that for tasks like segmentation you want equivariance, not invariance.

Cross-check with the textbook: LeNet's subsampling had weights

"Typical pooling layers do not have any learnable parameters" is true today. But Bishop (§5.5.6) describes the original LeNet subsampling units as averaging a 2×2 block, then multiplying by an adaptive weight, adding an adaptive bias, and applying a sigmoid. Géron's LeNet-5 table likewise lists S2 and S4 as average pooling with a tanh activation. That's the "early age of deep learning" learnable pooling the professor mentions (40:19).

A 2×2 block holds 1, 5, 3, 2. What do max and average pooling output? How many parameters does a 2×2 max-pool layer on 64 channels have?

Max = 5, average = . Zero parameters, no matter how many channels.

Section 6

A whole CNN: LeNet-5

Lecture 13:30–20:16, 27:02–31:30, 48:12–49:38Slides 12–14, 20–21, 37Géron Ch. 14 "CNN Architectures", "LeNet-5"

The lecture's running example is LeNet-5 (LeCun, Bottou, Bengio and Haffner, 1998), built to read handwritten digits. A 32×32 grayscale image goes through alternating convolution and subsampling, then fully connected layers, ending in 10 outputs, one per digit.

input 32×32 C1 6@28×28 S2 6@14×14 C3 16@10×10 S4 16@5×5 C5 120 F6 84 out 10 feature extractor classifier
The map gets smaller and the stack gets deeper. Width and height shrink 32 → 28 → 14 → 10 → 5 → 1 while the channels grow 1 → 6 → 16 → 120. The convolution and pooling layers act as an automatic feature extractor; the last layers form an ordinary MLP classifier (slide 21). Squares are drawn to scale.
LayerOperationOutputSize checkParameters
Inputgrayscale image1@32×320
C16 kernels, 5×56@28×2832 − 5 + 1(25 + 1)·6 = 156
S22×2 pooling, stride 26@14×1428 / 20
C316 kernels, 5×5×616@10×1014 − 5 + 1(150 + 1)·16 = 2,416
S42×2 pooling, stride 216@5×510 / 20
C5120 kernels, 5×5×16120 (1×1)5 − 5 + 1(400 + 1)·120 = 48,120
F6fully connected84120·84 + 84 = 10,164
Outputfully connected1084·10 + 10 = 850
Total61,706

Two things to notice. First, C5's 5×5 kernel exactly covers S4's 5×5 maps, so each of its 120 outputs sees all values: it's a convolution in name but a fully connected layer in effect (the professor's "16 × 25 = 400" on slide 13, and his description of C5 as "a mapping from S4 after vectorization"). Second, C5 + F6 + output hold 59,134 of the 61,706 parameters, about 96%. That's the lecture's point (48:54): in a classic CNN, the dense layers at the end hold most of the parameters and are the computational bottleneck. (The parameter counts assume every C3 kernel sees all 6 S2 maps, as a modern implementation would. The 1998 original wired C3 to subsets of maps and used a slightly different output layer, which brings its total to about 60,000.)

Vocabulary from the diagram (slide 14)

  • "Feature detectors" = kernels = filters, reused across positions (weight sharing).
  • "6@28×28": the number before @ is the number of feature maps (channels); after @ is the feature-map size.
  • "Subsampling" = what we now call pooling.
  • "Gaussian connections": LeNet's output layer measured squared distances to class templates, which is essentially a fully connected layer with mean-squared-error loss. Today you'd use a fully connected layer + softmax + cross-entropy loss (week 13).

Hidden layers, features and the classifier

The input and output layers are fixed by the problem; everything in between is hidden. Each "bunch" of feature maps produced by a convolution, and each fully connected layer, counts as one layer. Pooling layers don't count: they have no weights. When a paper talks about "the feature vector" of an image, it usually means the activations of the second-to-last layer (here the 84-dimensional F6). The final layer, which turns those features into class scores, is "the classifier". Slide 21 draws the line more loosely: everything fully connected is the "regular classifier" and everything convolutional is the "automatic feature extractor".

Heads up: lecture 28:15 / slide 20, counting layers

Slide 20 says "counting the FC layers, this network has 5 layers", and the lecture says "the hidden layer is 5". The five are the layers with weights: C1, C3, C5, F6 and the output layer, and that's where the "5" in LeNet-5 comes from. But the output layer isn't hidden, so strictly LeNet-5 has 4 hidden layers and 5 weight layers. (LeCun's paper counts 7 layers because it includes the two subsampling layers.)

Heads up: lecture 13:31 calls this network "AlexNet"

The professor introduces the slide 13–14 network as "AlexNet" and says AlexNet uses MSE loss (18:01), then corrects himself at 19:20: the pipeline was developed by Yann LeCun. The network on slides 12–14 and 20–21 is LeNet-5 (1998). AlexNet is the much larger 2012 ImageNet network of Section 9, and it used softmax with cross-entropy.

Worked example: a small modern CNN for 28×28 digits

Input 28×28×1. Conv 3×3, 8 kernels, → ReLU → max-pool 2 → conv 3×3, 16 kernels, → ReLU → max-pool 2 → flatten → fully connected to 10 classes.

LayerOutputParameters
conv 3×3, 8, P = 128×28×8(9·1 + 1)·8 = 80
max-pool 214×14×80
conv 3×3, 16, P = 114×14×16(9·8 + 1)·16 = 1,168
max-pool 27×7×16 = 7840
fully connected → 1010784·10 + 10 = 7,850
Total9,098

Compare the first layer with a fully connected layer producing the same 28×28×8 = 6,272 outputs from the 784 pixels: parameters, about 61,500 times the convolution's 80. Even in this small net, the one fully connected layer holds 86% of all the parameters.

In LeNet-5, what would the output of C1 be if it used "same" padding? What would then come out of S2?

"Same" padding for a 5×5 kernel is : , so 6@32×32. S2 halves it to 6@16×16.

Section 7

Receptive fields grow with depth

Lecture 21:30–22:26, 51:34Slide 15Géron Ch. 14 "Convolutional Layers", "CNN Architectures"

The lecture defines the receptive field as the patch of pixels one feature-map cell sees, and says the kernel size sets it. That's true for the first layer. Deeper layers see more: a layer-2 neuron looks at a 3×3 patch of layer-1 cells, and each of those looks at its own 3×3 patch of pixels, so together they cover 5×5 pixels.

input layer 1 (3×3) layer 2 (3×3) sees 5 pixels sees 3 pixels
Two 3×3 layers see 5 pixels across; three see 7. Shown in one dimension: the orange layer-2 cell connects to 3 layer-1 cells, which connect to 5 different input pixels. This is how deep layers come to respond to whole object parts rather than tiny edges (Section 9).

receptive-field width (in input pixels) of a layer- cell
"jump": how many input pixels apart neighboring layer- cells are
kernel (or pooling window) size and stride of layer
  1. Three 3×3 convolutions, stride 1: . Each layer adds 2.
  2. Conv 3×3 → max-pool 2×2 (stride 2) → conv 3×3: , then with jump 2, then . After pooling, each extra layer adds twice as much: pooling speeds up the growth.
  3. LeNet-5: C1 (5) → S2 (6) → C3 (14) → S4 (16) → C5 (32). A C5 neuron sees the whole 32×32 image, which is what you want right before classifying.
Why modern nets use 3×3 kernels

Two stacked 3×3 layers see the same 5×5 region as one 5×5 layer, but use weights instead of (for channels in and out), and they get an extra ReLU in between. Géron calls using kernels that are too large "a common mistake", except possibly in the first layer. This is why the professor says 3×3 is the most common kernel size.

What is the receptive field of a neuron after four stacked 3×3 convolutions with stride 1? After conv 3×3 with stride 2 followed by conv 3×3 with stride 1?

Four stride-1 layers: , so 9×9.

Stride-2 then stride-1: first , ; then , so 7×7.

Section 8

Backpropagation with shared weights

Lecture 31:58–34:08Slides 23–25Bishop §5.5.6

Training a CNN is the same gradient descent with backpropagation as for last week's MLP. The only new wrinkle is the "additional weight sharing constraint" (slide 23): each kernel weight is used at every position, so it influences the loss through many paths. The multivariable chain rule (slide 24) says what to do: add up the contributions from every path.

w₁ w₂ w₁ w₂ x₁ x₂ x₃ z₁ z₂ L w₁ is used twice, so ∂L/∂w₁ has two terms
A shared weight's gradient is a sum over its uses. A 1-D kernel slides over three inputs. Teal edges all use , orange edges all use . The gradient for collects one term from and one from .

For a kernel weight , : the input pixel that weight touched at that position.

Worked example

Inputs , kernel , targets , loss .

  1. Forward: , . Loss .
  2. Output errors: , .
  3. touched (for ) and (for ):

  4. touched and :

  5. Gradient step with : . A finite-difference check of the loss gives the same gradient .

Because every position sends its gradient into the same weight, each copy stays identical after the update. That's how the constraint on slide 25 (the same weight at two places in the image) is maintained automatically.

Heads up: slide 25's "optional averaging" (lecture 33:04)

Slide 25 updates a shared weight with , and the lecture calls the update "the average of the summation". The true gradient of the loss with respect to the shared weight is the sum. Averaging just divides it by the number of uses, which is the same as using a smaller learning rate; that's why the slide labels it optional. Frameworks such as PyTorch use the sum. On an exam, if asked for "the gradient", give the sum.

A kernel weight is used at 4 positions, and the per-position gradient terms are 0.2, −0.5, 0.1 and 0.4. What is its gradient, and what is the update with η = 0.5?

Gradient . Update: .

Section 9

AlexNet, ImageNet and what CNNs learn

Lecture 40:40–55:32Slides 29–33, 38–44Géron Ch. 14 "AlexNet", "CNN Architectures"

AlexNet (Krizhevsky, Sutskever and Hinton, 2012) is the breakthrough that made CNNs mainstream. It won the ImageNet challenge with a top-5 error of about 17%, against 26% for the runner-up (Géron), whose methods were based on hand-crafted features. Its structure is LeNet's, scaled up: five convolutional layers with max pooling, then three fully connected layers. What was new:

  • ReLU activations instead of sigmoid/tanh, which train much faster in deep nets (week 13).
  • GPU training, with the network split across two GPUs (that's why slide 29's diagram has two parallel streams).
  • Regularization with dropout and data augmentation (random shifts, flips, lighting changes), from Géron.

ImageNet (the challenge version): about 1.2 million training images in 1,000 classes collected from the internet. Top-5 accuracy counts a prediction as correct if the true label is among the model's 5 highest-scoring classes; top-1 requires the single best guess to be right.

Fixed input size (43:18): images are resized to one size, usually 224×224 (still standard today, because bigger inputs cost much more computation). That's 224·224·3 = 150,528 input numbers. The size has to be fixed because the flattened vector going into the first fully connected layer must have a fixed length. (Géron's fully convolutional networks replace the dense layers with convolutions and accept any size.)

Cross-check with the textbook: 224 or 227?

Slide 32 (following the paper) says the inputs were 224×224. AlexNet's first layer uses 11×11 kernels with stride 4 and outputs 55×55. Check: , not 55. With 227: exactly. Géron's AlexNet table lists the input as 227×227 for this reason. It's a well-known inconsistency in the original paper and a nice exercise with the output-size formula.

Where the parameters are. Counting AlexNet layer by layer (as one network, without the two-GPU split): the five convolutional layers have about 3.7 million parameters, while the three fully connected layers have about 58.6 million, roughly 94% of the total. The first one alone (6×6×256 = 9,216 inputs → 4,096 outputs) has 37.8 million. That's the "bottleneck" the professor points to at 44:07: dense layers are slow and huge; convolutions are cheap because their connections are sparse.

After AlexNet

Slide 33 (Canziani et al., 2016) compares later architectures (VGG, GoogLeNet/Inception, ResNet, and others) by accuracy, computation and size. The lecture's summary: accuracy improved a lot over the years, top-1 accuracy on ImageNet is now close to 90%, top-5 is near 100%, and the professor considers ImageNet classification essentially "solved". Géron covers these architectures in the sections after AlexNet (GoogLeNet, VGGNet, ResNet), which are reading, not lecture material.

Heads up: "outperforms humans" (lecture 45:59)

The comparison with humans is usually made on top-5 error: a human annotator's top-5 error on ImageNet was estimated at about 5%, and CNNs passed that around 2015. The 86–90% figure the professor quotes is top-1 accuracy, which doesn't have a matching human number. Also, slide 33's paper is from 2016, not 2019 as said in the lecture.

What a CNN sees

The learned kernels can be visualized. AlexNet's first-layer kernels (slide 30) look like oriented edge detectors and color blobs, much like the hand-designed edge filters of image processing. Zeiler and Fergus (2014, slides 41–44) went deeper: take a strongly activated neuron, push its activation back down to pixel space (backpropagating and "unpooling"), and see which image patterns fire it. A hierarchy appears:

  • Layer 1: edges and simple color patterns.
  • Layer 2: corners, textures, simple shapes.
  • Layer 3: object parts (a mesh pattern, a wheel, a face-like arrangement).
  • Layers 4–5: whole objects or object classes (dog faces, people, bicycles), grouped like clusters across many images.

The professor's takeaway (53:43): a CNN classifier is really detecting specific concepts in the image and classifying from those detections. That's why the same networks transfer so naturally to object detection.

Flagged in lecture · 54:20 and 55:04: homework

"For this lecture, you should be familiar with the concepts, for example kernels, feature maps, convolutions, FC layers, pooling layers, activation maps, kernel size, feature map size, and try to connect them together." Then: search for CNN image-classification code online, "try to read the code, see how you implement the CNN using, for example, PyTorch to finish certain tasks. So this is somehow the homework, the purpose of the homework." The PyTorch sketch below is the 28×28 network from Section 6.

nn.Conv2d(1, 8, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(8, 16, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
nn.Flatten(), nn.Linear(16*7*7, 10)

Train with nn.CrossEntropyLoss() (it applies the softmax for you). Every number here is something you can now derive: 3×3 kernels with padding 1 keep 28×28, each pool halves it, and 16 channels × 7 × 7 = 784 inputs to the last layer.

Why does AlexNet need a fixed input size, when its convolution layers would work on any size?

The convolution and pooling layers would happily produce bigger or smaller maps. But the first fully connected layer has a weight matrix sized for exactly 6×6×256 = 9,216 inputs. A different image size gives a different flattened length, and the matrix no longer fits. Remove the dense layers (fully convolutional network) or end with global average pooling and the restriction goes away.

Section 10

Cheat sheet

Conv (as used), cross-correlation; true convolution flips the kernel
Output size; "same" with stride 1:
Conv parameters, independent of image size
FC parameters
Kernel tensor, bias ; PyTorch data NCHW, Keras NHWC
Poolingmax or mean over each block, per channel; usually 2×2, stride 2; 0 parameters
Receptive field, ; stacked 3×3 stride-1 →
Shared-weight gradientsum of the gradient terms over every position the weight is used
Two key ideassparse connectivity (faster), parameter sharing (fewer parameters)
Invarianceconv is shift-equivariant; pooling adds small-shift invariance; no rotation invariance
LeNet-532×32 → 6@28×28 → 6@14×14 → 16@10×10 → 16@5×5 → 120 → 84 → 10; ~96% of params in C5/F6/out
AlexNet2012, ReLU + GPUs + dropout; 227×227×3 input; ~94% of params in FC layers
Top-5 accuracycorrect if the true label is among the 5 highest scores
What layers learnedges → textures → parts → objects
Section 11

Practice

Score: 0 / 0

Q1A 32×32 image goes through a 5×5 convolution with no padding and stride 1. What is the feature-map size?

Q2A conv layer has 3×3 kernels, 16 input channels and 32 output channels. How many parameters?

Q32×2 max pooling with stride 2 is applied to the 4×4 map with rows (4, 1, 2, 8), (0, 3, 5, 1), (6, 2, 3, 3), (1, 0, 7, 2). What is the output?

Q4What does a PyTorch Conv2d layer actually compute, and does it matter?

Q5Which property makes a conv layer's parameter count independent of the image size?

Q6A 6×6 input, 3×3 kernel, no padding, stride 2. Output size?

Q7Three 3×3 convolutions with stride 1 are stacked. How wide is the receptive field of a neuron in the third layer?

Q8A shared kernel weight is used at two positions, contributing gradient terms 0.4 and −0.1. What is ∂L/∂w?

Q9In classic CNNs like LeNet-5 and AlexNet, where are most of the parameters?

Q10You shift an input image 1 pixel to the right. What happens to the output of a stride-1 conv layer (no pooling)?

Problem 1: Input rows (2, 0, 1, 3), (1, 4, 0, 2), (0, 1, 5, 1), (3, 2, 1, 0). Kernel rows (1, −1), (1, −1), stride 1, no padding. (a) Give the output size and the feature map. (b) Apply ReLU. (c) Apply 2×2 max pooling with stride 1.

(a) Size , so 3×3. Each entry is (top-left − top-right) + (bottom-left − bottom-right) of a 2×2 window. Top row: , , . Middle: , , . Bottom: , , .

(b) ReLU zeroes the negatives: rows (0, 3, 0), (0, 0, 2), (0, 0, 5).

(c) Output , so 2×2: max(0, 3, 0, 0) = 3, max(3, 0, 0, 2) = 3, max(0, 0, 0, 0) = 0, max(0, 2, 0, 5) = 5. Result rows (3, 3), (0, 5).

Checked with scipy.signal.correlate2d. Note how ReLU throws away the "wrong-direction" edges, which the network would catch with a second, mirrored kernel if it needed them.

Problem 2: An RGB 64×64 image goes through conv 5×5, 16 kernels, P = 2, S = 1 → ReLU → max-pool 2×2, stride 2 → conv 3×3, 32 kernels, P = 1, S = 2 → ReLU → flatten → fully connected to 10 classes. Give every output shape, every layer's parameter count, the total, and the receptive field of a neuron after the second conv. Compare the first layer with a fully connected layer producing the same output shape.

Conv 1: , so 64×64×16. Parameters .

Pool: 32×32×16, no parameters.

Conv 2:

so 16×16×32. Parameters .

Flatten: . FC: .

Total: . Again the single dense layer dominates (93%).

Receptive field: conv 5×5: ; pool: ; conv 3×3 stride 2: , so 10×10 pixels.

FC instead of conv 1: inputs to outputs:

That's about 660,000 times the conv layer's 1,216.