Convolutional Neural Networks
After this lesson, you will be able to:
- See how small sliding filters detect patterns like edges, textures, and shapes in images
- Understand how pooling shrinks the image while keeping the most important information
- Follow the CNN's learning hierarchy: edges to textures to parts to whole objects
- Calculate output spatial dimensions using the stride, padding, and kernel size formula, and explain why skip connections in ResNet solved the degradation problem
Before you start
CNNs are one of the most visual and intuitive architectures in all of deep learning. If you can understand how a filter slides across an image, you understand the core idea. Everything else is just stacking that idea in clever ways. Let yourself enjoy this one — it is genuinely cool to see how a network learns to "see."
#End-to-End CNN Pipeline
#Step 1: Input Image (28x28)
A grayscale image enters the network as a 28x28 grid of pixel values, each normalized to [0, 1]. For RGB images, there are three such grids (channels). The spatial structure of the image, which pixels are neighbors — is the key information that CNNs exploit.
#Step 2: Convolution (Filter Slides)
Small learned filters (e.g., 3x3) slide across the image. At each position, the filter computes a dot product with the local pixel patch. A vertical edge filter produces strong responses where vertical edges exist. Multiple filters (32, 64, or more) each detect different patterns simultaneously.
#Step 3: Feature Map Produced
#Step 4: ReLU Activation
ReLU is applied element-wise to every value in every feature map: negative values become zero, positive values pass through. This introduces nonlinearity — without it, stacking convolutions would still be a single linear operation.
#Step 5: Max Pooling (Downsample)
A 2x2 max pooling window slides across each feature map, keeping only the maximum value in each window. This halves the spatial dimensions (28x28 becomes 14x14), making the representation more compact and slightly translation-invariant.
#Step 6: More Conv Layers
Additional convolution + ReLU + pooling blocks stack on top. Each layer detects higher-level patterns using the previous layer's features as input. Layer 2 detects textures (combinations of edges). Layer 3 detects object parts (combinations of textures). Spatial dimensions shrink while channel count grows.
#Step 7: Flatten
After the final convolutional block, the 3D feature volume (e.g., 7x7x128) is flattened into a 1D vector (6,272 values). This converts the spatial representation into a format compatible with fully-connected layers.
#Step 8: Fully Connected
One or more dense layers process the flattened features. These layers combine spatial features from across the entire image to make a holistic decision. Dropout is often applied here to prevent overfitting.
#Step 9: Softmax and Class Probabilities
The final layer outputs one score per class, and softmax converts these to probabilities. For MNIST: 10 probabilities, one per digit. The highest probability is the predicted class. The CNN has transformed raw pixels into a class prediction through learned hierarchical feature extraction.
#Why Regular Networks Fail on Images
Try it! Take any small image (even a 4x4 grid you draw on paper). Create a simple 3x3 filter where the middle column is [1,1,1] and the sides are [-1,-1,-1]. Slide it across your image — wherever there is a vertical edge, the output spikes. You just performed convolution by hand!
#The Convolution Operation
Strictly, this sum is a cross-correlation: a textbook convolution flips the kernel first. Deep learning libraries compute the unflipped sum and still call it convolution. Because the kernel is learned, the flip would only rename the weights.
#Step 1: Place the Filter
Take a small filter (e.g., 3x3) and place it on the top-left corner of the input image. The filter overlaps a 3x3 patch of pixels.
#Step 2: Compute the Dot Product
Multiply each filter value by the corresponding pixel value, then sum all 9 products. This gives one number — the output for this position. If the filter detects vertical edges, this number will be large where there is a vertical edge under the filter.
#Step 3: Slide the Filter
Move the filter one pixel to the right (stride = 1) and repeat the dot product. Continue sliding across the entire row, then move down one row and repeat. The filter visits every possible position.
#Step 4: Produce the Feature Map
#Step 5: Multiple Filters
One filter detects one pattern. A convolutional layer uses many filters (typically 32, 64, 128, or more) — each detecting a different pattern. Each filter produces its own feature map. The output of the layer is a stack of feature maps: one per filter. If you have 64 filters, the output is 64 feature maps.
#Step 6: Add Bias and Activation
After convolution, add a bias term (one per filter) and apply an activation function (usually ReLU). This is the same nonlinearity as in fully-connected layers — without it, stacking convolutional layers would still be linear.
#Convolution as a banded matrix
A convolution looks like a new operation, but it is a matrix product in which most entries are zero and the rest repeat. Take one dimension, stride 1 and no padding, with a kernel w of length k.
#Why convolution is translation equivariant
Equivariant means that shifting the input shifts the output by the same amount. This is the precise form of the idea that a pattern is found wherever it is.
#The backward pass of a convolution
Training needs the gradient of the loss with respect to the kernel and with respect to the input. Both turn out to be convolutions again. The chain rule and the matrix-gradient identities used here are derived in Vector & Matrix Calculus: Jacobian, Hessian & Backprop Rules, and the layer-to-layer recursion in Backpropagation.
Move the three kernel weights, the stride, the padding, the input values and the Forward/Backward toggle, and watch three things: the sliding window and the banded matrix product give the same numbers, the diagonals of the matrix stay constant because the kernel is shared, and in Backward mode the transpose acts as a correlation with the flipped kernel.
#Key Concepts
#Stride
The number of pixels the filter moves at each step. Stride 1 means move one pixel at a time (output nearly same size as input). Stride 2 means skip every other position (output half the size). Larger strides reduce spatial dimensions but lose fine detail.
#Padding
#Receptive Field
The region of the original input that influences a particular output value. A single 3x3 convolution has a 3x3 receptive field. Two stacked 3x3 convolutions have a 5x5 receptive field. Three have 7x7. Deep CNNs have receptive fields that eventually cover the entire image, allowing them to capture both local details and global structure.
With strides, the field grows faster the deeper the layer is. Write r_l for the receptive field after layer l, k_l for its kernel size and s_l for its stride:
The brackets round down: when the last window does not fit exactly, the leftover cells are dropped.
A 3x3 convolution layer with 64 filters applied to an RGB (3-channel) input has how many parameters?
Each filter has size 3x3x3 (height x width x input_channels) = 27 weights, plus 1 bias = 28 parameters per filter. With 64 filters: 64 * 28 = 1,792. This is dramatically fewer than the ~150 million a fully-connected layer would need. Weight sharing is the key — each filter is reused at every spatial position.
#Pooling: Dimensionality Reduction
#Max Pooling
Take the maximum value in each non-overlapping window (typically 2x2 with stride 2). This halves the spatial dimensions while keeping the strongest activations.
#Average Pooling
#Where the gradient goes in pooling
Pooling has no weights, but the gradient still has to pass through it on the way back.
#The Feature Hierarchy
Select different kernel presets (edge detection, blur, sharpen) and watch the filter slide across the 8x8 input grid. Observe how each kernel produces a different output feature map. Increase the stride to see how it reduces the output dimensions.
#Classic CNN Architectures
#LeNet-5 (1998) — The Pioneer
- 2 convolutional layers, 2 pooling layers, 3 fully-connected layers
- ~60,000 parameters
- Read handwritten digits at the post office
#AlexNet (2012) — The Revolution
- 5 convolutional layers, 3 fully-connected layers
- ~60 million parameters
- Used ReLU instead of tanh, GPU training, dropout
- Won ImageNet 2012 by a huge margin: 16.4% top-5 error vs. 26.2% for the runner-up
#VGGNet (2014) — Depth Matters
- 16 or 19 layers, all using tiny 3x3 filters
- Showed that stacking small filters is better than large filters (two 3x3 = one 5x5 receptive field, but fewer parameters and more nonlinearity)
- ~138 million parameters
#ResNet (2015) — The Skip Connection Revolution
- 50 to 152 layers with skip connections (shortcut paths that bypass layers)
- Solved the degradation problem: without skip connections, very deep networks train worse than shallow ones
- Skip connections allow gradients to flow directly to early layers
Why does the shortcut help gradients? Take blocks of the simpler form x_(l+1) = x_l + F_l(x_l), with no activation after the addition, which is the variant analysed in the follow-up paper on identity mappings. The chain rule used here is derived in Vector & Matrix Calculus: Jacobian, Hessian & Backprop Rules.
#1x1 Convolutions: The Channel Mixer
1x1 convolutions are used extensively in modern architectures:
- Bottleneck blocks in ResNet: reduce channels before the expensive 3x3 conv, then expand again
- Channel attention in SE-Net: learn which channels to emphasize
- Pointwise convolutions in MobileNet: mix channels after depthwise separable convolutions
#Try It Yourself
Tests: Verify vertical edge filter produces non-zero output where the edge is. Verify horizontal edge filter produces zeros on the vertical-edge image.
ImageNet Classification with Deep Convolutional Neural Networks
Alex Krizhevsky, Ilya Sutskever, Geoffrey Hinton (2012)
The AlexNet paper. Won ImageNet 2012 and launched the deep learning revolution in computer vision. Introduced ReLU, dropout, and GPU training to CNNs. Over 120,000 citations.
Deep Residual Learning for Image Recognition
Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun (2015)
Introduced ResNet with skip connections, enabling training of networks with 100+ layers. Won ImageNet 2015 with 3.57% top-5 error — superhuman performance. The skip connection became a fundamental building block of all modern architectures.
#Key Takeaways
- Convolution applies learned filters to detect local patterns. Small filters slide across the input, detecting edges, textures, and shapes through parameter sharing, which dramatically reduces the number of weights compared to fully-connected layers
- CNNs learn hierarchical features automatically. Early layers detect edges and colors, middle layers combine these into textures and parts, and deep layers recognize whole objects; this hierarchy emerges from training, not from manual design
- Pooling reduces spatial dimensions while preserving important features. Max pooling or average pooling compresses feature maps, making the representation more compact and translation-invariant
- Parameter sharing and local connectivity are the key insights. The same filter weights are used across the entire image, encoding the assumption that a useful pattern (like an edge) is equally useful regardless of where it appears
#Quick Check
What makes convolutional layers more efficient than fully-connected layers for image processing?