AnyLearn
All lessons
AIintermediate

Convolutional Neural Networks

Understand why fully-connected layers fail at image scale, then build up the CNN toolkit: convolutions, kernels, stride, padding, feature maps, pooling, and parameter sharing. Finish with the ResNet residual connection idea that unlocked networks of 100+ layers.

Updated · AI-authored, review-gated · how lessons are made

Not signed in: your progress and quiz score won't be saved.
Progress1 / 9

Why fully-connected layers fail on images

A 224×224 RGB image has 224×224×3=150,528224 \times 224 \times 3 = 150{,}528 input values. A fully-connected (FC) hidden layer with 1024 neurons would require 150,528×1024154150{,}528 \times 1024 \approx 154 million parameters — for a single layer. Problems:

  • Parameter explosion: you run out of memory before the network gets interesting.
  • No spatial inductive bias: FC layers treat pixel (0, 0) and pixel (100, 100) as unrelated — they know nothing about locality.
  • No translation invariance: a cat in the top-left corner activates completely different weights than the same cat in the bottom-right corner.

Images are not arbitrary 1D vectors. Nearby pixels are strongly correlated, and the same pattern (edge, texture) can appear anywhere. The convolution operation exploits exactly this structure.

Full lesson text

All 9 steps on one page, for reading, reference, and search.

Show

1. Why fully-connected layers fail on images

A 224×224 RGB image has 224×224×3=150,528224 \times 224 \times 3 = 150{,}528 input values. A fully-connected (FC) hidden layer with 1024 neurons would require 150,528×1024154150{,}528 \times 1024 \approx 154 million parameters — for a single layer. Problems:

  • Parameter explosion: you run out of memory before the network gets interesting.
  • No spatial inductive bias: FC layers treat pixel (0, 0) and pixel (100, 100) as unrelated — they know nothing about locality.
  • No translation invariance: a cat in the top-left corner activates completely different weights than the same cat in the bottom-right corner.

Images are not arbitrary 1D vectors. Nearby pixels are strongly correlated, and the same pattern (edge, texture) can appear anywhere. The convolution operation exploits exactly this structure.

2. The convolution operation

A 2D convolution slides a small filter KRk×kK \in \mathbb{R}^{k \times k} over the input II and computes a dot product at each position:

(IK)[i,j]=m=0k1n=0k1I[i+m,j+n]K[m,n](I * K)[i, j] = \sum_{m=0}^{k-1} \sum_{n=0}^{k-1} I[i+m,\, j+n] \cdot K[m, n]

The filter detects a pattern; the output — called a feature map — encodes where that pattern appears. Each value in the feature map requires only k2k^2 multiplications, regardless of image size.

import torch
import torch.nn as nn

# 3-channel input, 16 filters of size 3x3
conv = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, padding=1)
x = torch.randn(1, 3, 224, 224)  # (batch, channels, H, W)
out = conv(x)  # shape: (1, 16, 224, 224) with padding='same'

The 16 filters learn 16 different feature detectors. The first layers typically learn Gabor-like edge detectors; deeper layers learn complex semantic patterns.

3. Stride, padding, and output size

Two hyperparameters control the spatial extent of the output:

Stride (ss): how many pixels the filter moves at each step. s=1s=1 produces a dense output; s=2s=2 halves spatial dimensions (common for downsampling without pooling).

Padding (pp): zeros added around the input border. padding=1 with a 3×33 \times 3 kernel preserves spatial size.

Output size formula for input size HH, kernel kk, stride ss, padding pp:

Hout=H+2pks+1H_{\text{out}} = \left\lfloor \frac{H + 2p - k}{s} \right\rfloor + 1

InputKernelStridePaddingOutput
224311224
224321112
224723112

The 7×7, stride-2 pattern in ResNet's first layer aggressively shrinks the feature map early, reducing compute for the rest of the network.

4. Parameter sharing and translation equivariance

A single filter has k2×Cink^2 \times C_{\text{in}} parameters, shared across every spatial position. This is the key savings: a 3×33 \times 3 filter applied to a 224×224224 \times 224 input has only 3×3×Cin3 \times 3 \times C_{\text{in}} weights, not 2242×Cin224^2 \times C_{\text{in}}.

