Notes / Robot Learning

Convolutional Neural Networks

Updated

Introduction

In Convolution and Image Filtering, we saw how sliding a small kh×kwk_h \times k_w weight matrix KK (a kernel or filter) across a 2D grayscale image X∈RH×WX \in \mathbb{R}^{H \times W} extracts local spatial structure. At each pixel position (i,j)(i, j), 2D cross-correlation multiplies the aligned kh×kwk_h \times k_w image patch by KK and sums:

(X⋆K)[i,j]=∑u=0kh−1∑v=0kw−1X[i+u, j+v] K[u,v].(X \star K)[i, j] = \sum_{u=0}^{k_h - 1} \sum_{v=0}^{k_w - 1} X[i + u,\, j + v]\, K[u, v].

(Signal processing reserves the word convolution for sliding a 180∘180^\circ-flipped kernel X∗KX * K, whereas deep learning frameworks compute cross-correlation above and call it convolution because the weights in KK are learned anyway.)

Instead of hand-designing one 3×33 \times 3 kernel to smooth noise or highlight edges, a convolutional neural network (CNN) initializes entire banks of filters randomly and lets gradient descent discover whichever filters minimize a task’s loss. In this note, we will build up the machinery behind CNNs until we’re able to understand the LeNet-5 architecture, the seed of modern vision techniques.

Convolutional Layers

Padding and Stride

Suppose an input image has height HH and width WW, and we slide a k×kk \times k kernel across it one pixel at a time. Without anything outside the border, the kernel’s top-left corner can start at row 0,1,…,H−k0, 1, \ldots, H - k, giving H−k+1H - k + 1 valid positions vertically (and W−k+1W - k + 1 horizontally). Every pass of the kernel therefore shaves k−1k - 1 pixels off of both height and width (two pixels when k=3k = 3) - gradually shrinking away the image and underweighing pixels near the edges (a corner pixel touches only one k×kk \times k window, whereas an interior pixel touches k2k^2).

To prevent this shrinkage, we can surround the input border with pp rows and columns of zeros, called zero-padding, which expands the effective input size to (H+2p)×(W+2p)(H + 2p) \times (W + 2p). This ensures that each pixel in the original input image gets the same consideration by the kernel, but as you might imagine, can create headaches in other areas since, by adding zeros, we might be adding features into the image that weren’t originally there!

We can also control how far the window jumps between evaluations. Up to now we have shifted the kernel by one pixel at a time; more generally, the stride s≥1s \ge 1 is the step size (in pixels) between adjacent window positions, so output entry (i,j)(i, j) anchors its window at (s i, s j)(s\,i,\, s\,j) in the padded input.

You may ask - why would we want to jump more than one pixel at a time? A few reasons, which we will add to later:

  1. With stride s=1s = 1 and matching zero-padding, the output keeps the same spatial dimensions as the input. In deep learning, we often want to progressively compress the spatial grid as we extract higher-level features; stepping with s>1s > 1 shrinks the output directly.
  2. Compressing the grid at each stage cuts memory and compute cost, since both scale directly with the spatial size Hout×WoutH_{\text{out}} \times W_{\text{out}} of the layer’s output.
  3. At s=1s = 1, adjacent windows overlap heavily—two neighboring 3×33 \times 3 patches share six of their nine entries, and adjacent pixels in natural images tend to vary slowly—so stepping by more than one pixel avoids spending compute on highly redundant neighboring evaluations.

Let’s briefly go through the math to compute the size of the output image from the stride ss. Placing the first kk-pixel window at index 00 uses up kk pixels and leaves (H+2p)−k(H + 2p) - k pixels of room to travel. Each step of stride ss consumes ss of those remaining pixels, so we can take ⌊(H+2p−k)/s⌋\lfloor (H + 2p - k)/s \rfloor steps after the initial placement (rounding down with ⌊⋅⌋\lfloor \cdot \rfloor because a leftover remainder smaller than ss cannot fit another full window). Counting the initial window at index 00 adds 11:

