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.

Intermediate 4 min readLesson 9 of 14

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.

10-120-210-1
A 3×3 vertical-edge (Sobel) filter: responds strongly where brightness changes from left to right
Python
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 out

Key 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

ParameterEffect
Kernel size kUsually 3×3 (stacking two 3×3 layers sees as far as one 5×5, with fewer weights)
Stride sStep between positions; stride 2 halves the resolution
Padding pZeros added at the border; "same" padding keeps the size
output size=⌊n+2p−ks⌋+1\text{output size} = \left\lfloor \frac{n + 2p - k}{s} \right\rfloor + 1

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

Early layersedges, colours, simple texturesMiddle layerscorners, patterns, parts (eyes, wheels, fur)Deep layersobject-level concepts (faces, cars, dogs)Classifier headglobal pooling → dense → softmax over classes

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

Python
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-10

Landmark architectures

ModelYearContribution
LeNet-51998Conv + pool + dense; read handwritten digits on cheques
AlexNet2012Won ImageNet by a huge margin using GPUs, ReLU and dropout — started the deep learning boom
VGG2014Very deep stacks of simple 3×3 convolutions
GoogLeNet / Inception2014Parallel filters of several sizes; 1×1 convolutions to cut channels
ResNet2015Residual connections made 50–150+ layers trainable; surpassed human-level ImageNet error
MobileNet, EfficientNet2017–19Depthwise-separable convolutions and compound scaling for phones and efficiency
ConvNeXt2022Modernised CNNs competitive with vision transformers

Residual blocks compute y=x+F(x)\mathbf{y} = \mathbf{x} + F(\mathbf{x}): 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:

Python
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 rate

With 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:

Python
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

TaskOutputModels
ClassificationOne label per imageResNet, EfficientNet, ViT
Object detectionBoxes + labelsYOLO, Faster R-CNN, DETR
Semantic segmentationA class per pixelU-Net, DeepLab
Instance segmentationA mask per objectMask R-CNN, SAM (Segment Anything)
Image generationNew imagesDiffusion models (with U-Net or transformer backbones)
Image embeddings / retrievalVectors for similarity searchCLIP, DINOv2

CNNs also apply beyond images: 1-D convolutions for audio and time series, and 3-D convolutions for video and medical scans.

Key takeaways
  • 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.