Convolutional Neural Networks
How CNNs see — convolution as sliding filters, feature maps, stride and padding, pooling, receptive fields, the classic architectures (LeNet, AlexNet, VGG, ResNet), transfer learning, data augmentation, and computer-vision tasks beyond classification.
A 224×224 colour image has 150,528 input values. A fully connected first layer with 1,000 neurons would need 150 million weights — and would treat a cat in the top-left corner as unrelated to the same cat in the bottom-right. Convolutional neural networks (CNNs) fix both problems by building in two facts about images:
- Locality: nearby pixels are related; useful patterns (edges, textures) are small.
- Translation equivariance: a pattern means the same thing wherever it appears.
Convolution
A filter (kernel) — a small grid of learnable weights, e.g. 3×3 — slides across the image. At each position, it computes a dot product with the patch underneath, producing one number in the output feature map.
import numpy as np
def conv2d(image, kernel):
kh, kw = kernel.shape
H, W = image.shape
out = np.zeros((H - kh + 1, W - kw + 1))
for i in range(out.shape[0]):
for j in range(out.shape[1]):
out[i, j] = (image[i:i+kh, j:j+kw] * kernel).sum() # dot product with the patch
return outKey properties:
- Weight sharing: the same filter is used at every position — a 3×3×3 filter has just 27 weights (+1 bias), regardless of image size.
- A layer has many filters (e.g. 64), each detecting a different pattern; their outputs stack into a 3-D tensor of channels.
- Filters aren't designed by hand — they're learned by backpropagation.
Stride, padding and output size
| Parameter | Effect |
|---|---|
| Kernel size k | Usually 3×3 (stacking two 3×3 layers sees as far as one 5×5, with fewer weights) |
| Stride s | Step between positions; stride 2 halves the resolution |
| Padding p | Zeros added at the border; "same" padding keeps the size |
A 32×32 input, 3×3 kernel, padding 1, stride 1 → 32×32. Stride 2 → 16×16.
Pooling
Max pooling (typically 2×2, stride 2) keeps the largest value in each window: it halves resolution, adds a little translation invariance, and reduces computation. Modern networks often use strided convolutions instead, and end with global average pooling (average each channel to one number) before the classifier.
The hierarchy of features
Each layer's receptive field — the region of the input that can influence one unit — grows with depth, so deeper layers combine local patterns into larger structures.
A CNN in PyTorch
import torch
from torch import nn
class SmallCNN(nn.Module):
def __init__(self, num_classes=10):
super().__init__()
def block(cin, cout):
return nn.Sequential(
nn.Conv2d(cin, cout, kernel_size=3, padding=1), nn.BatchNorm2d(cout), nn.ReLU(),
nn.Conv2d(cout, cout, kernel_size=3, padding=1), nn.BatchNorm2d(cout), nn.ReLU(),
nn.MaxPool2d(2),
)
self.features = nn.Sequential(block(3, 32), block(32, 64), block(64, 128)) # 32→16→8→4
self.head = nn.Sequential(nn.AdaptiveAvgPool2d(1), nn.Flatten(),
nn.Dropout(0.3), nn.Linear(128, num_classes))
def forward(self, x): # x: (batch, 3, 32, 32)
return self.head(self.features(x))
model = SmallCNN()
print(sum(p.numel() for p in model.parameters())) # ≈ 290k parameters — ~90% accuracy on CIFAR-10Landmark architectures
| Model | Year | Contribution |
|---|---|---|
| LeNet-5 | 1998 | Conv + pool + dense; read handwritten digits on cheques |
| AlexNet | 2012 | Won ImageNet by a huge margin using GPUs, ReLU and dropout — started the deep learning boom |
| VGG | 2014 | Very deep stacks of simple 3×3 convolutions |
| GoogLeNet / Inception | 2014 | Parallel filters of several sizes; 1×1 convolutions to cut channels |
| ResNet | 2015 | Residual connections made 50–150+ layers trainable; surpassed human-level ImageNet error |
| MobileNet, EfficientNet | 2017–19 | Depthwise-separable convolutions and compound scaling for phones and efficiency |
| ConvNeXt | 2022 | Modernised CNNs competitive with vision transformers |
Residual blocks compute : layers learn a correction to the identity, and gradients flow through the shortcut (Backpropagation). This idea now underpins nearly every deep architecture, including transformers.
Vision Transformers (ViT) split images into patches and apply attention; with enough data they match or beat CNNs, and multimodal LLMs use them as image encoders. CNNs remain excellent and efficient, especially on smaller datasets and edge devices.
Transfer learning
Training from scratch needs millions of labelled images. Instead, start from a model pretrained on ImageNet (or a large self-supervised model) — its early layers already detect generic visual features — and fine-tune it:
import torch
from torch import nn
from torchvision import models
model = models.resnet50(weights=models.ResNet50_Weights.DEFAULT)
for p in model.parameters():
p.requires_grad = False # 1. freeze the pretrained backbone
model.fc = nn.Linear(model.fc.in_features, 5) # 2. new head for 5 classes (e.g. plant diseases)
# train the head; optionally 3. unfreeze later layers and fine-tune with a small learning rateWith a few hundred to a few thousand images per class, transfer learning routinely achieves strong accuracy.
Data augmentation
Random, label-preserving transformations generate more varied training data and reduce overfitting:
from torchvision import transforms
train_tf = transforms.Compose([
transforms.RandomResizedCrop(224, scale=(0.7, 1.0)),
transforms.RandomHorizontalFlip(),
transforms.ColorJitter(0.2, 0.2, 0.2),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), # ImageNet statistics
])Choose augmentations that make sense for the domain (flipping is fine for cats, not for digits like 6/9 or text).
Vision tasks
| Task | Output | Models |
|---|---|---|
| Classification | One label per image | ResNet, EfficientNet, ViT |
| Object detection | Boxes + labels | YOLO, Faster R-CNN, DETR |
| Semantic segmentation | A class per pixel | U-Net, DeepLab |
| Instance segmentation | A mask per object | Mask R-CNN, SAM (Segment Anything) |
| Image generation | New images | Diffusion models (with U-Net or transformer backbones) |
| Image embeddings / retrieval | Vectors for similarity search | CLIP, DINOv2 |
CNNs also apply beyond images: 1-D convolutions for audio and time series, and 3-D convolutions for video and medical scans.
- CNNs exploit locality and translation equivariance with small shared filters that slide over the image.
- Convolutions produce feature maps; stride and pooling reduce resolution; channels hold different learned features.
- Deeper layers have larger receptive fields and detect increasingly abstract features.
- ResNet's residual connections made very deep networks trainable — an idea now used everywhere.
- Transfer learning from pretrained models plus data augmentation works with modest datasets.
- Vision tasks include classification, detection, segmentation and generation; vision transformers are a strong alternative.