Hout=⌊H+2p−ks⌋+1,Wout=⌊W+2p−ks⌋+1.H_{\text{out}} = \left\lfloor \frac{H + 2p - k}{s} \right\rfloor + 1, \qquad W_{\text{out}} = \left\lfloor \frac{W + 2p - k}{s} \right\rfloor + 1.

Two settings appear constantly in practice:

  • Same-size filtering (s=1s = 1, p=k−12p = \frac{k-1}{2} for odd kk): with k=3k = 3 and p=1p = 1, Hout=(H+2−3)/1+1=HH_{\text{out}} = (H + 2 - 3)/1 + 1 = H, preserving spatial resolution.
  • Strided halving (k=3,p=1,s=2k = 3, p = 1, s = 2): for even HH, Hout=⌊(H−1)/2⌋+1=H/2H_{\text{out}} = \lfloor(H - 1)/2\rfloor + 1 = H/2, filtering and downsampling by 2×2\times in one pass.

From Grayscale to Multiple Channels

Everything so far has treated an image as a single H×WH \times W grid of brightness values (grayscale). A color camera, however, records three separate H×WH \times W grids at once—one for red, one for green, and one for blue. Each of those parallel 2D grids is called a channel, and stacking the three grids together represents a color image as a 3×H×W3 \times H \times W array XX.

Why stop at three channels? As we saw in Convolution and Image Filtering, a single 3×33 \times 3 kernel can only detect one kind of local pattern, such as vertical edges or horizontal edges. To understand a complex scene, a convolutional layer learns a whole bank of CoutC_{\text{out}} different filters in parallel. Each filter produces its own Hout×WoutH_{\text{out}} \times W_{\text{out}} response grid (called an output channel or feature map), and stacking all CoutC_{\text{out}} grids together produces a Cout×Hout×WoutC_{\text{out}} \times H_{\text{out}} \times W_{\text{out}} array YY. The next convolutional layer then reads YY in the exact same way, seeing CinC_{\text{in}} input channels.

How does one filter process an input that has CinC_{\text{in}} channels? A common misconception is that it slides a flat kh×kwk_h \times k_w matrix over each channel separately. Instead, a single filter W(m)W^{(m)} is a 3D block of weights of shape Cin×kh×kwC_{\text{in}} \times k_h \times k_w that reaches across all CinC_{\text{in}} input channels simultaneously. At position (i,j)(i, j), it multiplies all Cin⋅kh⋅kwC_{\text{in}} \cdot k_h \cdot k_w aligned values, sums them into a single number, and adds a learnable scalar offset bmb_m (called a bias, which shifts the filter’s baseline output up or down just like the intercept in wx+bw x + b). That single number becomes entry (i,j)(i, j) of output channel mm.

3D filter W^(m) spanning all C_in input channels to produce slice m of output volume Y.

Grouping all CoutC_{\text{out}} filters together packs their weights into a four-indexed array W∈RCout×Cin×kh×kwW \in \mathbb{R}^{C_{\text{out}} \times C_{\text{in}} \times k_h \times k_w} with biases b∈RCoutb \in \mathbb{R}^{C_{\text{out}}}. Writing XpadX_{\text{pad}} for the zero-padded input, the complete forward pass of a convolutional layer is

Y[m,i,j]=bm+∑c=0Cin−1∑u=0kh−1∑v=0kw−1Xpad[c, s i+u, s j+v] W[m,c,u,v],Y[m, i, j] = b_m + \sum_{c=0}^{C_{\text{in}} - 1} \sum_{u=0}^{k_h - 1} \sum_{v=0}^{k_w - 1} X_{\text{pad}}[c,\, s\,i + u,\, s\,j + v]\, W[m, c, u, v],

for each output channel m∈{0,…,Cout−1}m \in \{0, \ldots, C_{\text{out}} - 1\}. From this sum we can read off both the memory footprint (how many weights are stored) and the compute cost of a forward pass. In deep learning, compute is usually counted in multiply-adds (also called MACs, for multiply-accumulates). One multiply-add is a single sum += x * w step - multiplying one input activation by one weight and adding the product into a running sum (which modern CPUs and GPUs execute as a single fused hardware instruction, and which equals two individual floating-point operations, or 2 FLOPs2\text{ FLOPs}). Each filter stores Cin kh kwC_{\text{in}}\,k_h\,k_w weights plus 11 bias, and each of the Hout Wout CoutH_{\text{out}}\,W_{\text{out}}\,C_{\text{out}} output entries runs Cin kh kwC_{\text{in}}\,k_h\,k_w multiply-adds:

