Specialized neural networks for processing data with a grid-like topology, such as images. They use convolutional layers that apply filters to local regions of the input.
Author
Benedict Thekkel
Intuition: Local Receptive Fields, Parameter Sharing, Translation Invariance
A Convolutional Neural Network (CNN) is built for data with a grid topology, most famously images. Instead of connecting every input to every neuron (as an MLP does), a CNN exploits three key ideas:
Local receptive fields: each neuron looks only at a small spatial neighborhood (e.g. a 3x3 patch). Nearby pixels are correlated, so local connectivity is a strong, useful prior.
Parameter sharing: the same small filter (set of weights) slides across the whole image. One 3x3x3 filter is just 27 weights regardless of image size, versus millions for a fully-connected layer. This dramatically reduces parameters and overfitting.
Translation invariance: because the filter is shared across positions, a feature (an edge, a texture) is detected wherever it appears. Combined with pooling, the network becomes robust to small shifts.
Early layers learn low-level features (edges, colors); deeper layers compose them into textures, parts, and eventually whole objects.
The Convolution Operation (By Hand)
A 2D convolution slides a small kernel (filter) over the input, and at each position computes the element-wise product summed over the patch (technically cross-correlation, which is what deep learning frameworks actually compute). For an input patch \(P\) and kernel \(K\) of the same size:
conv_same out: (1, 16, 32, 32) formula 32
conv_down out: (1, 16, 16, 16) formula 16
pool out: (1, 16, 16, 16)
dilated out: (1, 16, 32, 32)
Channels and Feature Maps
An RGB image has 3 input channels. A convolution with out_channels = 16 produces 16 feature maps, each the response of one learned filter to the whole image. Each filter has shape (in_channels, kH, kW) and there are out_channels of them, so the weight tensor is (out_channels, in_channels, kH, kW).
As we go deeper we typically increase channels (richer features) while shrinking spatial dimensions (via stride/pooling), trading spatial resolution for semantic depth.
Here is a compact LeNet-style classifier for 1x28x28 grayscale digits. A common pattern is repeated [Conv -> ReLU -> Pool] blocks to extract features, then flatten and pass through fully-connected layers to produce class logits. The forward method prints intermediate shapes so you can trace how spatial size shrinks and channels grow.
The receptive field of a neuron is the region of the original input that influences it. Stacking convolutions grows it: two 3x3 layers see a 5x5 region, three see 7x7. This is why deep stacks of small kernels (VGG-style) capture large context cheaply.
A 1x1 convolution has a kernel that looks at a single spatial location but mixes across channels. It is effectively a per-pixel fully-connected layer and is used to change the channel count (cheaply project up or down) and add non-linearity. It is a core building block of Inception and ResNet bottleneck layers.
x = torch.randn(2, 256, 16, 16) # (N, C=256, H, W)# 1x1 conv to reduce channels 256 -> 64 (a 'bottleneck'), spatial size unchangedreduce= nn.Conv2d(256, 64, kernel_size=1)y =reduce(x)print('after 1x1 reduce:', tuple(y.shape)) # (2, 64, 16, 16)# Parameter comparison: a 1x1 vs a 3x3 doing the same channel changep_1x1 =sum(p.numel() for p in nn.Conv2d(256, 64, 1).parameters())p_3x3 =sum(p.numel() for p in nn.Conv2d(256, 64, 3, padding=1).parameters())print('1x1 params:', p_1x1, ' 3x3 params:', p_3x3)
LeNet-5 (1998): the original ConvNet for digit recognition. Two conv+pool stages then fully-connected layers.
AlexNet (2012): deeper, ReLU activations, dropout, GPU training; won ImageNet and launched the deep learning era.
VGG (2014): very uniform design using only stacked 3x3 convolutions; simple but parameter-heavy.
ResNet (2015): introduced residual (skip) connections that let gradients flow through identity shortcuts, enabling networks 50-150+ layers deep without degradation.
Inception/GoogLeNet (2014): parallel branches with different kernel sizes (and 1x1 bottlenecks) concatenated together, capturing multi-scale features efficiently.
The residual block is the single most influential building block; here it is in PyTorch.
In CNNs, nn.BatchNorm2d normalizes each channel across the batch and spatial dimensions, then applies a learnable scale and shift per channel. It stabilizes and speeds up training, allows higher learning rates, and reduces sensitivity to initialization. The conventional ordering is Conv -> BatchNorm -> ReLU, and convs before a batchnorm usually set bias=False because the batchnorm already provides a learnable shift.
Rather than training from scratch, transfer learning reuses a model pretrained on a large dataset (e.g. ImageNet) and adapts it to a new task. The typical recipe: load a pretrained backbone, freeze most of its weights, and replace the final classification head with one sized to your number of classes. This needs far less data and compute.
import torch.nn as nnfrom torchvision import models# Load resnet18 pretrained on ImageNetresnet = models.resnet18(weights=models.ResNet18_Weights.DEFAULT)# Freeze all backbone parameters (feature extractor)for p in resnet.parameters(): p.requires_grad =False# Replace the final fully-connected head for, say, 5 classesnum_features = resnet.fc.in_features # 512 for resnet18resnet.fc = nn.Linear(num_features, 5) # new head, trainable by defaulttrainable = [n for n, p in resnet.named_parameters() if p.requires_grad]print('in_features :', num_features)print('trainable parts:', trainable) # only the new 'fc' layer
Data augmentation synthetically expands the training set by applying random, label-preserving transforms (flips, crops, color jitter, rotation). This improves generalization and is one of the cheapest, most effective regularizers for vision models. Augmentation is applied only to the training set; validation/test use deterministic preprocessing (resize, center crop, normalize).
Parameter sharing makes them efficient and data-efficient for images.
Built-in translation invariance and a strong spatial-locality prior.
Hierarchical feature learning from edges to objects; pretrained backbones transfer well.
Weaknesses
Limited global context per layer; long-range dependencies need deep stacks or attention.
Not naturally suited to non-grid data (sequences, graphs, sets).
Sensitive to large rotations/scale changes unless trained with augmentation.
Vision Transformers can outperform CNNs given very large datasets.
When to use
Images and video, spectrograms (audio as 2D), and any data with a grid structure where local patterns and translation invariance matter. For sequences and language, prefer RNNs or Transformers.
Key Takeaways
CNNs replace full connectivity with local receptive fields, parameter sharing, and translation invariance - ideal for grid-structured data like images.
Convolution slides a small learned kernel and computes element-wise products summed over each patch; output size follows \(O = \lfloor (W - K + 2P)/S \rfloor + 1\).
A filter spans all input channels; out_channels filters yield out_channels feature maps.
Typical design: stacked Conv -> BN -> ReLU -> Pool blocks, increasing channels while shrinking spatial size, then a fully-connected head.
1x1 convs mix channels cheaply; residual connections enable very deep networks.
BatchNorm stabilizes training; augmentation regularizes; transfer learning with a pretrained backbone is the practical default.
Reach for CNNs on vision tasks; use RNNs/Transformers for sequential data.