Convolutional Neural Networks
Introduction
In Convolution and Image Filtering, we saw how sliding a small weight matrix (a kernel or filter) across a 2D grayscale image extracts local spatial structure. At each pixel position , 2D cross-correlation multiplies the aligned image patch by and sums:
(Signal processing reserves the word convolution for sliding a -flipped kernel , whereas deep learning frameworks compute cross-correlation above and call it convolution because the weights in are learned anyway.)
Instead of hand-designing one 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 and width , and we slide a kernel across it one pixel at a time. Without anything outside the border, the kernel’s top-left corner can start at row , giving valid positions vertically (and horizontally). Every pass of the kernel therefore shaves pixels off of both height and width (two pixels when ) - gradually shrinking away the image and underweighing pixels near the edges (a corner pixel touches only one window, whereas an interior pixel touches ).
To prevent this shrinkage, we can surround the input border with rows and columns of zeros, called zero-padding, which expands the effective input size to . 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 is the step size (in pixels) between adjacent window positions, so output entry anchors its window at 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:
- With stride 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 shrinks the output directly.
- Compressing the grid at each stage cuts memory and compute cost, since both scale directly with the spatial size of the layer’s output.
- At , adjacent windows overlap heavily—two neighboring 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 . Placing the first -pixel window at index uses up pixels and leaves pixels of room to travel. Each step of stride consumes of those remaining pixels, so we can take steps after the initial placement (rounding down with because a leftover remainder smaller than cannot fit another full window). Counting the initial window at index adds :
Two settings appear constantly in practice:
- Same-size filtering (, for odd ): with and , , preserving spatial resolution.
- Strided halving (): for even , , filtering and downsampling by in one pass.
From Grayscale to Multiple Channels
Everything so far has treated an image as a single grid of brightness values (grayscale). A color camera, however, records three separate 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 array .
Why stop at three channels? As we saw in Convolution and Image Filtering, a single 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 different filters in parallel. Each filter produces its own response grid (called an output channel or feature map), and stacking all grids together produces a array . The next convolutional layer then reads in the exact same way, seeing input channels.
How does one filter process an input that has channels? A common misconception is that it slides a flat matrix over each channel separately. Instead, a single filter is a 3D block of weights of shape that reaches across all input channels simultaneously. At position , it multiplies all aligned values, sums them into a single number, and adds a learnable scalar offset (called a bias, which shifts the filter’s baseline output up or down just like the intercept in ). That single number becomes entry of output channel .
Grouping all filters together packs their weights into a four-indexed array with biases . Writing for the zero-padded input, the complete forward pass of a convolutional layer is
for each output channel . 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 ). Each filter stores weights plus
bias, and each of the output entries runs
multiply-adds:
Notice that the parameter count does not depend on or 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 and computes with a full matrix , giving every output entry its own separate weight for every single input pixel.
Suppose we want to map a tiny color image ( numbers) to output channels of size ( numbers):
| Layer type | Weight shape | Parameters |
|---|---|---|
Fully connected (nn.Linear) | (incl. biases) | |
Conv (nn.Conv2d) | (incl. biases) |
A fully connected layer needs billion parameters for that single step and discards 2D pixel neighborhoods altogether. A convolutional layer needs parameters because it bakes in two assumptions about images:
- Features are local (nearby pixels belong together) and
- 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 Convolution
Look back at the three-sum formula for a convolutional layer:
A filter of shape spans two kinds of axes: its 2D footprint across neighboring rows and columns of the image, and its depth across channels. What happens if we set the kernel height and width to and (with ), so the filter no longer looks at any neighboring pixels at all—only at the single pixel ? Both inner sums over and reduce to the single index :
Think of a concrete example on a -channel RGB image () with filter having weights (the ratio for red, green, and blue that our eye uses to perceive brightness) and : at every pixel , it computes , 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 channel values sitting at pixel into a column vector , a convolution just runs the tiny fully connected layer independently at every pixel using the same weight matrix . Even though it never mixes neighboring pixels, it lets a network blend information across channels and cheaply expand or compress the channel count (used, for example, for squeezing channels down to before running an expensive layer in Deep Residual Networks, or ResNets).
Building Deep Convolutional Networks
Why Do We Need Activation Functions?
Cross-correlation is a linear operation in . Just as multiplying a vector by two matrices and in a row collapses into multiplying by a single matrix (), running one linear convolution directly on the output of another collapses into a single linear filter: two convolutions in series can always be rewritten as one 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 ():
which leaves positive numbers unchanged and sets negative numbers to zero. Writing for the previous layer’s output (with ), layer computes
The bias and work together as a learned gate: a filter’s response at survives past only when its dot product exceeds . 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 shifts the output map by the same offset. Because a stride- convolution applies the same weights at every coordinate, moving an object right by pixels simply moves its response in right by 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 pixels to the right in the camera frame, their segmentation mask and bounding box must move 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 while increasing the number of channels , reducing memory cost and letting later filters span larger portions of the scene. Besides using a strided convolution (, which learns downsampling weights), CNNs also halve 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 (, stride ) replaces each block of entries with its largest value, . If a strong feature shifts by a single pixel inside that 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 photo of a golden retriever, and every convolutional layer uses tiny filters. A single 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 is called that layer’s receptive field ( pixels). Why does tracking its size matter? Suppose the final convolutional layer has a receptive field of only pixels on a image. Then the output cell sitting over a dog’s head depends strictly on its own 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 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 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 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 kernels everywhere, stacking layers grows the receptive field automatically. Trace three layers with stride along one row:
- In layer , each output reads adjacent input pixels ().
- In layer , each output reads adjacent entries of layer . The leftmost of those entries reaches one pixel further left in and the rightmost reaches one pixel further right, so one layer- entry now sees input pixels ().
- In layer , reading entries of layer adds one more pixel on each side, reaching input pixels ().
You can see this growth directly below. Hover or click any output cell to trace back every input pixel that feeds into it:
Notice an important practical consequence right away. To get a view of the image, you could use one big layer, or you could stack three layers. Suppose each layer has input and output channels (ignoring biases):
- One layer has weights and applies once.
- Three stacked layers reach the exact same receptive field with only weights (45% fewer parameters) and three 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 and filters with uniform stacks of convolutions), a design rule almost every CNN has followed since.
Still, if every layer only widens the view by pixels (), it would take over layers to span a photo. That is the other big reason CNNs downsample by (using either pooling or stride- convolutions), since shrinking the grid makes every subsequent 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 () covers input pixels, and neighboring cells in Layer sit input pixel apart.
- Layer () still reads adjacent cells of Layer (covering input pixels), but because it steps by , neighboring cells in Layer ‘s output now sit input pixels apart instead of .
- Layer () reads adjacent cells of Layer : the middle cell covers input pixels, the left cell reaches pixels further left, and the right cell reaches pixels further right—spanning input pixels instead of .
Each time a network halves again, the pixel spacing between adjacent cells doubles ( pixels), so a filter after four downsamplings steps across original pixels at a time. With just four or five downsampling stages, a 15- or 18-layer CNN easily sees across an entire photograph.
Putting It Together with LeNet-5
Up to now we have looked at individual layers and components in isolation including convolutions, , 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 grayscale digits ( through ) on bank checks. Below is LeNet-5’s architecture (updated to use , max pooling, and a linear output layer in place of the 1998 paper’s activations, average pooling, and template-matching head, as standard PyTorch implementations do today):
| Stage | Layer | Output shape | What happens |
|---|---|---|---|
| Input | Grayscale digit image | Raw pixel intensities | |
| Conv 1 | conv, filters, + | Detects local stroke / edge patterns | |
| Pool 1 | pool, | Halves grid; adds small local shift tolerance | |
| Conv 2 | conv, filters, + | Combines edges into loops, corners, junctions | |
| Pool 2 | pool, | Halves grid again; total numbers left | |
| Flatten | Reshape into a vector | Drops the 2D grid for classification | |
| FC 1 | nn.Linear(400, 120) + | Mixes features across the whole digit | |
| FC 2 | nn.Linear(120, 84) + | Compact digit representation | |
| Head | nn.Linear(84, 10) | One raw score (logit) per digit – |
Notice the two halves of the architecture. The convolutional body progressively shrinks the spatial grid () while widening channels () 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 unnormalized class scores (here ).
To turn the raw scores into class probabilities that sum to , we apply softmax:
If the true label of the image is class , the standard classification loss is cross-entropy:
When the network assigns probability to the right digit, ; when it assigns close to , the penalty grows steeply toward , pushing gradient descent to raise the true class’s score 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 to watch the response of the filters and classification:
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 , measuring how the scalar loss changes with each entry of our layer’s output . From , the layer computes three things: and to update its own parameters, and to pass backward to the layer before it.
Recall the expression for the single-channel, unit-stride () forward pass:
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 , the chain rule says its total derivative is simply the sum of its effects through each of those outputs. Walking through , , and one at a time turns out to be surprisingly clean, so let’s look through them one by one.
Bias Gradient
The scalar bias is added directly to every output entry with weight . Nudging up by a tiny amount raises every single pixel of by that same amount, so its total effect on the loss is just the sum of all entries in the upstream gradient map :
Filter Weight Gradient
Pick one specific weight inside the kernel, . Every time the sliding window lands at position to produce , that weight multiplies input pixel , so its local derivative on is . Multiplying by the upstream sensitivity and summing across every window position gives
Look at the right-hand side - to find the gradient for the filter weights, we simply slide the upstream gradient map across the input image via 2D cross-correlation.
Input Gradient
Now stand on a single input pixel (at row , column ) and ask which output entries read it during the forward pass:
- When the window started right at to compute , pixel sat under the top-left weight , contributing to the gradient.
- When the window started one column to the left at to compute , pixel sat under , contributing .
- In general, whenever the window started at , pixel sat at offset inside the kernel and multiplied .
Summing across all in the kernel (and treating any out-of-bounds index of near the image border as , which is equivalent to zero-padding by rows and columns) gives
Notice the minus signs and : true mathematical convolution—sliding after flipping it —reappears automatically on the backward pass! That mirrors ordinary linear algebra: any linear layer sends gradients backward through its matrix transpose (), and transposing a sliding-window operator reverses the direction of the window.
Where Plain CNNs Hit a Wall
Armed with convolutions, activations, pooling, and backpropagation, plain networks of to 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 or 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
- LeCun, Bottou, Bengio, & Haffner, Gradient-Based Learning Applied to Document Recognition (1998). Introduces LeNet-5 and end-to-end backpropagation through convolutional feature extractors.
- Zeiler & Fergus, Visualizing and Understanding Convolutional Networks (ECCV 2014). Introduces feature visualization showing how early Gabor/color filters build into textures, parts, and object detectors across depth.
- Simonyan & Zisserman, Very Deep Convolutional Networks for Large-Scale Image Recognition (2014). Establishes stacked convolutions as the canonical building block.
- Dumoulin & Visin, A Guide to Convolution Arithmetic for Deep Learning (2016). Detailed derivations of padding, stride, and convolution geometry.