Parameters=Cout(Cin kh kw+1),Multiply-Adds=Hout Wout Cout Cin kh kw.\text{Parameters} = C_{\text{out}}\bigl(C_{\text{in}}\,k_h\,k_w + 1\bigr), \qquad \text{Multiply-Adds} = H_{\text{out}}\,W_{\text{out}}\,C_{\text{out}}\,C_{\text{in}}\,k_h\,k_w.

Notice that the parameter count does not depend on HH or WW at all. To appreciate why that matters, let’s compare a convolutional layer with a simple general-purpose fully connected layer. A fully connected layer flattens all input values into one long vector x∈Rdinx \in \mathbb{R}^{d_{\text{in}}} and computes y=Wx+by = W x + b with a full matrix W∈Rdout×dinW \in \mathbb{R}^{d_{\text{out}} \times d_{\text{in}}}, giving every output entry its own separate weight for every single input pixel.

Suppose we want to map a tiny 3×64×643 \times 64 \times 64 color image (din=12,288d_{\text{in}} = 12{,}288 numbers) to 3232 output channels of size 64×6464 \times 64 (dout=131,072d_{\text{out}} = 131{,}072 numbers):

Layer typeWeight shapeParameters
Fully connected (nn.Linear)131,072×12,288131{,}072 \times 12{,}2881,610,743,8081{,}610{,}743{,}808 (incl. 131,072131{,}072 biases)
3×33 \times 3 Conv (nn.Conv2d)32×3×3×332 \times 3 \times 3 \times 3896896 (incl. 3232 biases)

A fully connected layer needs 1.611.61 billion parameters for that single step and discards 2D pixel neighborhoods altogether. A convolutional layer needs 896896 parameters because it bakes in two assumptions about images:

  1. Features are local (nearby pixels belong together) and
  2. Features are shift-invariant in appearance (a vertical edge in the top-left corner can be detected with the same weights as a vertical edge in the bottom-right corner).

Mixing Channels with a 1×11\times 1 Convolution

Look back at the three-sum formula for a convolutional layer:

Y[m,i,j]=bm+∑c=0Cin−1∑u=0kh−1∑v=0kw−1Xpad[c, s i+u, s j+v] W[m,c,u,v].Y[m, i, j] = b_m + \sum_{c=0}^{C_{\text{in}} - 1} \sum_{u=0}^{k_h - 1} \sum_{v=0}^{k_w - 1} X_{\text{pad}}[c,\, s\,i + u,\, s\,j + v]\, W[m, c, u, v].

A filter of shape Cin×kh×kwC_{\text{in}} \times k_h \times k_w spans two kinds of axes: its 2D footprint kh×kwk_h \times k_w across neighboring rows and columns of the image, and its depth CinC_{\text{in}} across channels. What happens if we set the kernel height and width to kh=1k_h = 1 and kw=1k_w = 1 (with s=1,p=0s = 1, p = 0), so the filter no longer looks at any neighboring pixels at all—only at the single pixel (i,j)(i, j)? Both inner sums over uu and vv reduce to the single index u=0,v=0u = 0, v = 0:

Y[m,i,j]=bm+∑c=0Cin−1W[m,c,0,0] X[c,i,j].Y[m, i, j] = b_m + \sum_{c=0}^{C_{\text{in}} - 1} W[m, c, 0, 0]\, X[c, i, j].

