Learning path: Neural Networks from Scratch to Embeddings · Step 7 of 9
Convolutional Neural Networks (CNN) Basics: Filters, Feature Maps and Pooling
Small filters slide over a picture looking for patterns. A vertical-edge filter by hand, padding and stride, max pooling, then a 20,490-parameter CNN that reaches 0.9861 on MNIST test digits.
What you will learn
- Apply one 3 x 3 filter by hand and slide it with F.conv2d to make a feature map
- Predict feature-map sizes with and without padding and stride
- Shrink a map with max pooling
- Build and train a small CNN in PyTorch and compare it with the dense network
Before you start
- The Same Network in PyTorch: DataLoader, nn.Module and the Five-Line Training Loop
Imagine sweeping a small magnifying glass across a photo, one spot at a time. At first you only notice small things, like edges: a dark patch right next to a bright one. Edges together make shapes, like a curve or a corner. Shapes together make the object: "oh, it's a 5."
That magnifying glass is a filter. What it finds, spot by spot, is a feature map. A convolutional neural network (CNN) is a network made of these filters. The data and the training loop stay exactly as in The Same Network in PyTorch; only the model changes.
Setup: keep the picture's shape
The dense network flattened each digit to 784 numbers. A CNN keeps the 28 x 28 grid, plus one extra dimension for the channel (1 for grey scale):
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from torch.utils.data import TensorDataset, DataLoader
import matplotlib.pyplot as plt
torch.manual_seed(42)
d = np.load("mnist.npz")
X = torch.tensor(d["x_train"] / 255.0,
dtype=torch.float32).unsqueeze(1)
y = torch.tensor(d["y_train"], dtype=torch.long)
X_tr, y_tr = X[:48000], y[:48000]
X_va, y_va = X[48000:], y[48000:]
print(X_tr.shape)
torch.Size([48000, 1, 28, 28])
One filter, one spot
Take a 3 x 3 window from our first digit (a 5) and a filter with -1 on the left, 0 in the middle and +1 on the right. Multiply each pixel by the filter number in the same place and add all nine.
digit = X[0, 0] # the first image, a 5
patch = digit[10:13, 11:14] # a 3 x 3 window
kernel = torch.tensor([[-1., 0., 1.],
[-1., 0., 1.],
[-1., 0., 1.]])
print(patch.round(decimals=2))
print("patch * kernel, summed:",
round((patch * kernel).sum().item(), 2))
tensor([[0.6000, 0.9900, 0.3500],
[0.5500, 0.9900, 0.7500],
[0.0400, 0.7500, 0.9900]])
patch * kernel, summed: 0.9
Basically the right column minus the left column: (0.35 + 0.75 + 0.99) - (0.60 + 0.55 + 0.04) = 0.9. A big number means "dark on the left, bright on the right": a vertical edge. Then the window slides one pixel to the right and does it again. Every spot gives one number, and all those numbers together make the feature map.
Slide the filter everywhere with F.conv2d
img = X[0:1] # shape (1, 1, 28, 28)
k = kernel.view(1, 1, 3, 3)
fmap = F.conv2d(img, k)
fmap_pad = F.conv2d(img, k, padding=1)
fmap_s2 = F.conv2d(img, k, padding=1, stride=2)
print("no padding:", tuple(fmap.shape[2:]))
print("padding=1 :", tuple(fmap_pad.shape[2:]))
print("stride=2 :", tuple(fmap_s2.shape[2:]))
no padding: (26, 26)
padding=1 : (28, 28)
stride=2 : (14, 14)
- No padding: the window can't hang over the edge, so the map shrinks to 26 x 26.
padding=1: a ring of zeros around the picture keeps the map at 28 x 28.stride=2: the window jumps two pixels at a time, so the map is 14 x 14.
What the filters find
Run the vertical filter on the whole picture, and its twin turned on its side (kernel.T) for horizontal edges:
horiz = kernel.T.reshape(1, 1, 3, 3)
maps = [img[0, 0], fmap_pad[0, 0],
F.conv2d(img, horiz, padding=1)[0, 0]]
names = ["input", "vertical edges", "horizontal edges"]
fig, ax = plt.subplots(1, 3)
for a, m, t in zip(ax, maps, names):
a.imshow(m, cmap="gray" if t == "input" else "coolwarm")
a.set_title(t)
a.axis("off")
plt.show()

