You want a model to recognise a handwritten digit even when the strokes appear in slightly different places. A useful pattern may be a short edge or a curve that occurs in many parts of the image. Convolutional neural networks look for those local patterns with filters that slide across the pixels. LeCun's 1998 LeNet work used learned filters to read bank cheques.
We follow those sliding filters one patch at a time in NumPy and check output against PyTorch. Filter size, stride and padding then determine how the operations assemble into a digit model. The three-layer classifier reaches 98.6% peak MNIST accuracy during five epochs.
Stride-2 convolutions reduce the spatial resolution before a linear layer predicts the class.
Let's Build It
First, let's see the full CNN in action. Click the badge to open the interactive notebook:

Here is a complete, working CNN that classifies MNIST digits. We will unpack every piece afterwards.
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms
# Load MNIST
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
train_data = datasets.MNIST('data', train=True, download=True, transform=transform)
test_data = datasets.MNIST('data', train=False, transform=transform)
train_loader = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_data, batch_size=1000)
# Define CNN
class SimpleCNN(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 8, kernel_size=5, padding=2, stride=2) # 28->14
self.conv2 = nn.Conv2d(8, 16, kernel_size=3, padding=1, stride=2) # 14->7
self.conv3 = nn.Conv2d(16, 32, kernel_size=3, padding=1, stride=2) # 7->4
self.fc = nn.Linear(32 * 4 * 4, 10)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
x = F.relu(self.conv3(x))
x = x.view(x.size(0), -1)
return self.fc(x)
# Train
model = SimpleCNN()
optimiser = torch.optim.Adam(model.parameters(), lr=1e-3)
for epoch in range(5):
model.train()
for images, labels in train_loader:
loss = F.cross_entropy(model(images), labels)
optimiser.zero_grad()
loss.backward()
optimiser.step()
# Evaluate
model.eval()
correct = 0
with torch.no_grad():
for images, labels in test_loader:
correct += (model(images).argmax(1) == labels).sum().item()
print(f"Epoch {epoch+1}: {correct/len(test_data)*100:.1f}% accuracy")
Epoch 1: 96.7% accuracy
Epoch 2: 97.7% accuracy
Epoch 3: 98.2% accuracy
Epoch 4: 98.6% accuracy
Epoch 5: 98.4% accuracy

Five epochs, three convolutional layers, 98.6% peak accuracy. Now let's understand what those convolutional layers are actually doing.
What Just Happened?
The Convolution Operation
A convolution slides a small grid of numbers (the kernel or filter) across the input image. At each position, it computes element-wise multiplication between the kernel and the overlapping input patch, then sums the results into a single output value.
Here is the operation for a single position. Given a 3x3 input patch and a 3x3 kernel:
import numpy as np
# A 3x3 patch from the input image
patch = np.array([
[1, 0, 1],
[0, 1, 0],
[1, 0, 1]
])
# A 3x3 kernel (edge detector)
kernel = np.array([
[-1, -1, -1],
[-1, 8, -1],
[-1, -1, -1]
])
# Convolution at this position: element-wise multiply, then sum
output_pixel = np.sum(patch * kernel)
print(f"Output pixel value: {output_pixel}") # 4
Output pixel value: 4
That is the entire operation. Multiply corresponding elements, sum the results. The kernel slides across every position in the input to produce the full output (the feature map).
Building Conv2d from Scratch
Let's implement the full 2D convolution in NumPy. This is the core function that PyTorch's nn.Conv2d runs under the hood (albeit optimised in C++/CUDA).
def conv2d_numpy(input_img, kernel, stride=1, padding=0):
"""
2D convolution from scratch.
Args:
input_img: shape (H, W) for single channel
kernel: shape (kH, kW)
stride: step size for sliding the kernel
padding: zero-padding added to input borders
Returns:
output: shape (out_H, out_W)
"""
if padding > 0:
input_img = np.pad(input_img, padding, mode='constant', constant_values=0)
H, W = input_img.shape
kH, kW = kernel.shape
out_H = (H - kH) // stride + 1
out_W = (W - kW) // stride + 1
output = np.zeros((out_H, out_W))
for i in range(out_H):
for j in range(out_W):
h_start = i * stride
w_start = j * stride
patch = input_img[h_start:h_start + kH, w_start:w_start + kW]
output[i, j] = np.sum(patch * kernel)
return output
Let's test it on a 6x6 input with a 3x3 edge-detection kernel:
input_img = np.array([
[0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 0],
[0, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 0],
[0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0]
], dtype=np.float32)
edge_kernel = np.array([
[-1, -1, -1],
[-1, 8, -1],
[-1, -1, -1]
], dtype=np.float32)
output = conv2d_numpy(input_img, edge_kernel)
print("Output shape:", output.shape)
print(output)
Output shape: (4, 4)
[[-3. 4. 4. -3.]
[ 4. 1. 1. 4.]
[ 4. 1. 1. 4.]
[-3. 4. 4. -3.]]