Think of a concrete example on a 33-channel RGB image (Cin=3C_{\text{in}} = 3) with Cout=1C_{\text{out}} = 1 filter having weights [0.30,0.59,0.11][0.30, 0.59, 0.11] (the ratio for red, green, and blue that our eye uses to perceive brightness) and b0=0b_0 = 0: at every pixel (i,j)(i, j), it computes 0.30 Ri,j+0.59 Gi,j+0.11 Bi,j0.30\,R_{i,j} + 0.59\,G_{i,j} + 0.11\,B_{i,j}, converting the 3-channel color image into a 1-channel grayscale image as the human eye would see it! More generally, if you stack the CinC_{\text{in}} channel values sitting at pixel (i,j)(i, j) into a column vector xi,j∈RCinx_{i,j} \in \mathbb{R}^{C_{\text{in}}}, a 1×11 \times 1 convolution just runs the tiny fully connected layer Wxi,j+bW x_{i,j} + b independently at every pixel using the same Cout×CinC_{\text{out}} \times C_{\text{in}} weight matrix WW. Even though it never mixes neighboring pixels, it lets a network blend information across channels and cheaply expand or compress the channel count Cin→CoutC_{\text{in}} \to C_{\text{out}} (used, for example, for squeezing 256256 channels down to 6464 before running an expensive 3×33 \times 3 layer in Deep Residual Networks, or ResNets).

Building Deep Convolutional Networks

Why Do We Need Activation Functions?

Cross-correlation is a linear operation in XX. Just as multiplying a vector by two matrices W1W_1 and W2W_2 in a row collapses into multiplying by a single matrix (W2(W1x)=(W2W1)xW_2(W_1 x) = (W_2 W_1)x), running one linear convolution directly on the output of another collapses into a single linear filter: two 3×33 \times 3 convolutions in series can always be rewritten as one 5×55 \times 5 convolution. Without something nonlinear between layers, stacking 50 convolutional layers could not express anything more than a single linear filter.

To prevent layers from collapsing together, we pass every entry of a layer’s output through a simple elementwise nonlinear function, called an activation function, before the next layer reads it. The standard choice in CNNs is the rectified linear unit (ReLU⁡\operatorname{ReLU}):

ReLU⁡(z)=max⁡(0,z),\operatorname{ReLU}(z) = \max(0, z),

which leaves positive numbers unchanged and sets negative numbers to zero. Writing Aℓ−1A_{\ell - 1} for the previous layer’s output (with A0=XA_0 = X), layer ℓ\ell computes

Aℓ=ReLU⁡(Wℓ⋆Aℓ−1+bℓ).A_\ell = \operatorname{ReLU}(W_\ell \star A_{\ell - 1} + b_\ell).

The bias bmb_m and ReLU⁡\operatorname{ReLU} work together as a learned gate: a filter’s response at (i,j)(i, j) survives past ReLU⁡\operatorname{ReLU} only when its dot product exceeds −bm-b_m. Early layers detect simple oriented edges and zero out weak matches, letting deeper layers combine those clean, thresholded edge maps into corners, contours, and whole objects.

Equivariance, Invariance, and Pooling

We care about two different ways a CNN’s output can respond when an object or feature shifts in the frame:

  • Translation equivariance means that shifting the input image by (Δi,Δj)(\Delta i, \Delta j) shifts the output map by the same offset. Because a stride-11 convolution applies the same weights at every coordinate, moving an object right by 88 pixels simply moves its response in YY right by 88 pixels (everywhere inside the interior—things can differ slightly right at the image edges if zero-padding starts entering the window or part of the object slides out of frame), preserving where the object is in the image.
  • Translation invariance means that shifting the input leaves the final output unchanged. You want invariance when classifying the whole image (“cat” vs. “dog”), where moving the cat or dog in the input image does not change the classification of whether a cat or dog is present.

Notice that a convolutional layer by itself gives us equivariance, not invariance. A CNN earns translation invariance gradually across the network by combining repeated downsampling (pooling or strided convolutions, which coarsen the spatial grid so small shifts fall into the same cell) with a final spatial collapse—either flattening a tiny remaining grid into linear layers or averaging each channel across all pixels—so the final class scores no longer depend strongly on where the object sat in the frame.

At the same time, classification is not the only vision task. In dense prediction tasks—such as semantic segmentation (assigning a category label to every single pixel, e.g., road vs. sidewalk vs. car), object detection (predicting bounding-box coordinates for every object), or depth estimation—throwing away spatial position would ruin the answer. If a pedestrian moves 2020 pixels to the right in the camera frame, their segmentation mask and bounding box must move 2020 pixels to the right with them. Those models keep the equivariant convolutional feature maps intact (often upsampling them back to full image resolution) instead of collapsing them into a single vector.

