Concept Explanation
Feed a 224×224 colour photo to a fully-connected layer and you need 150,528 inputs. One hidden layer of 1,000 neurons is 150 million parameters — for a single layer, on one small image. It would overfit instantly and still not recognise the same cat shifted three pixels to the left.
Convolutional networks fix both problems with two ideas.
1. Local connectivity. A pixel's meaning comes from its neighbours, not from a pixel on the opposite corner. So each neuron looks at a small patch — typically 3×3 — instead of the whole image.
2. Weight sharing. An edge detector is useful everywhere in the image, so the same small filter slides across the entire input. One 3×3 filter on a colour image is 28 parameters (3×3×3 weights + 1 bias) and it examines every position.
Together these give translation invariance: a feature learned in one corner is detected in every corner, for free.
What a Convolution Does
A filter (kernel) slides over the input, computing a dot product at each position, producing a feature map — a picture of where that pattern occurs.
nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, padding=1)
| Argument | Meaning |
|---|---|
in_channels | Depth of the input (3 for RGB, 1 for greyscale) |
out_channels | How many different filters to learn |
kernel_size | Patch size — 3 is almost always right |
stride | Step between positions; 2 halves the output size |
padding | Zeros added around the border |
Use padding=1 with kernel_size=3 and the output keeps the input's height and width. This "same padding" convention lets you stack layers without recalculating dimensions at every step.
The Output Size Formula
out = floor((in + 2*padding - kernel_size) / stride) + 1
For a 32×32 input with kernel_size=3, padding=1, stride=1: (32 + 2 - 3)/1 + 1 = 32. Unchanged, as promised.
Pooling
nn.MaxPool2d(2) takes the maximum of each 2×2 block, halving height and width. It has no parameters. Two effects:
- Shrinks the spatial size, cutting computation for later layers.
- Enlarges the receptive field — after pooling, each neuron effectively sees a bigger region of the original image.
The Standard Architecture
Nearly every classic CNN follows one shape:
[Conv -> BatchNorm -> ReLU -> Conv -> BatchNorm -> ReLU -> MaxPool] x N
-> Flatten (or GlobalAvgPool) -> Linear -> output
Spatial size shrinks while channel count grows: 32×32×3 → 16×16×32 → 8×8×64 → 4×4×128. The network trades "where" for "what", building from edges to textures to object parts to objects.
Channels-First Tensor Shape
PyTorch expects (batch, channels, height, width) — NCHW. TensorFlow and most image libraries use (batch, height, width, channels) — NHWC. Loading images with PIL or OpenCV gives you HWC, so you must permute:
tensor = torch.from_numpy(array).permute(2, 0, 1) # HWC -> CHW
Getting this wrong produces a shape error if you are lucky, and a model that trains on garbage if you are not.
Data Augmentation Is Not Optional
Images are the one domain where free extra data is genuinely available:
transforms.Compose([
transforms.RandomHorizontalFlip(),
transforms.RandomCrop(32, padding=4),
transforms.ColorJitter(brightness=0.2),
transforms.ToTensor(),
transforms.Normalize(mean, std),
])
Apply augmentation to the training set only. Augmenting validation data makes your metric random. And think about whether each transform preserves the label: horizontal flips are fine for cats, wrong for digits (a flipped 2 is not a 2) and wrong for text.
Code Example #1 (Basic)
Watching the shapes move through a small CNN.
import torch
import torch.nn as nn
torch.manual_seed(0)
# One batch of 8 colour images, 32x32
x = torch.randn(8, 3, 32, 32) # NCHW
print(f"input {tuple(x.shape)}")
conv1 = nn.Conv2d(3, 16, kernel_size=3, padding=1)
print(f"after Conv2d(3 -> 16) {tuple(conv1(x).shape)} (H, W unchanged)")
pool = nn.MaxPool2d(2)
h = pool(torch.relu(conv1(x)))
print(f"after MaxPool2d(2) {tuple(h.shape)} (H, W halved)")
conv2 = nn.Conv2d(16, 32, kernel_size=3, padding=1)
h = pool(torch.relu(conv2(h)))
print(f"after Conv2d(16 -> 32)+pool {tuple(h.shape)}")
conv3 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
h = pool(torch.relu(conv3(h)))
print(f"after Conv2d(32 -> 64)+pool {tuple(h.shape)}")
flat = h.flatten(1) # keep the batch dim
print(f"after flatten {tuple(flat.shape)} = 64 * 4 * 4")
head = nn.Linear(64 * 4 * 4, 10)
print(f"after Linear -> 10 classes {tuple(head(flat).shape)}\n")
# --- Why convolution is cheap: compare the parameter counts ---
conv_params = sum(p.numel() for p in nn.Conv2d(3, 16, 3, padding=1).parameters())
dense_params = 32 * 32 * 3 * 16 + 16 # a dense layer with 16 outputs
print(f"Conv2d(3->16, k=3): {conv_params:>10,} parameters")
print(f"Equivalent Linear: {dense_params:>10,} parameters")
print(f"Convolution is {dense_params / conv_params:,.0f}x smaller.")
# --- A stride of 2 replaces pooling ---
strided = nn.Conv2d(3, 16, kernel_size=3, stride=2, padding=1)
print(f"\nstride=2 output: {tuple(strided(x).shape)} (downsamples with learned weights)")
Printing shapes at every layer is the single most useful debugging habit in computer vision. The 64 * 4 * 4 figure feeding the first Linear is not something to guess — derive it, or let the network tell you.
Code Example #2 (Intermediate)
A real CNN with BatchNorm, augmentation, and global average pooling.
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader, TensorDataset
torch.manual_seed(0)
device = "cuda" if torch.cuda.is_available() else "cpu"
class ConvBlock(nn.Module):
"""Conv -> BatchNorm -> ReLU, the unit every modern CNN is built from."""
def __init__(self, in_ch, out_ch):
super().__init__()
# bias=False: BatchNorm has its own shift, so the conv bias is redundant
self.conv = nn.Conv2d(in_ch, out_ch, kernel_size=3, padding=1, bias=False)
self.norm = nn.BatchNorm2d(out_ch)
def forward(self, x):
return F.relu(self.norm(self.conv(x)))
class SmallCNN(nn.Module):
def __init__(self, num_classes=10, in_ch=1):
super().__init__()
self.features = nn.Sequential(
ConvBlock(in_ch, 32), ConvBlock(32, 32), nn.MaxPool2d(2), # 28 -> 14
nn.Dropout2d(0.1),
ConvBlock(32, 64), ConvBlock(64, 64), nn.MaxPool2d(2), # 14 -> 7
nn.Dropout2d(0.2),
ConvBlock(64, 128),
)
# Global average pooling: one number per channel, so any input size works
self.pool = nn.AdaptiveAvgPool2d(1)
self.head = nn.Sequential(
nn.Flatten(),
nn.Dropout(0.3),
nn.Linear(128, num_classes),
)
def forward(self, x):
return self.head(self.pool(self.features(x)))
model = SmallCNN(num_classes=10, in_ch=1).to(device)
total = sum(p.numel() for p in model.parameters())
print(f"SmallCNN: {total:,} parameters")
# Confirm the shape contract before training anything
dummy = torch.randn(4, 1, 28, 28, device=device)
print(f"forward pass: {tuple(dummy.shape)} -> {tuple(model(dummy).shape)}\n")
# Global pooling means a different input size still works
odd = torch.randn(2, 1, 40, 40, device=device)
print(f"40x40 input also works: {tuple(model(odd).shape)} (thanks to AdaptiveAvgPool2d)\n")
# ---------- Synthetic 'digits': 3 distinguishable shapes ----------
def make_shapes(n_per_class=400, size=28):
xs, ys = [], []
g = torch.Generator().manual_seed(0)
for cls in range(3):
for _ in range(n_per_class):
img = torch.zeros(1, size, size)
r = torch.randint(4, 12, (1,), generator=g).item()
cy = torch.randint(r + 2, size - r - 2, (1,), generator=g).item()
cx = torch.randint(r + 2, size - r - 2, (1,), generator=g).item()
if cls == 0: # filled square
img[:, cy - r:cy + r, cx - r:cx + r] = 1.0
elif cls == 1: # hollow square
img[:, cy - r:cy + r, cx - r:cx + r] = 1.0
img[:, cy - r + 2:cy + r - 2, cx - r + 2:cx + r - 2] = 0.0
else: # horizontal bar
img[:, cy - 2:cy + 2, cx - r:cx + r] = 1.0
img += 0.08 * torch.randn(img.shape, generator=g)
xs.append(img)
ys.append(cls)
return torch.stack(xs), torch.tensor(ys)
X, y = make_shapes()
perm = torch.randperm(len(X), generator=torch.Generator().manual_seed(1))
X, y = X[perm], y[perm]
split = int(0.8 * len(X))
train_loader = DataLoader(TensorDataset(X[:split], y[:split]), batch_size=64, shuffle=True)
val_loader = DataLoader(TensorDataset(X[split:], y[split:]), batch_size=256, shuffle=False)
model = SmallCNN(num_classes=3, in_ch=1).to(device)
criterion = nn.CrossEntropyLoss() # expects raw logits + integer labels
optimiser = torch.optim.Adam(model.parameters(), lr=2e-3)
print(f"{'epoch':>5} {'train':>8} {'val':>8} {'acc':>7}")
for epoch in range(1, 9):
model.train()
tl = 0.0
for xb, yb in train_loader:
xb, yb = xb.to(device), yb.to(device)
# Cheap augmentation: random horizontal flip on the batch
if torch.rand(1).item() > 0.5:
xb = torch.flip(xb, dims=[3])
optimiser.zero_grad()
loss = criterion(model(xb), yb)
loss.backward()
optimiser.step()
tl += loss.item() * len(xb)
tl /= split
model.eval()
vl, correct = 0.0, 0
with torch.no_grad():
for xb, yb in val_loader:
xb, yb = xb.to(device), yb.to(device)
logits = model(xb)
vl += criterion(logits, yb).item() * len(xb)
correct += (logits.argmax(1) == yb).sum().item()
n_val = len(X) - split
print(f"{epoch:>5} {tl:>8.4f} {vl / n_val:>8.4f} {correct / n_val:>7.3f}")
# --- What did the first layer learn? ---
first = model.features[0].conv.weight.detach().cpu()
print(f"\nfirst conv weights: {tuple(first.shape)} = (32 filters, 1 channel, 3x3)")
print("Filter 0:\n", first[0, 0].round(decimals=2))
AdaptiveAvgPool2d(1) is worth adopting as a default. It replaces the flatten-plus-huge-Linear pattern, cuts most of the parameters, overfits far less, and — as the 40×40 test shows — makes the network accept any input size instead of exactly the one you hardcoded.
Common Mistakes
- Wrong tensor layout: passing NHWC to PyTorch. It wants NCHW. Use
.permute(0, 3, 1, 2). - Hardcoding the flatten size wrong:
Linear(64*4*4, ...)when the feature map is actually 5×5. Print the shape, or useAdaptiveAvgPool2d. - Forgetting
padding=1withkernel_size=3: every layer shrinks the image by 2 pixels, so a deep stack runs out of spatial dimensions. - Augmenting the validation set: your metric becomes noise. Training transforms and evaluation transforms must be separate objects.
- Label-breaking augmentation: horizontal flips on digits or text change what the image means.
- Applying
SoftmaxbeforeCrossEntropyLoss: it includes log-softmax. Feeding it probabilities kills your gradients. - Not normalising pixel values: raw 0–255 inputs make training unstable. Scale to [0,1] and normalise with the dataset's mean and std.
- Missing
model.eval(): BatchNorm keeps updating its running statistics during validation, so your numbers drift. - A giant
Linearafter flatten:128*28*28 -> 512is 51 million parameters and a guaranteed overfit. Pool first. - Training a large CNN from scratch on 500 images: use transfer learning instead. From-scratch training needs tens of thousands of examples.
Dropoutinstead ofDropout2dbetween conv layers:Dropout2ddrops entire channels, which is the correct regularisation for feature maps.
Best Practices
- Print the shape after every layer the first time you build an architecture. It takes a minute and saves an hour.
- Use
kernel_size=3, padding=1as your default conv — cheap, stackable, and dimension-preserving. - Follow Conv → BatchNorm → ReLU, with
bias=Falseon the conv since BatchNorm supplies the shift. - Grow channels as you shrink space: 32 → 64 → 128 while 28 → 14 → 7.
- End with
AdaptiveAvgPool2d(1)rather than a large flatten-plus-Linear. - Normalise inputs with the dataset's own mean and standard deviation.
- Augment training data only, and check that every transform preserves the label.
- Reach for a pretrained backbone first: a fine-tuned ResNet beats a from-scratch CNN on almost any small dataset.
- Overfit 32 images deliberately as a smoke test before starting a real run.
- Visualise the first-layer filters: they should look like edge and blob detectors. If they look like noise, training has not worked.
- Use
CrossEntropyLosswith raw logits and integer labels — no one-hot encoding, no Softmax layer.
Practice Exercises
- The Shape Tracker: Build a 4-layer CNN and print the tensor shape after every single layer for a
(8, 3, 64, 64)input. Then compute by hand what the flatten size will be and confirm your arithmetic against the printout. - The Parameter Comparison: Count the parameters in
nn.Conv2d(3, 32, 3, padding=1)versus ann.Linearmapping a flattened 64×64×3 image to 32 outputs. Report the ratio and explain which of the two ideas — local connectivity or weight sharing — saves more. - The Pooling Swap: Take a working CNN that ends in
Flatten() -> Linear(big, n)and replace that withAdaptiveAvgPool2d(1) -> Flatten() -> Linear(channels, n). Compare parameter counts and validation accuracy, and confirm the new version accepts a differently-sized input.