MLDay 37 of 50Deep Learning
Convolutional Networks and an Image Classifier
A dense layer sees a 28×28 photo as 784 unrelated numbers.
A dense layer sees a 28×28 photo as 784 unrelated numbers. To spot the edge of a trouser leg, it has to learn that edge separately at every place it might appear. A convolutional network learns one small edge detector and slides it over the whole image.
The idea
A filter (also called a kernel) is a small grid of weights, here 3×3. Lay it on the image, multiply the 9 pixels under it by its 9 weights, and add them up. Then slide it one pixel along and repeat. The grid of results is a feature map: it's large wherever that patch of the image looks like the filter.
A convolutional layer holds many filters and learns their weights by backpropagation, like any other layer. Each filter uses the same 9 weights at every position. This parameter sharing makes the layer tiny: 16 filters of size 3×3 need 160 weights, while a dense layer from 784 pixels to 16 units needs 12,560.
Three more terms. Stride is how many pixels the filter jumps between positions. Padding adds rings of zeros around the border, so the filter can sit on the edge pixels too. Max pooling keeps the largest value in each 2×2 block, halving the height and width.
A CNN stacks these layers. The first filters find edges; the next ones can combine edges into parts, such as a collar or a heel. A dense layer at the end turns those parts into 10 class scores. A channel is one feature map in the stack: a grayscale image has 1, and the first layer outputs 16. This course's CNN:
Data augmentation makes extra training images with small changes that keep the label. A mirrored trouser is still a trouser, so each time the model draws an image, it gets a flipped copy half the time. Augment the training data only: the validation set must stay the real images the model will be scored on.
A tiny example
Take the vertical-edge filter: every row of it is (1, 0, −1). So each row gives its left pixel minus its right pixel. Pixels run from 0 (white) to 1 (dark).
| Where the window sits | Each of its 3 rows | One row gives | Output |
|---|---|---|---|
| a leg's left side | (0, 1, 1) | 0 + 0 − 1 = −1 | −3 |
| inside the leg | (1, 1, 1) | 1 + 0 − 1 = 0 | 0 |
| a leg's right side | (1, 1, 0) | 1 + 0 − 0 = 1 | +3 |
Edges score ±3, and flat patches score 0. ReLU (D29) then keeps the +3 and zeroes the −3, so catching the other side takes a second, mirrored filter. A 2×2 max pool over (0, 3, 0, 3) keeps 3: the edge survives while the map shrinks.
The formula
The size of a feature map along one side:
| Symbol | Meaning |
|---|---|
| output width (and height, for a square image) | |
| input width | |
| filter size ( for a 3×3 filter) | |
| padding: rings of zeros added on each side | |
| stride: pixels the filter jumps per step | |
| round down |
Worked: , , , gives . Pooling uses the same formula with , : , and later .
The weights in one convolutional layer:
| Symbol | Meaning |
|---|---|
| input channels (1 for a grayscale image) | |
| filters in the layer (each makes one output channel) | |
| each filter's bias |
Worked: the first layer has weights; the second has
. With the final Linear(800, 10) (8,010), the whole CNN has 12,810.
Try it
Find the edges of a tiny pair of trousers
Each output cell is the sum of the 3×3 window of pixels times the kernel's weights, cell by cell. Hover or focus an output cell to see its window. Try the edge presets.
Input image (10×10)
Kernel (edit any weight)
Output feature map (8×8)
out[1, 1] = 0·0 + 1·0 + 1·0 + 0·0 + 1·1 + 1·0 + 0·0 + 1·0 + 1·0 = 1
O = ⌊(W − K + 2P) / S⌋ + 1 = ⌊(10 − 3 + 2·0) / 1⌋ + 1 = 8
The starting kernel only copies the middle of the image, so no edge stands out. Click vertical edge: each leg's sides light up at −3 and +3, and the insides of the legs drop to 0. Then try horizontal edge, which finds the top of the gap between the legs. Set S to 2 and the output shrinks from 8×8 to 4×4. Back at S = 1, set P to 1 and it grows to 10×10, as the formula under the grid shows.
In code
First, a hand-made filter on a real trouser image. nn.Conv2d takes images shaped (batch, channels,
height, width):
# script_id: day_037_convolutional_networks/edge_filter
import os
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import torch
from torch import nn
DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
d = np.load(DATA_DIR / "fashion_mnist" / "fashion_mnist_slice.npz")
trouser = torch.from_numpy(d["X_train"][d["y_train"] == 1][0].astype("float32") / 255)
image = trouser.reshape(1, 1, 28, 28) # one image, one channel
vertical = torch.tensor([[1.0, 0.0, -1.0]] * 3) # left pixel minus right pixel
conv = nn.Conv2d(1, 2, kernel_size=3, bias=False) # 2 filters, set by hand
with torch.no_grad():
conv.weight.copy_(torch.stack([vertical, vertical.T]).unsqueeze(1))
maps = conv(image)[0] # (2, 26, 26)
print("feature maps:", tuple(maps.shape))
print(f"mean |response|: vertical {maps[0].abs().mean():.3f}, horizontal {maps[1].abs().mean():.3f}")
print("weights in a 16-filter 3x3 layer:", sum(p.numel() for p in nn.Conv2d(1, 16, 3).parameters()))
feature maps: (2, 26, 26)
mean |response|: vertical 0.463, horizontal 0.103
weights in a 16-filter 3x3 layer: 160
The two maps are 26×26, as the formula says. The vertical filter responds about 4.5 times as strongly as the horizontal one, because a trouser is mostly long vertical edges. Drawing the vertical map shows where:
# script_id: day_037_convolutional_networks/edge_filter
FIG_DIR = Path(os.environ.get("ML_FIG_DIR", "figures"))
FIG_DIR.mkdir(exist_ok=True)
fig, axes = plt.subplots(1, 2, figsize=(6, 4))
axes[0].imshow(trouser, cmap="gray_r")
axes[0].set_title("input (28×28)")
lim = maps[0].abs().max().item()
axes[1].imshow(maps[0], cmap="RdBu", vmin=-lim, vmax=lim)
axes[1].set_title("vertical-edge map (26×26)")
for ax in axes:
ax.set_axis_off()
fig.suptitle("A vertical-edge filter lights up the trouser legs' sides")
fig.tight_layout()
fig.savefig(FIG_DIR / "edge_filter.png", dpi=120)
plt.close(fig)