Translation equivariance: if the input shifts by (Δi,Δj)(\Delta i, \Delta j), the feature map shifts by the same amount — the detected pattern follows the object. Formally: (shift(I))K=shift(IK)(\text{shift}(I)) * K = \text{shift}(I * K).

This is equivariance, not invariance — the output changes, but in a predictable way. True translation invariance (same output regardless of position) comes from pooling.

Parameter sharing also provides regularization: the filter is forced to be useful everywhere, not just at one location. This is a strong inductive bias for spatially stationary patterns like textures and edges.

5. Pooling: building translation invariance

Pooling summarizes a local region into a single value, discarding exact position and reducing spatial size:

  • Max pooling (2×2, stride 2): takes the maximum of each 2×2 block. Halves HH and WW. Retains the presence of a feature, ignoring exact location — providing local translation invariance.
  • Average pooling: takes the mean. Smoother but less discriminative.
  • Global average pooling (GAP): averages all spatial positions into a single value per channel. Replaces a large FC layer at the network head, used in ResNet and MobileNet.
# Max pooling: 224x224 -> 112x112
pool = nn.MaxPool2d(kernel_size=2, stride=2)

# Global average pooling: (B, C, H, W) -> (B, C, 1, 1)
gap = nn.AdaptiveAvgPool2d(1)
features = gap(x).squeeze(-1).squeeze(-1)  # (B, C)

Modern architectures (EfficientNet, Vision Transformer) often drop max pooling in favor of strided convolutions, which are learned rather than fixed.

6. A typical CNN architecture

The classic pattern is: repeated Conv → BN → ReLU → Pool blocks, followed by a classifier head.

