Convolutional Neural Networks (CNNs)
How a small sliding filter turns pixels into edges, textures and objects. Convolution, kernels, stride, padding, pooling, feature maps and receptive fields — with the output-size formula you will use constantly.
A 224×224 colour image has 224·224·3 = 150,528 numbers. A fully connected layer with just 1,000 units on top of it would need 150 million weights — and it would have to learn separately that a cat in the top-left corner is the same as a cat in the bottom-right. A convolutional neural network fixes both problems with one idea: slide a small filter across the image and reuse the same weights everywhere. A 3×3 filter on an RGB image has only 3·3·3 = 27 weights (+1 bias), no matter how large the image is. CNNs power image classification, detection, segmentation, medical imaging and, in 1D form, audio and time-series models[1].
The convolution operation
- y[i, j]
- output value at row i, column j of the Feature map
- Σₘ Σₙ
- sum over all kernel rows m and kernel columns n (e.g. m, n = 0, 1, 2 for a 3×3 kernel)
- x[i·s + m, j·s + n]
- the input pixel under kernel cell (m, n) when the kernel sits at output position (i, j)
- k[m, n]
- the learned kernel weight at row m, column n
- s
- the Stride: how many pixels the kernel jumps between output positions
- b
- bias: one learned number per filter, added after the sum
▸Worked example
Worked example: a 3×3 patch where the left two columns are dark (10) and the right column bright (80), and the Sobel-X kernel (−1 0 1 / −2 0 2 / −1 0 1). Row by row: (−10 + 0 + 80) + (−20 + 0 + 160) + (−10 + 0 + 80) = 70 + 140 + 70 = 280 — a strong response, because there's a dark-to-bright vertical edge. On a flat patch (all 10s), the same kernel gives exactly 0. Classic image processing hand-designs such kernels; a CNN learns its kernel values by Backpropagation.
Output size: stride and padding
▸Worked example
| Input n | k | p | s | Output | Comment |
|---|---|---|---|---|---|
| 16 | 3 | 0 | 1 | 14 | “valid”: shrinks by k − 1 |
| 16 | 3 | 1 | 1 | 16 | “same”: p = (k − 1)/2 keeps the size |
| 16 | 3 | 1 | 2 | 8 | Stride 2 halves the resolution |
| 224 | 7 | 3 | 2 | 112 | ResNet's first layer |
| 32 | 5 | 0 | 1 | 28 | LeNet-5's first layer |
Stride is how many pixels the filter jumps between positions; stride 2 skips every other position and downsamples the map. Padding adds a border (usually zeros) so that the filter can be centred on edge pixels and the output keeps its size. Dumoulin & Visin's guide has excellent animations of every combination[2].
Channels, filters and parameter count
Real inputs have channels (RGB = 3), and each layer outputs many channels. A filter always spans all input channels: its shape is k × k × C_in. A layer with C_out filters produces C_out feature maps stacked as the output channels. Parameters = (k·k·C_in + 1)·C_out. Example: a 3×3 conv from 64 to 128 channels has (9·64 + 1)·128 = 73,856 parameters — independent of image size. Compare that with millions for a dense layer.
Pooling
Pooling summarises small neighbourhoods without learned weights. Max pooling 2×2 with stride 2 keeps the largest value in each 2×2 block, halving height and width (¾ of the values are discarded) while keeping the strongest responses — giving a little tolerance to small shifts. Average pooling takes the mean. Global average pooling averages each whole feature map into a single number and is the standard way modern CNNs go from feature maps to a classifier. Many modern architectures replace pooling layers with stride-2 convolutions[1].
Receptive field and the feature hierarchy
- r_l
- Receptive field (in input pixels, per side) of one unit in layer l
- r_{l−1}
- receptive field of the previous layer
- k_l
- kernel (or pooling window) size of layer l
- s₁ · s₂ · … · s_{l−1}
- product of the strides of all earlier layers (the “jump” between neighbouring units)
- r₀
- start value: one input pixel sees itself
▸Worked example
Each unit in the first layer sees only a tiny patch, so it can only detect local things like edges and colour blobs. Deeper units combine earlier feature maps, so their receptive field grows — strides and pooling make it grow much faster. Zeiler & Fergus visualized this hierarchy in a trained network: early layers respond to edges and colours, middle layers to textures and motifs, deep layers to object parts and whole objects[5]. That's the core of the CNN inductive bias: locality (nearby pixels matter together), weight sharing (the same pattern can appear anywhere) and hierarchy (complex things are made of simpler parts)[4].
- Edge detectors: load the “edges” preset (or draw a vertical bar). Compare Sobel X with Sobel Y: Sobel X lights up on vertical edges, Sobel Y on horizontal ones. Positive and negative values mark the two sides of an edge.
- Do the math once: hover over a bright output cell and check the multiply-sum yourself — it's exactly the formula above.
- Stride and padding: with padding 0 the 16×16 input gives 14×14; switch padding to 1 → 16×16; then stride 2 → 8×8. Check each against ⌊(n + 2p − k)/s⌋ + 1.
- ReLU and pooling: turn on ReLU — negative responses vanish, keeping only one side of each edge. Then turn on 2×2 max-pool: the map halves but the strong responses survive.
- Custom kernel: set all weights to 0 except the centre = 1 → identity (output = input). Change the centre to 2 → everything doubles. Set all nine to 1/9 → a blur. You've just rebuilt three classic filters.
- Checkerboard: try the checkerboard preset with the Laplacian — it responds strongly to rapid changes in every direction.
- What it is
- Height × width of each filter (e.g. 3×3, 5×5, 7×7).
- ↑ If you increase it
- Larger receptive field per layer and more context, but parameters and compute grow with k² and the output shrinks more without padding. Two 3×3 layers usually beat one 5×5 (fewer weights, extra non-linearity).
- ↓ If you decrease it
- Cheaper and more local; 1×1 kernels only mix channels (no spatial context) and are used to change channel count cheaply.
- Typical values
- 3×3 almost everywhere; 7×7 in some stems; 1×1 for channel mixing.
- What it is
- Step size of the filter between positions.
- ↑ If you increase it
- Downsamples: output size divides by ≈ s, compute drops by ≈ s², receptive field grows faster. Too large and fine detail is skipped (with s > k some pixels are never seen).
- ↓ If you decrease it
- s = 1 keeps full resolution — maximum detail, maximum compute and memory.
- Typical values
- 1 for most layers; 2 to downsample (replacing or alongside pooling).
- What it is
- Number of border pixels (usually zeros) added on each side of the input.
- ↑ If you increase it
- Keeps the spatial size (p = (k − 1)/2 → “same”) and lets edge pixels be centred under the filter; too much padding just adds empty border.
- ↓ If you decrease it
- p = 0 (“valid”) shrinks the map by k − 1 per layer; in deep nets the image would vanish, and border pixels contribute to fewer outputs.
- Typical values
- “same” padding (1 for 3×3, 3 for 7×7).
- What it is
- How many different patterns a layer looks for = number of feature maps it outputs.
- ↑ If you increase it
- Richer features and more capacity; parameters and compute grow linearly (and the next layer's grow too).
- ↓ If you decrease it
- Faster, smaller model; too few channels become a bottleneck and the model underfits.
- Typical values
- Often doubles each time resolution halves: 64 → 128 → 256 → 512.
- What it is
- Window and stride of the pooling operation, and whether it takes the max or the average.
- ↑ If you increase it
- Larger windows downsample more aggressively: more shift tolerance and less compute, but spatial detail (needed for segmentation/detection) is lost.
- ↓ If you decrease it
- Keeps more resolution; no pooling at all leaves downsampling to strided convolutions.
- Typical values
- 2×2 max-pool with stride 2; global average pooling before the classifier.
import torch
import torch.nn as nn
x = torch.randn(8, 3, 32, 32) # (batch, channels, height, width)
net = nn.Sequential(
nn.Conv2d(3, 32, kernel_size=3, padding=1), # -> (8, 32, 32, 32)
nn.ReLU(),
nn.MaxPool2d(2), # -> (8, 32, 16, 16)
nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1), # -> (8, 64, 8, 8)
nn.ReLU(),
nn.AdaptiveAvgPool2d(1), # global average pool -> (8, 64, 1, 1)
nn.Flatten(), # -> (8, 64)
nn.Linear(64, 10), # -> (8, 10) class logits
)
print(net(x).shape) # torch.Size([8, 10])
print(sum(p.numel() for p in net.parameters())) # 20042nn.Conv2d uses N, C, H, W ordering)[6]. Parameter count: 896 + 18,496 + 650 = 20,042.- Channel order: PyTorch expects (N, C, H, W); images loaded with PIL/NumPy are usually (H, W, C). Use
permuteor torchvision transforms. - Flatten size mismatch: hard-coding
nn.Linear(64*8*8, …)breaks when the input size changes — prefer global average pooling (AdaptiveAvgPool2d). - Unnormalized pixels (0–255) slow training; scale to [0, 1] and standardize per channel.
- Too much downsampling too early destroys small objects; count your strides.
- CNNs are not rotation- or scale-invariant by design — only roughly shift-invariant. Use augmentation for the rest.
▸Go deeper: equivariance, 1×1, depthwise and dilated convolutions
Convolution is translation-equivariant: shift the input, and the feature map shifts the same way. Pooling and global averaging turn that into approximate invariance for the final prediction[4]. A 1×1 convolution is a per-pixel dense layer across channels — used in GoogLeNet and ResNet bottlenecks to cut channels cheaply. Depthwise-separable convolutions split a k×k conv into a per-channel k×k conv plus a 1×1 conv, reducing compute by roughly k² for large channel counts (MobileNets, Howard et al., 2017). Dilated convolutions space out the kernel taps to enlarge the receptive field without extra parameters — common in segmentation and audio (WaveNet)[2].
History: LeCun et al. trained convolutional networks end-to-end with backprop for handwritten digits; LeNet-5 (1998) read millions of bank cheques[3]. Ideas go back to Fukushima's Neocognitron (1980), itself inspired by Hubel & Wiesel's discovery of simple and complex cells in the visual cortex.
Quiz
References
- [1]CS231n: Convolutional Neural Networks for Visual Recognition — ConvNet notesCourseStanford CS231ncs231n.github.io
- [2]A guide to convolution arithmetic for deep learningPaperDumoulin & Visin2016arxiv.org
- [3]Gradient-based learning applied to document recognitionPaperLeCun, Bottou, Bengio & Haffner1998doi.org
- [4]Deep Learning — Chapter 9: Convolutional NetworksBookGoodfellow, Bengio & Courville2016deeplearningbook.org
- [5]Visualizing and Understanding Convolutional NetworksPaperZeiler & Fergus2013arxiv.org
- [6]torch.nn.Conv2dDocsPyTorchdocs.pytorch.org