The output has large positive values (4) along the edges of the diamond where 1s border 0s, and smaller values (1) in the flat interior where all neighbours are the same. The corners get negative values (-3) where the diamond meets the zero border diagonally. That is exactly what an edge detector should do: it responds strongly wherever pixel intensity changes.
Verifying Against PyTorch
The real test: does our NumPy implementation produce the same output as PyTorch?
import torch
import torch.nn.functional as F
# Same input and kernel
input_torch = torch.tensor(input_img).unsqueeze(0).unsqueeze(0) # (1, 1, 6, 6)
kernel_torch = torch.tensor(edge_kernel).unsqueeze(0).unsqueeze(0) # (1, 1, 3, 3)
output_torch = F.conv2d(input_torch, kernel_torch)
output_numpy = conv2d_numpy(input_img, edge_kernel)
print("PyTorch output:\n", output_torch.squeeze().numpy())
print("\nNumPy output:\n", output_numpy)
print("\nMatch:", np.allclose(output_numpy, output_torch.squeeze().numpy()))
PyTorch output:
[[-3. 4. 4. -3.]
[ 4. 1. 1. 4.]
[ 4. 1. 1. 4.]
[-3. 4. 4. -3.]]
NumPy output:
[[-3. 4. 4. -3.]
[ 4. 1. 1. 4.]
[ 4. 1. 1. 4.]
[-3. 4. 4. -3.]]
Match: True
Identical. Our four nested lines of NumPy do the same thing as PyTorch's optimised C++ implementation. The difference is speed: PyTorch uses BLAS routines and GPU parallelism to compute thousands of convolutions per second.
The Output Size Formula
The output dimensions follow a simple formula. Given input size , kernel size , stride , and padding :
Let's verify with our CNN's first layer. Input is 28x28, kernel is 5x5, stride 2, padding 2:
H_out = (28 + 2*2 - 5) // 2 + 1 # = 14
print(f"Output size: {H_out}x{H_out}") # 14x14
That matches the comment in our SimpleCNN: the first conv layer maps 28x28 to 14x14.
Stride and Padding
Stride controls how far the kernel jumps between positions. Stride 1 slides one pixel at a time. Stride 2 skips every other position, halving the spatial dimensions. In our CNN, every layer uses stride 2, so the feature maps shrink: 28 to 14 to 7 to 4.
Padding adds zeros around the input border. Without padding, the output shrinks by pixels (a 3x3 kernel on a 28x28 input gives 26x26). Padding of 1 on each side restores the original size with stride 1. The formula padding = kernel_size // 2 preserves spatial dimensions, which is what our CNN uses.
# stride=1, no padding: output shrinks
out1 = conv2d_numpy(input_img, edge_kernel, stride=1, padding=0)
print(f"No padding: {input_img.shape} -> {out1.shape}") # (6,6) -> (4,4)
# stride=1, padding=1: output same size
out2 = conv2d_numpy(input_img, edge_kernel, stride=1, padding=1)
print(f"Padding=1: {input_img.shape} -> {out2.shape}") # (6,6) -> (6,6)
# stride=2, padding=1: output halved
out3 = conv2d_numpy(input_img, edge_kernel, stride=2, padding=1)
print(f"Stride=2: {input_img.shape} -> {out3.shape}") # (6,6) -> (3,3)
No padding: (6, 6) -> (4, 4)
Padding=1: (6, 6) -> (6, 6)
Stride=2: (6, 6) -> (3, 3)