class SimpleCNN(nn.Module):
    def __init__(self, num_classes=10):
        super().__init__()
        self.features = nn.Sequential(
            nn.Conv2d(3, 32, 3, padding=1), nn.BatchNorm2d(32), nn.ReLU(),
            nn.MaxPool2d(2),                   # 112x112
            nn.Conv2d(32, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(),
            nn.MaxPool2d(2),                   # 56x56
            nn.Conv2d(64, 128, 3, padding=1), nn.BatchNorm2d(128), nn.ReLU(),
            nn.AdaptiveAvgPool2d(1),           # 1x1
        )
        self.classifier = nn.Linear(128, num_classes)

    def forward(self, x):
        x = self.features(x).squeeze(-1).squeeze(-1)
        return self.classifier(x)

Depth increases (32 → 64 → 128 channels) while spatial dimensions shrink — a hallmark of all CNN designs. Channels encode what, spatial positions encode where.

7. CNN data flow from image to class

Spatial dimensions shrink; channel depth grows toward the classifier.

flowchart LR
  IMG["Image 3 x 224 x 224"]
  C1["Conv 32 x 224 x 224"]
  P1["Pool 32 x 112 x 112"]
  C2["Conv 64 x 112 x 112"]
  P2["Pool 64 x 56 x 56"]
  C3["Conv 128 x 56 x 56"]
  GAP["GlobalAvgPool 128"]
  FC["Linear -> num_classes"]
  IMG --> C1 --> P1 --> C2 --> P2 --> C3 --> GAP --> FC

8. Residual connections and ResNet

As networks grew deeper (50, 100, 152 layers), a paradox emerged: deeper networks performed worse than shallower ones — not from overfitting but from optimization failure. Gradients vanished before reaching early layers.

He et al. (2015) introduced the residual connection:

y=F(x,{Wi})+x\mathbf{y} = F(\mathbf{x}, \{W_i\}) + \mathbf{x}

where FF is a stack of layers (e.g., Conv → BN → ReLU → Conv → BN). The +x+\mathbf{x} skip connection lets the gradient flow directly backward through the identity path:

Lx=Ly(1+Fx)\frac{\partial \mathcal{L}}{\partial \mathbf{x}} = \frac{\partial \mathcal{L}}{\partial \mathbf{y}}\left(1 + \frac{\partial F}{\partial \mathbf{x}}\right)

Even if F/x0\partial F/\partial \mathbf{x} \approx 0, the gradient is at least L/y\partial \mathcal{L}/\partial \mathbf{y} — it never vanishes completely. The network learns the residual F(x)F(\mathbf{x}) rather than the full transformation, which is an easier optimization problem when F0F \approx 0 is a good starting point (identity shortcut).

9. Comparing classic CNN architectures

The evolution of CNN design encodes hard-won lessons:

ArchitectureYearDepthTop-1 (ImageNet)Key innovation
AlexNet2012863.3%Deep conv on GPU, ReLU, dropout
VGG-1620141674.4%Uniform 3×3 convolutions, depth
GoogLeNet20142274.8%Inception module, 1×1 conv
ResNet-5020155076.1%Residual connections
EfficientNet-B0201923777.1%Compound scaling (width/depth/res)

Key takeaways: small 3×3 kernels stack cheaper than one large kernel (VGG). 1×1 convolutions reduce channel depth before expensive 3×3 convs (bottleneck). Residual connections are now standard in almost all deep architectures, including transformers.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. For a 224×224 input, a Conv2d with kernel_size=3, stride=2, padding=1 produces an output of what spatial size?
    • 224×224
    • 112×112
    • 111×111
    • 56×56
  2. What is the key benefit of parameter sharing in convolutional layers?
    • It allows the network to learn a different filter for each spatial position, increasing expressiveness.
    • It forces the same filter weights to be used everywhere, dramatically reducing parameters and providing a useful inductive bias for spatially stationary patterns.
    • It makes backpropagation unnecessary since all parameters are shared.
    • It ensures the output feature map is always the same size as the input.
  3. What is the difference between translation equivariance and translation invariance in CNNs?
    • They are the same property — convolutions produce both simultaneously.
    • Equivariance means the output shifts when the input shifts; invariance means the output stays the same regardless of shift. Convolutions provide equivariance; pooling provides local invariance.
    • Invariance means the output shifts predictably; equivariance means the output is constant.
    • Equivariance applies to depth changes; invariance applies to spatial changes.
  4. ResNet's residual connection $\mathbf{y} = F(\mathbf{x}) + \mathbf{x}$ primarily solves which problem?
    • Overfitting in shallow networks by adding an implicit L2 penalty.
    • The vanishing gradient problem in very deep networks by providing a direct gradient path through the identity shortcut.
    • The dying ReLU problem by ensuring activations are never zero.
    • The parameter explosion problem by sharing weights between the residual branch and the skip connection.
  5. Global average pooling (GAP) at the network head replaces large fully-connected layers. What is the main advantage?
    • It retains exact spatial information needed for the classification decision.
    • It dramatically reduces parameters (from $H \times W \times C$ FC weights to $C$ channels) and provides implicit regularization by averaging spatial information.
    • It makes the network translation-equivariant, unlike FC layers.
    • It increases the gradient flow compared to FC layers with dropout.

Related lessons

AI
advanced

Architectures for Order Book Data, and Why They Help Less Than Expected

Convolutional and recurrent networks have been applied to order book data with published success, and the architectures encode real assumptions about the book's structure. This lesson explains what each one assumes, why the gains over simple baselines are smaller than headline numbers suggest, and where the modelling effort is better spent.

10 steps·~15 min
AI
advanced

Evaluating a Book Model Honestly

If your cost per round trip equals the move you are trying to capture, you need 100 percent directional accuracy to break even. This lesson computes that hurdle, replaces accuracy with metrics tied to a tradeable decision, and covers the capacity and latency limits that decide whether a real edge is worth anything.

10 steps·~15 min
AI
advanced

Why Reported Order Book Results Do Not Replicate

At a one-event horizon, 92 percent of mid-price labels are exactly no-change, so a model that always predicts flat scores 92 percent accuracy. This lesson computes that baseline across horizons and works through the four mechanisms that turn a genuine measurement into a number nobody can reproduce.

10 steps·~15 min
AI
advanced

What Is Actually in an Order Book, and What a Model Can See

Before choosing an architecture you have to decide what the input is, and an order book offers several incompatible representations that are not equally informative. This lesson covers what each data level contains, why raw prices are the wrong features, and the representation choices that decide more than the model does.

10 steps·~15 min