As we go deeper into a network, architectures typically shrink (H,W)(H, W) while increasing the number of channels CC, reducing memory cost and letting later filters span larger portions of the scene. Besides using a strided convolution (s=2s = 2, which learns downsampling weights), CNNs also halve (H,W)(H, W) using pooling, a fixed, parameter-free operation over each feature map that summarizes local blocks—discarding fine spatial detail in exchange for a smaller grid and tolerance to small shifts. Two types of pooling are common (and quite intuitive):

  • Max pooling (2×22 \times 2, stride 22) replaces each 2×22 \times 2 block of entries with its largest value, Y[c,i,j]=max⁡u,v∈{0,1}X[c,2i+u,2j+v]Y[c, i, j] = \max_{u, v \in \{0, 1\}} X[c, 2i + u, 2j + v]. If a strong feature shifts by a single pixel inside that 2×22 \times 2 block, the block’s maximum barely changes, giving small local shift tolerance at zero parameter cost.
  • Average pooling replaces each block with the mean of its values instead.

The Receptive Field

Suppose a network is looking at a 224×224224 \times 224 photo of a golden retriever, and every convolutional layer uses tiny 3×33 \times 3 filters. A single 3×33 \times 3 patch covers only a speck of fur—it has no way of telling whether it is looking at a dog, a carpet, or a sweater. To recognize an ear, a face, or an entire animal, deeper neurons need to see a much wider slice of the original image.

The region of the original input image that can influence a single entry in layer ℓ\ell is called that layer’s receptive field (rℓ×rℓr_\ell \times r_\ell pixels). Why does tracking its size matter? Suppose the final convolutional layer has a receptive field of only 30×3030 \times 30 pixels on a 224×224224 \times 224 image. Then the output cell sitting over a dog’s head depends strictly on its own 30×3030 \times 30 patch and never sees the tail, while the cell sitting on a dark rectangle never sees the surrounding street to tell whether it is a car window or a billboard.

You might wonder whether a layer placed after the convolutions can simply compare separate 30×3030 \times 30 blocks with one another. In dense prediction tasks like segmentation or detection, each pixel or bounding box is predicted directly from the feature vector at that location, so no downstream layer combines distant blocks. In classifiers that average each channel across all spatial positions before a final linear layer, the output only adds up local evidence like a bag of 30×3030 \times 30 patches—it cannot check how distant patches are arranged relative to each other. You could flatten the whole map into a fully connected layer so a single neuron reads every 30×3030 \times 30 block at once, but that sacrifices weight sharing and forces the network to re-learn every spatial relationship separately at every pair of coordinates. Instead, you want the convolutional receptive field itself to grow large enough across depth to cover the objects—and relevant scene context—you are trying to understand.

Even with tiny 3×33 \times 3 kernels everywhere, stacking layers grows the receptive field automatically. Trace three 3×33 \times 3 layers with stride s=1s = 1 along one row:

  • In layer 11, each output reads 33 adjacent input pixels (r1=3r_1 = 3).
  • In layer 22, each output reads 33 adjacent entries of layer 11. The leftmost of those entries reaches one pixel further left in XX and the rightmost reaches one pixel further right, so one layer-22 entry now sees 55 input pixels (r2=5r_2 = 5).
  • In layer 33, reading 33 entries of layer 22 adds one more pixel on each side, reaching 77 input pixels (r3=7r_3 = 7).

You can see this growth directly below. Hover or click any output cell to trace back every input pixel that feeds into it:

Receptive Field Playground
Stack

Notice an important practical consequence right away. To get a 7×77 \times 7 view of the image, you could use one big 7×77 \times 7 layer, or you could stack three 3×33 \times 3 layers. Suppose each layer has CC input and CC output channels (ignoring biases):

  • One 7×77 \times 7 layer has C×C×7×7=49 C2C \times C \times 7 \times 7 = 49\,C^2 weights and applies ReLU⁡\operatorname{ReLU} once.
  • Three stacked 3×33 \times 3 layers reach the exact same 7×77 \times 7 receptive field with only 3×(C×C×3×3)=27 C23 \times (C \times C \times 3 \times 3) = 27\,C^2 weights (45% fewer parameters) and three ReLU⁡\operatorname{ReLU} nonlinearities instead of one.

