Convolutional Neural Networks
Loading & Preparing the Data · Creating a Convolutional Model · Summarizing the Model · Training
Why Not Just Use More Dense Layers?
The feedforward networks from Modules 1–2 flatten the image immediately, throwing away all spatial structure — pixel (0,0) and pixel (0,1) become just two numbers in a list, with no notion that they're neighbors. A convolutional layer instead slides a small filter across the image, learning to detect local patterns — edges, curves, textures — wherever they appear. Far fewer parameters, and it actually exploits what makes images images.
Loading and Preparing the Data
Same ASL data as Module 2 — CSV in, reshape to (1, 28, 28), wrap in a Dataset and DataLoader. Nothing new here; the shape a CNN expects is exactly the shape we already built.
Creating a Convolutional Model
Three conv blocks, each following the same pattern: convolve → normalize → activate → (sometimes) drop out → pool.
import torch.nn as nn
model = nn.Sequential(
nn.Conv2d(1, 25, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(25),
nn.ReLU(),
nn.MaxPool2d(2, stride=2), # 28 → 14
nn.Conv2d(25, 50, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(50),
nn.ReLU(),
nn.Dropout(0.2),
nn.MaxPool2d(2, stride=2), # 14 → 7
nn.Conv2d(50, 75, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(75),
nn.ReLU(),
nn.MaxPool2d(2, stride=2), # 7 → 3
nn.Flatten(),
nn.Linear(75 * 3 * 3, 512),
nn.Dropout(0.3),
nn.ReLU(),
nn.Linear(512, 25)
)
Four new pieces, each doing one job:
| Layer | Job |
|---|---|
| Conv2d | Slides a learned filter across the image to detect local patterns. stride=1 means it moves 1 pixel at a time, checking every position; stride=2 (used below, in MaxPool2d) would skip every other position instead. |
| padding=1 (with a 3×3 kernel) | Adds a 1-pixel border so output size matches input size ("same" padding) |
| BatchNorm2d | Normalizes activations within a batch — stabilizes and speeds up training |
| MaxPool2d(2) | Halves height and width, keeping the strongest signal — less compute, more tolerance to small shifts |
Each MaxPool2d(2) halves the spatial size: 28 → 14 → 7 → 3. That's why the flatten step multiplies by 3 × 3, not 28 × 28 — check the math before you write the Linear layer, or you'll get a shape-mismatch error the moment you run it.
Dropout layers above. They exist to fight overfitting — what happens when a model gets so good at memorizing the exact training examples it's seen that it stops learning the general pattern, and does noticeably worse on new data it hasn't seen. Like a student who memorizes last year's exact exam answers instead of understanding the subject: perfect score on the old exam, falls apart on this year's new one. Dropout randomly switches off a fraction of the network's activations during training, so it can't lean too hard on any single memorized path — it's forced to learn something more general instead.
Summarizing the Model
No extra library needed — PyTorch modules already know their own parameters:
total_params = sum(p.numel() for p in model.parameters())
print(f"Total trainable parameters: {total_params:,}")
# → Total trainable parameters: 404,612
Printing the model itself (print(model)) also lists every layer in order — worth a glance any time the architecture changes, to catch mistakes before training wastes your time.
Training the Model
Identical loop to Module 2 — model.train() / model.eval(), track train and validation accuracy each epoch. The architecture changed; the training loop didn't have to.
Vocabulary
- Convolutional layer (Conv2d)
- Slides a small learned filter across an image to detect local patterns.
- Kernel / filter
- The small learned grid of numbers a convolutional layer slides across the image.
- Stride
- How many pixels a filter moves each step — 1 checks every position, 2 skips every other.
- Padding
- Adds a border of pixels so a layer's output size can match its input size.
- BatchNorm
- Normalizes activations within a batch, stabilizing and speeding up training.
- MaxPool
- Shrinks height and width, keeping only the strongest signal in each region.
- Dropout
- Randomly disables some activations during training only, to fight overfitting.
- Overfitting
- Memorizing training data instead of learning general patterns — great on old data, worse on new.
- Parameters
- The individual learned numbers (weights) inside a model.