Multi-Channel Convolution
Real images have multiple channels (RGB has 3, our CNN's intermediate layers have 8, 16, 32). Multi-channel convolution applies a separate kernel to each input channel and sums the results.
def conv2d_multichannel(input_img, kernels, bias=None, stride=1, padding=0):
"""
Multi-channel convolution: (C_in, H, W) input, (C_out, C_in, kH, kW) kernels.
Each output channel is the sum of convolutions across all input channels,
plus an optional bias term.
"""
C_out, C_in, kH, kW = kernels.shape
if padding > 0:
input_img = np.pad(input_img, ((0, 0), (padding, padding), (padding, padding)),
mode='constant', constant_values=0)
_, H, W = input_img.shape
out_H = (H - kH) // stride + 1
out_W = (W - kW) // stride + 1
output = np.zeros((C_out, out_H, out_W))
for co in range(C_out):
for ci in range(C_in):
for i in range(out_H):
for j in range(out_W):
h_start = i * stride
w_start = j * stride
patch = input_img[ci, h_start:h_start+kH, w_start:w_start+kW]
output[co, i, j] += np.sum(patch * kernels[co, ci])
if bias is not None:
output[co] += bias[co]
return output
Let's verify multi-channel convolution also matches PyTorch:
# Random input: 3 channels, 8x8
np.random.seed(42)
input_mc = np.random.randn(3, 8, 8).astype(np.float32)
# Random kernels: 4 output channels, 3 input channels, 3x3
kernels = np.random.randn(4, 3, 3, 3).astype(np.float32)
bias = np.random.randn(4).astype(np.float32)
# NumPy version
out_np = conv2d_multichannel(input_mc, kernels, bias, stride=1, padding=1)
# PyTorch version
input_t = torch.tensor(input_mc).unsqueeze(0)
kernel_t = torch.tensor(kernels)
bias_t = torch.tensor(bias)
out_pt = F.conv2d(input_t, kernel_t, bias_t, stride=1, padding=1).squeeze(0).numpy()
print(f"Shape: {out_np.shape}")
print(f"Match: {np.allclose(out_np, out_pt, atol=1e-5)}")
Shape: (4, 8, 8)
Match: True
A single nn.Conv2d(3, 4, kernel_size=3, padding=1) layer has learnable parameters (108 kernel weights + 4 biases). During training, backpropagation adjusts these parameters so the kernels learn to detect useful features.
What the Kernels Learn
Different kernels detect different features. Classic examples include:
# Horizontal edge detector
horizontal = np.array([[-1, -1, -1],
[ 0, 0, 0],
[ 1, 1, 1]], dtype=np.float32)
# Vertical edge detector
vertical = np.array([[-1, 0, 1],
[-1, 0, 1],
[-1, 0, 1]], dtype=np.float32)
# Sharpen filter
sharpen = np.array([[ 0, -1, 0],
[-1, 5, -1],
[ 0, -1, 0]], dtype=np.float32)
# Gaussian blur (3x3 approximation)
blur = np.array([[1, 2, 1],
[2, 4, 2],
[1, 2, 1]], dtype=np.float32) / 16

In a trained CNN, the first layer typically learns edge detectors (similar to these hand-crafted ones). Deeper layers combine edges into textures, then textures into parts, then parts into objects. This hierarchical feature extraction is what makes CNNs so powerful for vision tasks.
Going Deeper
The Case for Convolution
A fully connected layer connecting every pixel to every neuron in the next layer would have enormous parameter counts. For a 28x28 image mapped to 256 neurons, that is parameters in a single layer. And it throws away all spatial structure.
Convolution exploits two key properties of images:
Local connectivity. A pixel's meaning depends on its neighbours, not on pixels far away. A 3x3 kernel looks at 9 pixels at a time, which is enough to detect local features like edges and corners.
Translation equivariance. A vertical edge is a vertical edge regardless of where it appears in the image. By sharing the same kernel weights across all spatial positions, convolution naturally captures this. A single 3x3 kernel with 1 input and 1 output channel has just 9 + 1 = 10 parameters, no matter how large the image is.
The Architecture Pattern
Our CNN follows the pattern from the fast.ai course: repeated conv-relu blocks with stride 2 for downsampling, followed by a linear classifier.
Input: (1, 28, 28) # 1 channel, 28x28 pixels
Conv1: (8, 14, 14) # 8 filters, stride 2 halves spatial dims
Conv2: (16, 7, 7) # 16 filters, stride 2 again
Conv3: (32, 4, 4) # 32 filters, stride 2 again
Flatten: (512,) # 32 * 4 * 4 = 512
Linear: (10,) # 10 classes (digits 0-9)
Each layer doubles the channel count while halving the spatial dimensions. This trades spatial resolution for feature richness. By the final conv layer, each of the 32 channels encodes a high-level feature detected across a 4x4 spatial grid.

Pooling: An Alternative to Strided Convolutions
Traditional CNNs use pooling layers to downsample. Max pooling takes the maximum value in each patch; average pooling takes the mean. Our CNN uses stride-2 convolutions instead, which is the modern approach (the model learns how to downsample rather than using a fixed rule).
def max_pool2d(input_img, pool_size=2, stride=2):
"""Max pooling: take the maximum value in each pool_size x pool_size patch."""
H, W = input_img.shape
out_H = (H - pool_size) // stride + 1
out_W = (W - pool_size) // stride + 1
output = np.zeros((out_H, out_W))
for i in range(out_H):
for j in range(out_W):
h_start, w_start = i * stride, j * stride
output[i, j] = np.max(input_img[h_start:h_start+pool_size,
w_start:w_start+pool_size])
return output
Batch Normalisation
In the fast.ai notebooks, the CNN uses batch normalisation after each conv layer. Batch norm normalises each channel's activations to have zero mean and unit variance across the mini-batch, then applies a learnable scale and shift. This stabilises training and allows higher learning rates.
class CNNWithBatchNorm(nn.Module):
def __init__(self):
super().__init__()
self.layers = nn.Sequential(
nn.Conv2d(1, 8, 5, padding=2, stride=2), nn.BatchNorm2d(8), nn.ReLU(),
nn.Conv2d(8, 16, 3, padding=1, stride=2), nn.BatchNorm2d(16), nn.ReLU(),
nn.Conv2d(16, 32, 3, padding=1, stride=2), nn.BatchNorm2d(32), nn.ReLU(),
nn.Conv2d(32, 32, 3, padding=1, stride=2), nn.BatchNorm2d(32), nn.ReLU(),
nn.AdaptiveAvgPool2d(1),
nn.Flatten(),
nn.Linear(32, 10)
)
def forward(self, x):
return self.layers(x)
This mirrors the architecture from lesson7-resnet-mnist.ipynb in the fast.ai course. The AdaptiveAvgPool2d(1) replaces our manual flatten by averaging each channel down to a single value, regardless of spatial size.
Visualising Feature Maps
To see what a trained CNN "sees", we can extract the activations (feature maps) after each conv layer:
def get_feature_maps(model, image):
"""Extract feature maps from each conv layer."""
activations = []
x = image.unsqueeze(0)
for layer in [model.conv1, model.conv2, model.conv3]:
x = F.relu(layer(x))
activations.append(x.squeeze(0).detach().numpy())
return activations
# Get feature maps for a single digit
sample_image = test_data[0][0] # First test image
feature_maps = get_feature_maps(model, sample_image)
for i, fmaps in enumerate(feature_maps):
print(f"Layer {i+1}: {fmaps.shape[0]} channels, {fmaps.shape[1]}x{fmaps.shape[2]} spatial")
Layer 1: 8 channels, 14x14 spatial
Layer 2: 16 channels, 7x7 spatial
Layer 3: 32 channels, 4x4 spatial

The first layer's feature maps look like filtered versions of the input (edges in different orientations). By the third layer, the feature maps are small (4x4) and abstract, encoding high-level patterns that distinguish one digit from another.
Hyperparameters to Tune
| Parameter | Our value | Typical range | Effect |
|---|---|---|---|
| Kernel size | 5 (first), 3 (rest) | 3, 5, 7 | Larger = wider receptive field but more parameters |
| Number of filters | 8, 16, 32 | 16-512 | More filters = more features detected |
| Stride | 2 | 1 or 2 | Stride 2 downsamples; stride 1 preserves size |
| Learning rate | 1e-3 | 1e-4 to 1e-2 | Too high = diverges; too low = slow convergence |
| Batch size | 64 | 32-256 | Larger = smoother gradients, more memory |
The first conv layer uses a 5x5 kernel to capture slightly larger patterns in the raw pixels. All subsequent layers use 3x3, which is the standard choice since VGGNet (2014) showed that stacking two 3x3 convolutions gives the same receptive field as one 5x5 with fewer parameters.
When NOT to Use CNNs
CNNs excel at grid-structured data where local patterns matter (images, spectrograms, some time series). They are not the best choice for:
- Tabular data: Gradient-boosted trees (XGBoost, LightGBM) usually outperform CNNs on structured tables.
- Sequences with long-range dependencies: Transformers and RNNs handle variable-length text better, though 1D convolutions can work for fixed-length sequences.
- Very small datasets: CNNs need thousands of examples to learn useful filters. With fewer than a few hundred images, transfer learning or simpler models are better.
- Graph-structured data: Graph neural networks are designed for non-grid topologies.
Where This Comes From
The Neocognitron (1980)
The idea of learning local, shift-invariant features from images predates modern deep learning by decades. Kunihiko Fukushima introduced the Neocognitron in 1980, a self-organising neural network that learned to recognise handwritten characters through alternating "S-cells" (simple feature detectors, analogous to conv layers) and "C-cells" (pooling layers that provide shift tolerance).
"The network has a multi-layered structure. Each cell in a layer receives input connections from a restricted area of the preceding layer, and the connections have modifiable weight factors." -- Fukushima (1980), "Neocognitron: A Self-organizing Neural Network Model for a Mechanism of Pattern Recognition Unaffected by Shift in Position"
Fukushima's design was inspired by the neuroscience work of Hubel and Wiesel, who discovered that neurons in the cat visual cortex respond to oriented edges in specific spatial regions (receptive fields). The Neocognitron was the first computational model to replicate this hierarchical, local-to-global feature extraction.
LeNet-5 (1989-1998)
The modern CNN was born when Yann LeCun combined Fukushima's architectural ideas with backpropagation (which the Neocognitron lacked). LeCun's LeNet-5 (1998) was trained end-to-end with gradient descent on the very same task we tackled above: handwritten digit recognition.
"The ability of multi-layer networks to generalize can be greatly enhanced by providing constraints from the task's domain. This idea is implemented in convolutional networks, which can be seen as a special form of multi-layer perceptrons designed to recognize two-dimensional shapes." -- LeCun et al. (1998), "Gradient-Based Learning Applied to Document Recognition"
LeNet-5's architecture is strikingly similar to our SimpleCNN: alternating convolution and subsampling (pooling) layers, followed by fully connected layers. The paper demonstrated the system reading cheques for banks across the United States, processing millions of cheques per day.
The key innovation over Fukushima's work was learning the kernels by backpropagation rather than using unsupervised competitive learning. This meant the kernel weights were directly optimised for the classification objective. This is exactly what happens in our training loop: loss.backward() computes gradients through the conv layers, and the optimiser updates the kernel weights.
From LeNet to AlexNet to Today
CNNs languished for over a decade after LeNet. The compute was not yet there. The breakthrough came in 2012 when Alex Krizhevsky's AlexNet won the ImageNet competition by a large margin, using GPUs to train a much deeper CNN on millions of images. AlexNet used the same fundamental operations (convolution, ReLU, pooling, fully connected), just scaled up.
Since then, architectures have evolved: VGGNet (2014) showed deeper is better with uniform 3x3 kernels. GoogLeNet (2014) introduced inception modules. ResNet (2015) added skip connections, allowing networks hundreds of layers deep. The fast.ai notebooks you saw earlier build a simple ResNet from the same conv_layer building blocks we used here.
Further Reading
The weight initialisation experiments examine activation and gradient behaviour before training.
The LeNet paper: LeCun, Y., Bottou, L., Bengio, Y., & Haffner, P. (1998). "Gradient-Based Learning Applied to Document Recognition." Proceedings of the IEEE, 86(11), 2278-2324. Read sections II and III for the convolutional architecture.
Fukushima's Neocognitron: Fukushima, K. (1980). "Neocognitron: A Self-organizing Neural Network Model." Biological Cybernetics, 36, 193-202. The original local-receptive-field idea.
The fast.ai course: Practical Deep Learning for Coders. Lessons 7-8 cover CNNs from scratch in the same spirit as this post.
CS231n lecture notes: Stanford CS231n. Excellent visualisations of convolution, pooling, and architecture design.
Next algorithm to learn: Trust Region Methods (TRPO and PPO) if you want to see how neural networks are used in reinforcement learning.
Interactive Tools
- 2D Convolution Visualizer: Watch a kernel slide across an input matrix step by step with element-wise multiplication, adjustable stride, padding, and dilation
- CNN Layer Visualizer: Stack the conv and pool layers this post builds and read the output shape, receptive field, and parameter count for each one, with the equivalent
nn.Sequentialunderneath - Classification Metrics Calculator: Evaluate your CNN's predictions with precision, recall, F1, and confusion matrix analysis
- Overfitting Explorer: Visualise the bias-variance tradeoff that regularisation in CNNs addresses
Related Posts
- Backpropagation Demystified: Neural Nets from First Principles: Our CNN trains with backpropagation. This post builds a neural network from scratch and traces every gradient.
- Linear Regression from Scratch: Five Solvers, One Answer: The linear layer at the end of our CNN is a multivariate linear regression. This post covers the fundamentals.
- PCA and SVD: The Linear Algebra You Actually Need: Feature maps are high-dimensional representations. PCA/SVD explains how to think about dimensionality reduction.
- Hyperparameter Optimisation: Grid vs Random vs Bayesian: Tuning kernel sizes, learning rates, and filter counts systematically.
- Deep Q-Networks: Experience Replay and Target Networks: DQNs use CNNs to process pixel inputs for reinforcement learning.
- Graph Neural Networks from Scratch: Message Passing: Generalises convolution from regular pixel grids to arbitrary graphs via message passing.
- Vision Transformers from Scratch in PyTorch: The attention-based alternative to CNNs for vision, treating an image as a sequence of patches.
- JEPA from Scratch: Predicting in Latent Space: Self-supervised representation learning that often builds on CNN/ViT encoders like the ones here.
- Perceptual Loss and Super-Resolution: Why Pixel MSE Fails: Perceptual loss is built on the feature maps these conv layers learn.
- The Universal Approximation Theorem in NumPy: A CNN is one concrete architecture the theorem's guarantee applies to: universal in principle, structured for images in practice.
- Channel Attention in PyTorch: Five Seeds, No Effect: Squeeze-and-Excitation and ECA blocks added to a small CNN, with a paired ablation over five seeds that finds no clear effect.