Red is negative: reading left to right, light turns to dark, where each leg begins. Blue is positive, where each leg ends.
Now the CNN from the diagram against the MLP from D33, on the same split and with the same training settings. First the data and the two models:
# script_id: day_037_convolutional_networks/cnn
import os
from pathlib import Path
import numpy as np
import torch
import torchvision.transforms.v2 as T
from sklearn.model_selection import train_test_split
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
d = np.load(DATA_DIR / "fashion_mnist" / "fashion_mnist_slice.npz")
X, y = d["X_train"].astype("float32") / 255, d["y_train"].astype("int64")
X_tr, X_va, y_tr, y_va = train_test_split(X, y, test_size=1000, stratify=y, random_state=42)
X_tr, X_va = torch.from_numpy(X_tr).unsqueeze(1), torch.from_numpy(X_va).unsqueeze(1) # (n, 1, 28, 28)
y_tr, y_va = torch.from_numpy(y_tr), torch.from_numpy(y_va)
def mlp():
return nn.Sequential(nn.Flatten(), nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 10))
def cnn():
return nn.Sequential(
nn.Conv2d(1, 16, 3), nn.ReLU(), nn.MaxPool2d(2), # 28 -> 26 -> 13
nn.Conv2d(16, 32, 3), nn.ReLU(), nn.MaxPool2d(2), # 13 -> 11 -> 5
nn.Flatten(), nn.Linear(32 * 5 * 5, 10))
print("logits for one image:", tuple(cnn()(X_va[:1]).shape))
for name, make_model in [("MLP", mlp), ("CNN", cnn)]:
print(f"{name} weights: {sum(p.numel() for p in make_model().parameters()):,}")
logits for one image: (1, 10)
MLP weights: 101,770
CNN weights: 12,810
Training is the loop from D32, plus one line that flips each training image with probability 0.5:
# script_id: day_037_convolutional_networks/cnn
def accuracy(model, X, y):
model.eval()
with torch.no_grad():
return (model(X).argmax(dim=1) == y).float().mean().item()
def train(make_model, augment=None):
torch.manual_seed(42)
model = make_model()
loader = DataLoader(TensorDataset(X_tr, y_tr), batch_size=64, shuffle=True,
generator=torch.Generator().manual_seed(42))
opt, loss_fn = torch.optim.Adam(model.parameters(), lr=1e-3), nn.CrossEntropyLoss()
for epoch in range(10):
model.train()
for xb, yb in loader:
if augment: # training batches only
xb = torch.stack([augment(x) for x in xb]) # a fresh coin flip per image
opt.zero_grad()
loss_fn(model(xb), yb).backward()
opt.step()
return accuracy(model, X_tr, y_tr), accuracy(model, X_va, y_va)
for name, make_model, augment in [("MLP", mlp, None), ("CNN", cnn, None),
("CNN + flips", cnn, T.RandomHorizontalFlip())]:
train_acc, val_acc = train(make_model, augment)
print(f"{name:<11} train acc {train_acc:.3f} val acc {val_acc:.3f}")
MLP train acc 0.880 val acc 0.840
CNN train acc 0.858 val acc 0.830
CNN + flips train acc 0.847 val acc 0.822
The CNN comes within one point of the MLP with 8 times fewer weights, but it doesn't beat it. On 5,000 small, centred images, an MLP is a strong rival, and its validation accuracy swings by a few points between epochs. Flips cost 0.8 points: like dropout (D36), augmentation fights memorizing, and this CNN wasn't memorizing (training accuracy only 0.028 above validation). D39 trains and tunes this CNN.
Quick check
Quick check
1. A 28×28 image, a 3×3 filter, padding 1 and stride 2. How wide is the feature map?
2. A colour image has 3 channels (red, green, blue). How many weights does a 3×3 conv layer with 8 filters have?
3. Where should random flips be applied?
Next
D38: Transfer Learning borrows filters that a big network already learned from millions of photos, instead of learning them from 5,000.
Data: Fashion-MNIST (Zalando Research), MIT licence; cite Xiao, H., Rasul, K. and Vollgraf, R. (2017), "Fashion-MNIST: a Novel Image Dataset for Benchmarking Machine Learning Algorithms", arXiv:1708.07747.