That trade-off—same field of view, fewer weights, and richer nonlinear features—was popularized in 2014 by Karen Simonyan and Andrew Zisserman from Oxford’s Visual Geometry Group with their VGG networks (16- and 19-layer image classifiers that broke records on ImageNet by replacing large 5×55 \times 5 and 7×77 \times 7 filters with uniform stacks of 3×33 \times 3 convolutions), a design rule almost every CNN has followed since.

Still, if every 3×33 \times 3 layer only widens the view by 22 pixels (3→5→7→9…3 \to 5 \to 7 \to 9 \dots), it would take over 100100 layers to span a 224×224224 \times 224 photo. That is the other big reason CNNs downsample by 2×2\times (using either 2×22 \times 2 pooling or stride-22 convolutions), since shrinking the grid makes every subsequent 3×33 \times 3 filter reach twice as far across the original image.

Click the strided 3×3 (s = 1, 2, 1) preset in the playground above to watch why:

  • Layer 11 (3×3,s=13 \times 3, s = 1) covers 33 input pixels, and neighboring cells in Layer 11 sit 11 input pixel apart.
  • Layer 22 (3×3,s=23 \times 3, s = 2) still reads 33 adjacent cells of Layer 11 (covering 55 input pixels), but because it steps by s=2s = 2, neighboring cells in Layer 22‘s output now sit 22 input pixels apart instead of 11.
  • Layer 33 (3×3,s=13 \times 3, s = 1) reads 33 adjacent cells of Layer 22: the middle cell covers 55 input pixels, the left cell reaches 22 pixels further left, and the right cell reaches 22 pixels further right—spanning 5+2+2=95 + 2 + 2 = 9 input pixels instead of 77.

Each time a network halves (H,W)(H, W) again, the pixel spacing between adjacent cells doubles (1→2→4→8→161 \to 2 \to 4 \to 8 \to 16 pixels), so a 3×33 \times 3 filter after four 2×2\times downsamplings steps across 1616 original pixels at a time. With just four or five downsampling stages, a 15- or 18-layer CNN easily sees across an entire 224×224224 \times 224 photograph.

Putting It Together with LeNet-5

Up to now we have looked at individual layers and components in isolation including convolutions, ReLU⁡\operatorname{ReLU}, and pooling. How do we string them together into a complete network that does a useful task? For example, taking raw pixels and outputting a class prediction?

The blueprint was laid down by Yann LeCun and colleagues in 1998 with LeNet-5, built to read handwritten 32×3232 \times 32 grayscale digits (00 through 99) on bank checks. Below is LeNet-5’s architecture (updated to use ReLU⁡\operatorname{ReLU}, max pooling, and a linear output layer in place of the 1998 paper’s tanh⁡\tanh activations, average pooling, and template-matching head, as standard PyTorch implementations do today):

LeNet-5 architecture: a 1 by 32 by 32 digit passes through Conv 1, Pool 1, Conv 2, and Pool 2 before flattening to 400 values and passing through FC 1, FC 2, and 10 class logits.
StageLayerOutput shape (C×H×W)(C \times H \times W)What happens
InputGrayscale digit image1×32×321 \times 32 \times 32Raw pixel intensities
Conv 15×55 \times 5 conv, 66 filters, s=1,p=0s = 1, p = 0 + ReLU⁡\operatorname{ReLU}6×28×286 \times 28 \times 28Detects 66 local stroke / edge patterns
Pool 12×22 \times 2 pool, s=2s = 26×14×146 \times 14 \times 14Halves grid; adds small local shift tolerance
Conv 25×55 \times 5 conv, 1616 filters, s=1,p=0s = 1, p = 0 + ReLU⁡\operatorname{ReLU}16×10×1016 \times 10 \times 10Combines edges into loops, corners, junctions
Pool 22×22 \times 2 pool, s=2s = 216×5×516 \times 5 \times 5Halves grid again; 400400 total numbers left
FlattenReshape 16×5×516 \times 5 \times 5 into a vector400400Drops the 2D grid for classification
FC 1nn.Linear(400, 120) + ReLU⁡\operatorname{ReLU}120120Mixes features across the whole digit
FC 2nn.Linear(120, 84) + ReLU⁡\operatorname{ReLU}8484Compact digit representation
Headnn.Linear(84, 10)1010One raw score (logit) zkz_k per digit 00–99

