AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
▦Deep Learning Architectures
  1. Convolutional Neural Networks (CNNs)
  2. CNN Architectures and Transfer Learning
  3. Recurrent Networks: RNN, LSTM and GRU
  4. Embeddings: Meaning as Vectors
  5. Attention and Transformers
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Deep Learning Architectures

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.

Intermediate~28 min·6 references
Key terms
CNN (Convolutional Neural Network)ConvolutionKernel (filter)StridePaddingPoolingFeature mapReceptive field

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].

≈
A stencil sliding over a photo
Imagine a small transparent stencil with a pattern on it — say, a vertical edge. You slide it over every position of a photo and, at each spot, write down how well the photo underneath matches the pattern. The result is a new image (a feature map) that lights up wherever there's a vertical edge. A CNN layer does this with dozens of stencils at once, and it learns which patterns are worth looking for.

The convolution operation

y[i, j] = Σₘ Σₙ x[i·s + m, j·s + n] · k[m, n] + b
Each output pixel is a weighted sum of a k×k input patch. k is the kernel, s the stride. (Strictly this is cross-correlation — deep learning libraries don't flip the kernel, and since it is learned, it doesn't matter.)
In words: “to get output pixel (i, j), lay the kernel on the input patch that starts at (i·s, j·s), multiply every overlapping pair of numbers, add them all up, and add the bias.” The same kernel k is reused at every position — that is weight sharing.
Symbols(hover a symbol in the formula)
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
Patch x = [3 1 0; 4 2 1; 5 1 0], kernel k = [1 0 −1; 1 0 −1; 1 0 −1] (vertical-edge detector), b = 1 Row 1: 3·1 + 1·0 + 0·(−1) = 3 Row 2: 4·1 + 2·0 + 1·(−1) = 3 Row 3: 5·1 + 1·0 + 0·(−1) = 5 y = 3 + 3 + 5 + 1 = 12 → strong response: the left side of the patch is much brighter than the right. A flat patch (all values equal) gives 0 + b = 1: no edge.

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

out = ⌊(n + 2p − k) / s⌋ + 1
n = input size, k = kernel size, p = padding on each side, s = stride. Apply separately to height and width.
In words: “pad the input to n + 2p, count how many kernel-sized windows fit when you step by s, and add 1 for the first window.” Use it for height and width separately.
Symbols(hover a symbol in the formula)
out
output size (height or width) in pixels
n
input size (height or width)
p
Padding added on each side (so 2p in total)
k
kernel size (k × k)
s
Stride
⌊(n + 2p − k) / s⌋
floor: round down to a whole number (a window that does not fully fit is dropped)
▸Worked example
ResNet stem: n = 224, k = 7, p = 3, s = 2 (224 + 6 − 7) / 2 = 223 / 2 = 111.5 → ⌊111.5⌋ = 111 → out = 112 LeNet-5 conv1: n = 32, k = 5, p = 0, s = 1 → (32 − 5) / 1 + 1 = 28 “Same” 3×3 conv: n = 56, k = 3, p = 1, s = 1 → 56 − 3 + 2 + 1 = 56 (size kept)
Input nkpsOutputComment
1630114“valid”: shrinks by k − 1
1631116“same”: p = (k − 1)/2 keeps the size
163128Stride 2 halves the resolution
224732112ResNet's first layer
3250128LeNet-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 = r_{l−1} + (k_l − 1) · (s₁ · s₂ · … · s_{l−1}), r₀ = 1
The receptive field r_l: how many input pixels (per side) can influence one unit in layer l. Two stacked 3×3 convs (stride 1) see 5×5; three see 7×7.
In words: Each new layer widens the view by (k − 1) units of the previous layer, and one unit of a deep layer is as wide as the product of all earlier strides in input pixels. So strides early in the network make the receptive field grow much faster.
Symbols(hover a symbol in the formula)
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
conv 3×3 (s 1) → conv 3×3 (s 1) → max-pool 2×2 (s 2) → conv 3×3 (s 1) r₁ = 1 + 2·1 = 3 r₂ = 3 + 2·1 = 5 r₃ = 5 + 1·(1·1) = 6 r₄ = 6 + 2·(1·1·2) = 10 ← after the pool, each step counts double So one unit after these four layers sees a 10×10 patch of the image.

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].

Loading interactive…
Draw on the 16×16 input, choose a kernel, and watch the feature map. Hover an output cell to see its receptive field and the multiply-and-sum.
  1. 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.
  2. Do the math once: hover over a bright output cell and check the multiply-sum yourself — it's exactly the formula above.
  3. 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.
  4. 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.
  5. 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.
  6. Checkerboard: try the checkerboard preset with the Laplacian — it responds strongly to rapid changes in every direction.
knobKernel size k
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.
knobStride s
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).
knobPadding p
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).
knobNumber of filters (output channels)
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.
knobPooling size / type
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.
python
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()))   # 20042
Shapes through a small CNN in PyTorch (nn.Conv2d uses N, C, H, W ordering)[6]. Parameter count: 896 + 18,496 + 650 = 20,042.
Loading interactive…
LeNet-5 in 3D: every box is one layer's output tensor (height × width × channels). Rotate the stack and tap each layer to see its shape and parameter count. Notice the pattern from this lesson: convolutions add channels, pooling halves height and width, and the dense layers at the end hold most of the parameters.
!
Common pitfalls
Watch out for these:
  • Channel order: PyTorch expects (N, C, H, W); images loaded with PIL/NumPy are usually (H, W, C). Use permute or 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

1.
A 32×32 input goes through a 5×5 convolution with padding 2 and stride 1. What is the output size?
2.
How many parameters does a 3×3 conv layer from 16 to 32 channels (with bias) have?
3.
Why do CNNs need far fewer parameters than fully connected networks on images?
4.
What happens to the receptive field when you stack three 3×3 conv layers with stride 1?
5.
You switch a conv layer from stride 1 to stride 2 (same padding). What happens?
Score: 0/5

References

  1. [1]
    CS231n: Convolutional Neural Networks for Visual Recognition — ConvNet notes
    CourseStanford CS231ncs231n.github.io
  2. [2]
    A guide to convolution arithmetic for deep learning
    PaperDumoulin & Visin2016arxiv.org
  3. [3]
    Gradient-based learning applied to document recognition
    PaperLeCun, Bottou, Bengio & Haffner1998doi.org
  4. [4]
    Deep Learning — Chapter 9: Convolutional Networks
    BookGoodfellow, Bengio & Courville2016deeplearningbook.org
  5. [5]
    Visualizing and Understanding Convolutional Networks
    PaperZeiler & Fergus2013arxiv.org
  6. [6]
    torch.nn.Conv2d
    DocsPyTorchdocs.pytorch.org
← Previous
Hyperparameter Tuning
Next →
CNN Architectures and Transfer Learning