Jaber Notes · 13 of 16
CNNs
Convolution math, receptive fields, ResNet, transfer learning, detection.
Convolutional networks for vision: the 2D convolution math, output-size and receptive-field formulas, depthwise-separable cost analysis, backprop through convolutions, the landmark architectures, transfer learning, and detection/segmentation.
Visual reference
Forward pass through a network
The architecture behind nearly all computer vision breakthroughs. Understand the math of convolution, the design principles, and the landmark architectures.
Table of contents
- Motivation: why convolutions for images
- Discrete convolution (math)
- Convolutional layer parameters and output size
- Pooling layers
- Receptive field
- Backpropagation through convolution
- CNN building blocks: BatchNorm, activation, skip connections
- Landmark architectures
- Transfer learning and fine-tuning
- Object detection and segmentation (concepts)
1. Motivation: why convolutions for images
1.1 Problems with fully connected networks on images
A image has 150K pixels. A single FC layer mapping to 1000 hidden units has parameters — and that's one layer.
Worse: FC layers treat every pixel independently. They ignore the spatial structure of images: nearby pixels are correlated, patterns (edges, textures) appear in multiple locations.
1.2 Two key inductive biases
Translation equivariance: if a pattern (e.g., an edge) appears at position or , the same detector should fire. Convolutions achieve this by sharing the same filter weights across all positions.
Locality: nearby pixels are more related than far-away pixels. Convolutions use small filters (e.g., ) to capture local patterns.
These two biases hugely reduce parameters and encode useful image priors.
2. Discrete convolution (math)
2.1 1D convolution
For input and filter :
In signal processing, true convolution flips the kernel: . In deep learning the term "convolution" is used loosely — most frameworks implement cross-correlation (no flip). Since filters are learned, the flip doesn't matter.
2.2 2D convolution (single channel)
Input , filter :
Output size (no padding, stride 1): .
2.3 Multi-channel convolution
Input ( channels), filter ( filters):
Output .
Parameters per conv layer: (bias).
3. Convolutional layer parameters and output size
3.1 Padding
Adding zeros around the input border.
- Valid (no padding): output shrinks by per side.
- Same padding: output size = input size. Padding for odd .
3.2 Stride
Step size when sliding the filter.
Output spatial size (one dimension, e.g., height):
where = padding, = stride.
Example: , , , → (same size). With : (halved).
3.3 Dilation (atrous convolution)
Insert gaps between filter elements: with dilation , filter covers a spatial range of .
Output size: .
Effect: expands receptive field without increasing parameters or losing resolution. Used in semantic segmentation (DeepLab), WaveNet.
3.4 Depthwise separable convolution
Standard conv : multiplications.
Depthwise separable (MobileNet idea):
- Depthwise conv: apply one filter per input channel independently. Params: .
- Pointwise conv: convolution to mix channels. Params: .
Cost reduction factor: . For : ~ fewer multiplications.
3.5 1×1 convolution
: acts as a pointwise linear combination of channels at each spatial location. Used to:
- Change number of channels (up- or down-project).
- Add nonlinearity without changing spatial size.
- Bottleneck in ResNets (reduce channels before expensive conv).
4. Pooling layers
4.1 Max pooling
Takes max over a local region:
Backprop: gradient passed only to the location that achieved the maximum (others get 0). Uses a "switch" mask stored during forward pass.
4.2 Average pooling
Global average pooling (GAP): pool over entire spatial dimension → one value per channel. Replaces large FC layers at classifier head in modern architectures (ResNet, EfficientNet).
Why GAP beats FC: fewer parameters, translation invariant, acts as structural regularizer.
4.3 Strided convolution vs pooling
Modern architectures (ResNets, Transformers) increasingly use strided convolutions instead of pooling for spatial downsampling. Learned downsampling can preserve more information.
5. Receptive field
5.1 Definition
The receptive field of a neuron = the region of the input that influences its value.
For a stack of conv layers each with kernel size and stride 1:
- Layer 1: receptive field = .
- Layer 2: each neuron at layer 2 sees a region of layer 1, each of which sees of input → total for stride 1.
Formula for layers of kernel , stride 1:
With stride (effective): .
5.2 Effective receptive field
In practice, not all pixels in the theoretical RF contribute equally. Neurons near the center contribute more. The effective RF is much smaller than the theoretical RF (approximately Gaussian-shaped). This motivates design choices like larger kernels, dilated convolutions, and pooling.
6. Backpropagation through convolution
6.1 Gradient w.r.t. input (needed for backprop through earlier layers)
This is a convolution of the output gradient with the flipped kernel — i.e., a transposed convolution (deconvolution).
6.2 Gradient w.r.t. filters
Again a cross-correlation between input and output gradients.
7. CNN building blocks: BatchNorm, activation, skip connections
7.1 Standard block pattern
Input → Conv(3×3) → BN → ReLU → Conv(3×3) → BN → (+skip) → ReLU → Output7.2 ResNet residual block
where represents the two conv layers. If dimensions differ (stride 2), use a conv projection on the skip:
Why it works:
- Gradient highway: . The identity term ensures gradient flows even if .
- Easy to learn identity () early in training.
- Enables training of very deep networks (50, 100, 1000+ layers).
7.3 Bottleneck block (ResNet-50+)
Reduce channels with , then , then expand with :
Input(256) → 1×1 Conv → 64ch → 3×3 Conv → 64ch → 1×1 Conv → 256ch → + skipReduces computation by ~4× vs non-bottleneck for same channel count.
8. Landmark architectures
8.1 LeNet-5 (LeCun, 1998)
First successful deep CNN for digit recognition. Pattern: Conv → Pool → Conv → Pool → FC → FC → Output. Established the basic design.
8.2 AlexNet (Krizhevsky et al., 2012)
Won ImageNet ILSVRC 2012 with top-5 error 15.3% (vs 26.2% previous year). Key innovations:
- ReLU activations (first large-scale use).
- Dropout in FC layers.
- Data augmentation (crops, flips).
- Multi-GPU training.
- Local Response Normalization (now obsolete, replaced by BN).
8.3 VGGNet (Simonyan & Zisserman, 2014)
Insight: replace large kernels with stacks of small convs. Two convs have the same receptive field as one but fewer parameters ( vs ) and an extra nonlinearity. VGG-16/19 became standard feature extractors.
8.4 GoogLeNet / Inception (Szegedy et al., 2014)
Inception module: apply , , convolutions and max pooling in parallel; concatenate outputs along channel dimension. Captures features at multiple scales simultaneously.
bottlenecks reduce channel count before expensive larger convolutions.
8.5 ResNet (He et al., 2015)
Residual connections (see §7.2). Enabled training of 152-layer networks. ResNet-50/101/152 are still widely used. Key insight: depth matters — deeper networks consistently better if we can train them.
8.6 DenseNet (Huang et al., 2017)
Each layer connected to all subsequent layers (not just the next):
where denotes channel concatenation. Dense connectivity: maximum feature reuse, strong gradient flow, few parameters. Good when data is limited.
8.7 EfficientNet (Tan & Le, 2019)
Compound scaling: scale width (), depth (), and resolution () simultaneously via a scaling coefficient :
Subject to (FLOP constraint). Achieved state-of-the-art with fewer parameters.
8.8 Architecture evolution summary
| Model | Year | Top-5 Error | Params | Key idea |
|---|---|---|---|---|
| AlexNet | 2012 | 15.3% | 60M | ReLU, Dropout |
| VGG-16 | 2014 | 7.3% | 138M | Small 3×3 filters |
| GoogLeNet | 2014 | 6.7% | 7M | Inception module |
| ResNet-50 | 2015 | 3.57% | 25M | Residual connections |
| DenseNet | 2017 | ~3% | 8M | Dense connectivity |
| EfficientNet-B7 | 2019 | 1.8% | 66M | Compound scaling |
| ViT (transformer) | 2020 | 1.5% | 86M+ | No convolutions |
9. Transfer learning and fine-tuning
9.1 The idea
Train on large dataset (ImageNet: 1.2M images, 1000 classes), then transfer learned features to a new task.
Why it works: early layers learn general features (edges, textures, blobs) that are useful across tasks. Later layers become task-specific.
9.2 Strategies
| Strategy | When | How |
|---|---|---|
| Feature extraction | Small target dataset, similar domain | Freeze backbone; train only new head |
| Fine-tuning | Medium target dataset | Unfreeze top layers (or all); use small LR |
| Full fine-tuning | Large target dataset | Unfreeze all; LR 10–100× smaller than scratch |
| Linear probing | Evaluate representation quality | Train only linear classifier on frozen features |
9.3 Learning rate for fine-tuning
Use discriminative learning rates: lower LR for early (general) layers, higher for later (task-specific) layers:
9.4 Domain gap matters
Transferring from ImageNet to medical images: gap is large (natural RGB vs X-ray). May need more fine-tuning epochs, or pre-training on domain-specific data.
9.5 Code example
import torch
import torch.nn as nn
import torchvision.models as models
# Load pretrained ResNet-50
model = models.resnet50(weights='IMAGENET1K_V1')
# Option 1: Feature extraction — freeze all
for param in model.parameters():
param.requires_grad = False
# Replace final FC layer for new task (e.g., 10 classes)
num_features = model.fc.in_features
model.fc = nn.Linear(num_features, 10) # only this layer trains
# Option 2: Fine-tune all — use small LR
for param in model.parameters():
param.requires_grad = True
# Use optimizer with LR ~1e-4 (much smaller than scratch ~1e-1)
optimizer = torch.optim.Adam([
{'params': model.layer4.parameters(), 'lr': 1e-4},
{'params': model.fc.parameters(), 'lr': 1e-3},
])10. Object detection and segmentation (concepts)
10.1 Task definitions
| Task | Output | Example metrics |
|---|---|---|
| Image classification | Class label | Top-1/Top-5 accuracy |
| Object detection | Bounding boxes + class per object | mAP (mean Average Precision) |
| Semantic segmentation | Class per pixel | mIoU |
| Instance segmentation | Mask per instance | AP-mask |
| Panoptic segmentation | Unified mask (things + stuff) | PQ (Panoptic Quality) |
10.2 Two-stage detectors (R-CNN family)
R-CNN: region proposals → CNN features per region → classifier. Fast R-CNN: CNN features for whole image → ROI pooling extracts region features. Faster R-CNN: replaces selective search with Region Proposal Network (RPN) — a small CNN that outputs objectness scores and box proposals from feature map.
RPN loss:
where = objectness score, = box regression offsets.
10.3 One-stage detectors
YOLO (You Only Look Once): divide image into grid. Each cell predicts boxes and class probabilities in one pass.
SSD (Single Shot Detector): default boxes at multiple scales from different feature map levels.
One-stage vs two-stage:
- Two-stage: better accuracy, slower.
- One-stage: faster (real-time possible), slightly lower accuracy (modern ones close the gap).
10.4 Semantic segmentation
Fully Convolutional Network (FCN): replace FC layers with convs → output spatial map. Upsampling via transposed convolution or bilinear interpolation.
U-Net: encoder-decoder with skip connections between encoder and decoder at same resolution. Enables precise localization. Dominant in medical imaging.
DeepLab: dilated convolutions for large receptive field without downsampling. Atrous Spatial Pyramid Pooling (ASPP): parallel dilated convs with different dilation rates → multi-scale features.
10.5 IoU (Intersection over Union)
Standard metric for boxes/masks:
mAP = mean AP over classes, where AP is area under precision-recall curve at IoU threshold (e.g., 0.5, or averaged over 0.5:0.95).
*File: notes/13_cnns.md — next: notes/14_rnns_and_sequences.md*