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.

Not signed in โ€” your progress and quiz score won't be saved.
Lesson 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ร—1024โ‰ˆ154150{,}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ร—1024โ‰ˆ154150{,}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 KโˆˆRkร—kK \in \mathbb{R}^{k \times k} over the input II and computes a dot product at each position:

(Iโˆ—K)[i,j]=โˆ‘m=0kโˆ’1โˆ‘n=0kโˆ’1I[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+2pโˆ’ksโŒ‹+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(Iโˆ—K)(\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:

โˆ‚Lโˆ‚x=โˆ‚Lโˆ‚y(1+โˆ‚Fโˆ‚x)\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/โˆ‚xโ‰ˆ0\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 Fโ‰ˆ0F \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