Notice the two halves of the architecture. The convolutional body progressively shrinks the spatial grid (32×32→5×532 \times 32 \to 5 \times 5) while widening channels (1→6→161 \to 6 \to 16) and expanding each neuron’s receptive field until a single cell in Pool 2 spans almost the entire handwritten digit. Then the classifier head collapses the remaining spatial map into a 1D vector and maps it to KK unnormalized class scores z=(z0,…,zK−1)z = (z_0, \ldots, z_{K-1}) (here K=10K = 10).

To turn the KK raw scores zkz_k into class probabilities pk∈(0,1)p_k \in (0, 1) that sum to 11, we apply softmax:

pk=ezk∑j=0K−1ezj.p_k = \frac{e^{z_k}}{\sum_{j=0}^{K-1} e^{z_j}}.

If the true label of the image is class yy, the standard classification loss is cross-entropy:

L=−log⁡py.\mathcal{L} = -\log p_y.

When the network assigns probability py≈1p_y \approx 1 to the right digit, −log⁡py≈0-\log p_y \approx 0; when it assigns pyp_y close to 00, the penalty grows steeply toward +∞+\infty, pushing gradient descent to raise the true class’s score zyz_y and lower the others.

You can step through a LeNet-5 forward pass below in the interactive snippet. Pick a digit and drag the horizontal shift slider Δx\Delta x to watch the response of the filters and classification:

LeNet-5 Interactive Playground
Digit

Input

Conv 1 + ReLU

Pool 1

Pool 2 (4 of 16)

Softmax Output

When we train multi-layer CNNs end to end with backpropagation, we often discover that the very first convolutional layer - which looks at raw RGB pixels - learns weights that are remarkably consistent across different datasets and architectures; we typically get a mix of oriented wave-like edge and bar detectors alongside smooth color-opponent blobs (sensitive to transitions like red vs. green or blue vs. yellow). That is close to the classical edge and smoothing kernels from Convolution and Image Filtering, though richer in color and orientation. As you progress deeper into the network, introspecting abstract multi-channel feature maps becomes more difficult, though there are techniques to do so in the literature.

Training a CNN

When backpropagation reaches a convolutional layer, the layers after it hand back the upstream gradient map G[i,j]:=∂L∂Y[i,j]G[i, j] := \frac{\partial \mathcal{L}}{\partial Y[i, j]}, measuring how the scalar loss L\mathcal{L} changes with each entry of our layer’s output YY. From GG, the layer computes three things: ∂L∂b\frac{\partial \mathcal{L}}{\partial b} and ∂L∂W\frac{\partial \mathcal{L}}{\partial W} to update its own parameters, and ∂L∂X\frac{\partial \mathcal{L}}{\partial X} to pass backward to the layer before it.

Recall the expression for the single-channel, unit-stride (s=1,p=0s = 1, p = 0) forward pass:

Y[i,j]=b+∑u=0kh−1∑v=0kw−1X[i+u, j+v] W[u,v].Y[i, j] = b + \sum_{u=0}^{k_h - 1} \sum_{v=0}^{k_w - 1} X[i + u,\, j + v]\, W[u, v].

Because the same filter slides across the entire image, every parameter influences many output entries, and every input pixel feeds into several overlapping windows. Whenever one quantity contributes to multiple outputs Y[i,j]Y[i, j], the chain rule says its total derivative is simply the sum of its effects through each of those outputs. Walking through bb, WW, and XX one at a time turns out to be surprisingly clean, so let’s look through them one by one.

Bias Gradient

