6.2 Convolutional Neural Networks (CNNs)
6.2 Convolutional Neural Networks (CNNs)
Key Concepts
6.2.1 Convolution Operation
Convolution is the core operation that gives CNNs their name. It applies a learnable filter (kernel) across the input to detect local patterns.
How Convolution Works
Input (5×5) Kernel (3×3) Output (3×3)
┌─────────────┐ ┌───────┐ ┌───────┐
│ 1 0 1 0 1 │ │ 1 0 1 │ │ 4 3 4 │
│ 0 1 0 1 0 │ * │ 0 1 0 │ = │ 2 4 3 │
│ 1 0 1 0 1 │ │ 1 0 1 │ │ 4 3 4 │
│ 0 1 0 1 0 │ └───────┘ └───────┘
│ 1 0 1 0 1 │
└─────────────┘
Element-wise multiply and sum at each positionMathematical Definition
For 2D convolution:
(I * K)[i,j] = ΣₘΣₙ I[i+m, j+n] × K[m, n]Where:
- I = input feature map
- K = kernel/filter
-
- = convolution operation
Key Properties
- Parameter sharing: Same kernel applied across entire input
- Local connectivity: Each output depends only on a local region
- Translation equivariance: Pattern detected regardless of position
Output Size Formula
Output_size = (Input_size - Kernel_size + 2×Padding) / Stride + 1Example: Input=32, Kernel=3, Padding=1, Stride=1
Output = (32 - 3 + 2×1) / 1 + 1 = 326.2.2 Stride and Padding
Stride
Stride controls how much the kernel moves between applications.
Stride = 1: Stride = 2:
┌─┬─┬─┬─┐ ┌─┬─┬─┬─┐
│●│●│●│ │ → 4 positions │●│ │●│ │ → 2 positions
├─┼─┼─┼─┤ ├─┼─┼─┼─┤
│●│●│●│ │ │ │ │ │ │
├─┼─┼─┼─┤ ├─┼─┼─┼─┤
│●│●│●│ │ │●│ │●│ │
└─┴─┴─┴─┘ └─┴─┴─┴─┘- Stride = 1: Dense output, preserves spatial resolution
- Stride > 1: Downsamples output, reduces computation
Padding
Padding adds zeros around the input border.
No padding (valid): Same padding:
Input: 5×5 Input: 5×5 + padding
Kernel: 3×3 Kernel: 3×3
Output: 3×3 Output: 5×5 (preserved)Types:
- Valid (no padding): Output shrinks
- Same: Output same size as input (pad = kernel_size // 2)
- Full: Output larger than input
6.2.3 Pooling
Pooling reduces spatial dimensions while retaining important features.
Max Pooling
Takes the maximum value in each window:
Input (4×4) Max Pool 2×2, stride 2 Output (2×2)
┌───┬───┬───┬───┐ ┌───┬───┐
│ 1 │ 3 │ 2 │ 1 │ │ 4 │ 6 │
├───┼───┼───┼───┤ → ├───┼───┤
│ 4 │ 2 │ 5 │ 6 │ │ 8 │ 9 │
├───┼───┼───┼───┤ └───┴───┘
│ 7 │ 8 │ 1 │ 2 │
├───┼───┼───┼───┤
│ 3 │ 5 │ 9 │ 4 │
└───┴───┴───┴───┘Average Pooling
Takes the average value in each window.
Global Average Pooling (GAP)
Averages entire feature map to a single value:
Feature map (H×W×C) → Vector (1×1×C)- Used before final classification layer
- Reduces parameters dramatically
- Acts as regularization
Why Pooling?
- Dimensionality reduction: Fewer parameters, less computation
- Translation invariance: Small shifts don't change output
- Larger receptive field: Each output "sees" more of input
6.2.4 CNN Architecture Components
A typical CNN consists of:
Input → [Conv → ReLU → Pool] × N → Flatten → FC → Output
└─────────────────┘
Feature extraction ClassificationReceptive Field
The region of input that affects a particular output neuron.
Layer 1 (3×3 conv): Receptive field = 3×3
Layer 2 (3×3 conv): Receptive field = 5×5
Layer 3 (3×3 conv): Receptive field = 7×7
Stacking small kernels → large receptive field with fewer parametersChannel Dimension
Input: H × W × C_in
Kernel: K × K × C_in × C_out
Output: H' × W' × C_out
Each output channel = one kernel applied across all input channels6.2.5 Classic Architectures
LeNet-5 (1998)
- First successful CNN for digit recognition
- Architecture: Conv → Pool → Conv → Pool → FC → FC → Output
- ~60K parameters
AlexNet (2012)
- Won ImageNet, sparked deep learning revolution
- Key innovations: ReLU, dropout, GPU training, data augmentation
- 8 layers, ~60M parameters
VGG (2014)
- Simple, uniform architecture
- Only 3×3 convolutions, 2×2 max pooling
- Deep: VGG-16 (16 layers), VGG-19 (19 layers)
- ~138M parameters (VGG-16)
VGG-16 Structure:
[Conv3-64]×2 → Pool → [Conv3-128]×2 → Pool → [Conv3-256]×3 → Pool
→ [Conv3-512]×3 → Pool → [Conv3-512]×3 → Pool → FC-4096 → FC-4096 → FC-1000Inception/GoogLeNet (2014)
- Parallel convolutions with different kernel sizes
- "Inception module": 1×1, 3×3, 5×5 convs + pooling in parallel
- 1×1 convolutions for dimensionality reduction
- ~5M parameters (efficient!)
Inception Module:
┌─→ [1×1 conv] ─────────────────┐
│ │
Input ───┼─→ [1×1 conv] → [3×3 conv] ────┼─→ Concat → Output
│ │
├─→ [1×1 conv] → [5×5 conv] ────┤
│ │
└─→ [3×3 pool] → [1×1 conv] ────┘ResNet (2015)
- Introduced skip connections (residual learning)
- Enabled training of very deep networks (50, 101, 152 layers)
- Won ImageNet 2015 with 3.57% top-5 error
Residual Block:
┌───────────────────┐
│ │
x ──────┼──→ [Conv] → [Conv] ──→ (+) → ReLU → output
│ ↑
└───────────────────┘
identity (skip connection)
Output = F(x) + xU-Net (2015)
- Encoder-decoder architecture for segmentation
- Skip connections between encoder and decoder
- Preserves fine-grained spatial information
6.2.6 Skip Connections (Residual Connections)
Skip connections allow gradients to flow directly through the network, bypassing layers.
The Problem They Solve
Degradation problem: Very deep networks perform worse than shallow ones (not due to overfitting).
Without skip connections:
- Gradients must flow through every layer
- Vanishing gradients in deep networks
- Hard to learn identity mappingsHow They Work
# Standard block
output = F(x)
# Residual block
output = F(x) + x # Learn the residual F(x) = H(x) - xWhy They Help
- Gradient highway: Gradients flow directly through skip connections
- Easier optimization: Learning residual (difference) is easier than full mapping
- Identity mapping: If optimal, network can learn F(x) = 0
- Ensemble effect: Creates implicit ensemble of shallow networks
Types of Skip Connections
Identity shortcut: Projection shortcut:
(when dimensions match) (when dimensions differ)
x ──┬──→ F(x) ──→ (+) x ──┬──→ F(x) ──────→ (+)
│ ↑ │ ↑
└────────────┘ └──→ [1×1 conv] ──┘6.2.7 Transfer Learning and Fine-tuning
Transfer learning leverages knowledge from one task to improve performance on another.
Why Transfer Learning?
- Limited data: Your dataset is small
- Faster training: Start from good weights
- Better performance: Pretrained features are powerful
- Lower compute: Don't train from scratch
Approaches
1. Feature Extraction (Freeze backbone)
# Load pretrained model
model = ResNet50(weights='imagenet')
# Freeze all layers
for param in model.parameters():
param.requires_grad = False
# Replace final layer
model.fc = nn.Linear(2048, num_classes)
# Train only the new layer2. Fine-tuning (Unfreeze some/all layers)
# Load pretrained model
model = ResNet50(weights='imagenet')
# Replace final layer
model.fc = nn.Linear(2048, num_classes)
# Fine-tune with lower learning rate
optimizer = Adam([
{'params': model.layer4.parameters(), 'lr': 1e-4},
{'params': model.fc.parameters(), 'lr': 1e-3}
])When to Use What
| Scenario | Data Size | Similarity to Pretrained | Strategy |
|---|---|---|---|
| Small data, similar task | Small | High | Feature extraction |
| Small data, different task | Small | Low | Feature extraction (early layers) |
| Large data, similar task | Large | High | Fine-tune all |
| Large data, different task | Large | Low | Fine-tune or train from scratch |
Layer-wise Learning Rates
Earlier layers learn general features (edges, textures) → lower learning rate Later layers learn task-specific features → higher learning rate
Layer 1-2: lr = 1e-5 (general features, keep mostly frozen)
Layer 3-4: lr = 1e-4 (mid-level features)
Layer 5+: lr = 1e-3 (task-specific, adapt more)Questions & Answers
⭐ Q1: How does a Convolutional Neural Network (CNN) work?
Answer:
CNNs are specialized neural networks designed for grid-like data (images, sequences) that exploit spatial structure through three key ideas:
1. Local Connectivity
- Each neuron connects only to a local region (receptive field)
- Captures local patterns like edges, textures
- Reduces parameters compared to fully connected layers
2. Parameter Sharing
- Same filter (kernel) applied across entire input
- A 3×3 filter has only 9 parameters regardless of image size
- Detects the same pattern anywhere in the image
3. Translation Equivariance
- If input shifts, output shifts correspondingly
- Pattern detected regardless of position
Architecture:
Input Image
↓
[Convolution + ReLU] → Detect low-level features (edges)
↓
[Pooling] → Reduce spatial size, add invariance
↓
[Convolution + ReLU] → Detect mid-level features (textures, parts)
↓
[Pooling]
↓
[Convolution + ReLU] → Detect high-level features (objects)
↓
[Global Average Pooling or Flatten]
↓
[Fully Connected] → Classification
↓
Output (class probabilities)Key operations:
- Convolution: Slide kernel over input, compute dot products
- Activation (ReLU): Introduce non-linearity
- Pooling: Downsample, add translation invariance
- Batch Normalization: Stabilize training
Why CNNs work for images:
- Exploit spatial hierarchy (pixels → edges → textures → parts → objects)
- Dramatically fewer parameters than fully connected (parameter sharing)
- Built-in translation invariance through pooling
Q2: What is a U-Net architecture, and what novel features does it offer?
Answer:
U-Net is an encoder-decoder architecture designed for semantic segmentation, particularly in biomedical imaging.
Architecture:
Input Image
│
▼
┌─────────┐
│ Encoder │ ──────────────────────────────┐ (skip connection)
│ (down) │ │
├─────────┤ │
│ Encoder │ ────────────────────┐ │
│ │ │ │
├─────────┤ │ │
│ Encoder │ ──────────┐ │ │
│ │ │ │ │
├─────────┤ │ │ │
│Bottleneck│ │ │ │
├─────────┤ │ │ │
│ Decoder │ ←─────────┘ concat │ │
│ (up) │ │ │
├─────────┤ │ │
│ Decoder │ ←───────────────────┘ concat │
│ │ │
├─────────┤ │
│ Decoder │ ←─────────────────────────────┘ concat
└─────────┘
│
▼
Segmentation Map (same size as input)Novel Features:
-
Symmetric encoder-decoder structure
- Encoder: Captures context (what)
- Decoder: Enables precise localization (where)
- U-shaped architecture gives it the name
-
Skip connections between encoder and decoder
- Concatenate encoder features with decoder features
- Preserves fine-grained spatial information lost during downsampling
- Enables precise boundary detection
-
Works with limited training data
- Originally designed for biomedical images (few samples)
- Data augmentation (elastic deformations) helps
- Skip connections reduce need for large datasets
-
Pixel-wise output
- Output same resolution as input
- Each pixel gets a class label
Why skip connections matter in U-Net:
- Pooling loses spatial information
- Skip connections recover this information
- Combines "what" (deep features) with "where" (shallow features)
Applications:
- Medical image segmentation (tumors, organs, cells)
- Satellite image analysis
- Any dense prediction task
Q3: How can we use ResNet models for regression tasks?
Answer:
ResNet can be adapted for regression by modifying the output layer and loss function.
Steps:
1. Modify the output layer
import torch.nn as nn
from torchvision.models import resnet50
# Load pretrained ResNet
model = resnet50(weights='IMAGENET1K_V1')
# Original: FC layer outputs 1000 classes
# model.fc = nn.Linear(2048, 1000)
# For regression: output continuous value(s)
model.fc = nn.Linear(2048, 1) # Single value regression
# or
model.fc = nn.Linear(2048, num_outputs) # Multi-output regression2. Change the loss function
# Classification: CrossEntropyLoss
# Regression: MSELoss, L1Loss, SmoothL1Loss
criterion = nn.MSELoss() # Mean Squared Error
# or
criterion = nn.L1Loss() # Mean Absolute Error
# or
criterion = nn.SmoothL1Loss() # Huber loss (robust to outliers)3. Remove softmax (if present)
- Classification uses softmax for probabilities
- Regression outputs raw values (no activation or use appropriate one)
# For bounded outputs (e.g., 0-1 range)
model.fc = nn.Sequential(
nn.Linear(2048, 1),
nn.Sigmoid() # Output in [0, 1]
)
# For unbounded outputs
model.fc = nn.Linear(2048, 1) # No activation4. Consider output normalization
# Normalize targets to similar scale as pretrained features
# E.g., if predicting age (0-100), normalize to (0-1)
normalized_target = (target - mean) / stdExample use cases:
- Age estimation from face images
- House price prediction from photos
- Quality score prediction
- Pose estimation (predicting coordinates)
- Depth estimation
Tips:
- Use pretrained weights (transfer learning)
- Lower learning rate for pretrained layers
- Consider multi-task learning if predicting multiple values
Q4: What are skip connections and why do they help?
Answer:
Skip connections (residual connections) are direct pathways that allow information to bypass one or more layers.
Basic formulation:
Standard: y = F(x) # Learn full mapping
Residual: y = F(x) + x # Learn residual (difference)Why they help:
1. Solve the degradation problem
- Deep networks without skip connections perform worse than shallow ones
- Not due to overfitting (training error also higher)
- Skip connections enable training of 100+ layer networks
2. Gradient flow
Without skip:
∂L/∂x = ∂L/∂y × ∂F/∂x (can vanish if ∂F/∂x is small)
With skip:
∂L/∂x = ∂L/∂y × (∂F/∂x + 1) (always has +1 term)- Gradients have a direct path backward
- Prevents vanishing gradients in deep networks
3. Easier optimization
- Learning F(x) = 0 (identity) is easier than learning F(x) = x
- If identity is optimal, just push F(x) → 0
- Network can "skip" layers that aren't needed
4. Implicit ensemble
- ResNet can be viewed as ensemble of many shallow networks
- Different paths through the network
- Provides regularization effect
5. Feature reuse
- Earlier features directly available to later layers
- Don't need to re-learn or preserve information through transformations
Types:
| Type | When to Use | Example |
|---|---|---|
| Identity | Dimensions match | ResNet basic block |
| Projection (1×1 conv) | Dimensions differ | ResNet when channels change |
| Concatenation | Want to preserve all features | DenseNet, U-Net |
Visual comparison:
Plain network: ResNet: DenseNet:
x → F₁ → F₂ → F₃ x ─┬→ F₁ ─┬→ F₂ x ─┬→ F₁ ─┬→ F₂
│ ↓ │ ↓ │ ↓ │ ↓
└──→ (+) └──→ (+) └──┴───┴──┴→ concatInterview tip: Emphasize that skip connections solve a fundamental optimization problem (not just vanishing gradients), enabling the training of much deeper networks that would otherwise degrade in performance.