Red marks the edge each filter looks for (dark, then bright). In a real CNN you don't write these filters by hand. The Conv2d layers hold filters that the network learns on its own.
Pooling keeps the strongest
The second idea is pooling. Max pooling with a kernel size of 2 cuts the map into 2 x 2 blocks and keeps only the biggest number in each.
m = torch.tensor([[1., 3., 2., 0.],
[4., 6., 1., 1.],
[0., 2., 9., 5.],
[1., 1., 3., 7.]])
pooled = F.max_pool2d(m.view(1, 1, 4, 4),
kernel_size=2)
print(pooled.view(2, 2))
tensor([[6., 2.],
[2., 9.]])
The map is now half as wide and half as tall, and the strong signals stay. Less work for the next layer.
The only new part: the model class
class DigitCNN(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 16, 3, padding=1)
self.conv2 = nn.Conv2d(16, 32, 3, padding=1)
self.pool = nn.MaxPool2d(2)
self.out = nn.Linear(32 * 7 * 7, 10)
def forward(self, x):
x = self.pool(torch.relu(self.conv1(x)))
x = self.pool(torch.relu(self.conv2(x)))
return self.out(x.flatten(1))
conv1 takes 1 input channel and learns 16 filters of size 3 x 3. conv2 takes those 16 maps and makes 32. In forward we do filter, ReLU and pool, twice, then one Linear layer gives 10 scores.
One picture through the CNN
device = "cuda" if torch.cuda.is_available() else "cpu"
model = DigitCNN().to(device)
x = X[:1].to(device)
print("input ", tuple(x.shape))
x = model.pool(torch.relu(model.conv1(x)))
print("conv1 + pool", tuple(x.shape))
x = model.pool(torch.relu(model.conv2(x)))
print("conv2 + pool", tuple(x.shape))
print("flatten ", tuple(x.flatten(1).shape))
print("params:", sum(p.numel() for p in model.parameters()))
input (1, 1, 28, 28)
conv1 + pool (1, 16, 14, 14)
conv2 + pool (1, 32, 7, 7)
flatten (1, 1568)
params: 20490
16 maps of 14 x 14, then 32 maps of 7 x 7, then 32 x 7 x 7 = 1,568 numbers in one row for the Linear layer. The picture keeps its shape until the very end, and the whole network has only 20,490 parameters.
Same loop, better score
Training uses the same loop as the PyTorch article. The only change is that evaluate works in chunks of 1,000 images to save memory.
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
train_loader = DataLoader(
TensorDataset(X_tr, y_tr), batch_size=32, shuffle=True)
def train_one_epoch():
model.train()
for xb, yb in train_loader:
xb, yb = xb.to(device), yb.to(device)
loss = loss_fn(model(xb), yb)
optimizer.zero_grad()
loss.backward()
optimizer.step()
def evaluate(X, y): # in chunks of 1,000, to save memory
model.eval()
total, hits = 0.0, 0
with torch.no_grad():
for i in range(0, len(X), 1000):
pred = model(X[i:i + 1000].to(device))
yy = y[i:i + 1000].to(device)
total += loss_fn(pred, yy).item() * len(yy)
hits += (pred.argmax(1) == yy).sum().item()
return total / len(X), hits / len(X)
for epoch in range(1, 6):
train_one_epoch()
va_loss, va_acc = evaluate(X_va, y_va)
print(f"epoch {epoch} val_loss {va_loss:.3f}"
f" val_acc {va_acc:.3f}")
X_te = torch.tensor(d["x_test"] / 255.0,
dtype=torch.float32).unsqueeze(1)
y_te = torch.tensor(d["y_test"], dtype=torch.long)
acc = evaluate(X_te, y_te)[1]
print("test accuracy:", round(acc, 4))
epoch 1 val_loss 0.085 val_acc 0.976
epoch 2 val_loss 0.062 val_acc 0.981
epoch 3 val_loss 0.054 val_acc 0.985
epoch 4 val_loss 0.054 val_acc 0.984
epoch 5 val_loss 0.052 val_acc 0.985
test accuracy: 0.9861
97.6% after one epoch, 98.5% after five, and 0.9861 on the 10,000 test digits. On a CPU the training takes a few minutes.
Dense vs CNN
| Dense network | CNN | |
|---|---|---|
| Parameters | 101,770 | 20,490 |
| Epochs | 10 | 5 |
| Validation accuracy (last epoch) | 0.973 | 0.985 |
| Test accuracy | 0.9756 | 0.9861 |
About five times fewer knobs, half the epochs, and fewer mistakes. Filters that look at small neighbourhoods suit pictures much better than neurons that look at every pixel at once.
Common mistakes
- Forgetting the channel dimension.
Conv2dexpects (batch, channels, height, width); that's whatunsqueeze(1)adds. - Getting the
Linearinput size wrong. Follow the shapes: two pools take 28 to 14 to 7, so it's 32 x 7 x 7. - Forgetting padding shrinks the map. Without
padding=1, a 3 x 3 filter turns 28 into 26.
Quick recap
| Idea | Code | Example |
|---|---|---|
| A filter finds a pattern | (patch * kernel).sum() | Vertical edge: 0.9 |
| Feature map | F.conv2d(img, k, padding=1) | 28 x 28 map |
| Pooling keeps the strongest | F.max_pool2d(..., kernel_size=2) | 4 x 4 to 6, 2, 2, 9 |
| Learned filters | nn.Conv2d(1, 16, 3, padding=1) | 20,490 parameters |
| Result | same training loop | Test 0.9861 |
Try it yourself
Add a third block: nn.Conv2d(32, 64, ...) with a pool. What is the new shape before the Linear layer, and does the accuracy change?
The notebook and mnist.npz are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →The Same Network in PyTorch: DataLoader, nn.Module and the Five-Line Training Loop
Next →Embeddings: Words as Vectors, Cosine Similarity and nn.Embedding
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Why Neural Networks: Pixels, One Neuron and Layers
Why pictures need neural networks: a handwritten digit is 784 numbers, one neuron is a weighted sum plus a bias and one small rule, and neurons stack into layers. Worked out on MNIST with NumPy.
The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax
Follow numbers through a tiny 3-2-3 network in NumPy: one matrix product per layer, ReLU inside, softmax at the end, and a count of every weight and bias.
Loss and Backpropagation: How Wrong, and Who Is to Blame
The loss says how wrong the network was; backpropagation says how much each weight is to blame. MSE and cross-entropy, the chain rule by hand on a two-weight chain, then the same gradients from PyTorch autograd.
The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
How training is organised: shuffle, cut into mini-batches, take one step per batch, repeat per epoch. Real MNIST runs compare three learning rates, SGD against Adam, and show the overfitting signal in the validation loss.