The scalar bias bb is added directly to every output entry Y[i,j]Y[i, j] with weight 11. Nudging bb up by a tiny amount raises every single pixel of YY by that same amount, so its total effect on the loss is just the sum of all entries in the upstream gradient map GG:

∂L∂b=∑i,jG[i,j].\frac{\partial \mathcal{L}}{\partial b} = \sum_{i, j} G[i, j].

Filter Weight Gradient

Pick one specific weight inside the kernel, W[u,v]W[u, v]. Every time the sliding window lands at position (i,j)(i, j) to produce Y[i,j]Y[i, j], that weight multiplies input pixel X[i+u, j+v]X[i + u,\, j + v], so its local derivative on Y[i,j]Y[i, j] is X[i+u, j+v]X[i + u,\, j + v]. Multiplying by the upstream sensitivity G[i,j]G[i, j] and summing across every window position (i,j)(i, j) gives

∂L∂W[u,v]=∑i,jX[i+u, j+v] G[i,j]=(X⋆G)[u,v].\frac{\partial \mathcal{L}}{\partial W[u, v]} = \sum_{i, j} X[i + u,\, j + v]\, G[i, j] = (X \star G)[u, v].

Look at the right-hand side - to find the gradient for the filter weights, we simply slide the upstream gradient map GG across the input image XX via 2D cross-correlation.

Input Gradient

Now stand on a single input pixel X[r,c]X[r, c] (at row rr, column cc) and ask which output entries Y[i,j]Y[i, j] read it during the forward pass:

  • When the window started right at (r,c)(r, c) to compute Y[r,c]Y[r, c], pixel X[r,c]X[r, c] sat under the top-left weight W[0,0]W[0, 0], contributing G[r,c] W[0,0]G[r, c]\,W[0, 0] to the gradient.
  • When the window started one column to the left at (r,c−1)(r, c - 1) to compute Y[r,c−1]Y[r, c - 1], pixel X[r,c]X[r, c] sat under W[0,1]W[0, 1], contributing G[r,c−1] W[0,1]G[r, c - 1]\,W[0, 1].
  • In general, whenever the window started at (r−u, c−v)(r - u,\, c - v), pixel X[r,c]X[r, c] sat at offset (u,v)(u, v) inside the kernel and multiplied W[u,v]W[u, v].

Summing across all (u,v)(u, v) in the kernel (and treating any out-of-bounds index of GG near the image border as 00, which is equivalent to zero-padding GG by kh−1k_h - 1 rows and kw−1k_w - 1 columns) gives

∂L∂X[r,c]=∑u=0kh−1∑v=0kw−1G[r−u, c−v] W[u,v]=(G∗W)[r,c].\frac{\partial \mathcal{L}}{\partial X[r, c]} = \sum_{u=0}^{k_h - 1} \sum_{v=0}^{k_w - 1} G[r - u,\, c - v]\, W[u, v] = (G * W)[r, c].

Notice the minus signs r−ur - u and c−vc - v: true mathematical convolution—sliding WW after flipping it 180∘180^\circ—reappears automatically on the backward pass! That mirrors ordinary linear algebra: any linear layer y=Mxy = M x sends gradients backward through its matrix transpose (M⊤gM^\top g), and transposing a sliding-window operator reverses the direction of the window.

Where Plain CNNs Hit a Wall

Armed with 3×33 \times 3 convolutions, ReLU⁡\operatorname{ReLU} activations, pooling, and backpropagation, plain networks of 55 to 1919 layers—from LeNet-5 up through VGG—learn remarkably effective visual hierarchies. Real-world scenes, however, are messy: lighting shifts, clutter, reflections, partial occlusions, and fine-grained categories reward stacking even deeper hierarchies of features.

Yet if you naively stack 3030 or 5656 plain convolutional layers in a row - even after carefully calibrating random weight initialization and normalizing signals between layers (BatchNorm, covered in our upcoming ResNet note) so gradients neither vanish nor explode - something surprising happens: even on the training images themselves, the 56-layer network converges to higher error than a 20-layer network. Why naively adding depth hurts optimization, and how signal stabilization and a simple additive skip connection fix it, is the subject of our upcoming note on Deep Residual Networks (ResNets).

References