Skip to main content
Convolutional Neural Networks

Convolutional Neural Networks

Why Images Need Special Treatment

A 224×224 RGB image has 224 × 224 × 3 = 150,528 pixels. If we connected this to a fully connected layer with 1000 neurons:
  • 150,528 × 1000 = 150 million parameters in ONE layer!
  • Ignores spatial structure (neighboring pixels are related)
  • Overfits easily
  • Computationally expensive
CNNs solve this by:
  1. Local connectivity: Each neuron only sees a small patch (a cat’s ear doesn’t depend on what’s in the bottom-right corner)
  2. Weight sharing: Same filter applied across entire image (an edge detector that works in the top-left should work anywhere)
  3. Translation invariance: Cat is a cat, regardless of position (the learned patterns are position-independent)
Think of it like proofreading a document. A fully connected network reads the entire page at once, trying to understand every letter in relation to every other letter. A CNN uses a magnifying glass that slides across the page, looking for local patterns: misspellings, grammatical errors, formatting issues. The same magnifying glass works everywhere on the page — you don’t need a separate one for each paragraph. This is why CNNs are so parameter-efficient for spatial data.
Fully Connected vs Convolutional

The Convolution Operation

Intuition: A Sliding Window Detector

Imagine sliding a small “template” (filter/kernel) across an image, computing similarity at each position:
At each position, we compute: i,jImagei,jFilteri,j\sum_{i,j} \text{Image}_{i,j} \cdot \text{Filter}_{i,j}

Mathematical Definition

For a 2D convolution: (IK)[i,j]=mnI[i+m,j+n]K[m,n](I * K)[i, j] = \sum_{m}\sum_{n} I[i+m, j+n] \cdot K[m, n]

Common Filter Types

Edge Detection

Edge Detection Filters

Blur and Sharpen


CNN Building Blocks

Convolutional Layer

Parameter count: (kH×kW×Cin+1)×Cout(k_H \times k_W \times C_{in} + 1) \times C_{out}
  • 3×3×3+1=283 \times 3 \times 3 + 1 = 28 parameters per filter
  • 28×32=89628 \times 32 = 896 total parameters
Compare to fully connected: 224×224×3×32=4.8224 \times 224 \times 3 \times 32 = 4.8 million!

Pooling Layers

Pooling reduces spatial dimensions while keeping important features. Think of it as summarizing: instead of reporting every detail, you report the highlights.
Pooling Operations

Building a Complete CNN

LeNet-5 Style Architecture

Training the CNN


Visualizing What CNNs Learn

Filter Visualization

Feature Map Visualization

Feature Maps Visualization

Key CNN Concepts

Stride and Padding

Receptive Field

The receptive field is the region of input that affects a particular output neuron. This is one of the most important concepts in CNN design. Think of it as “how much of the original image can this neuron see?” A neuron in the first conv layer sees a 3x3 patch. A neuron two layers deep effectively sees a 5x5 patch (because it combines outputs from overlapping 3x3 patches). A neuron at the end of a deep CNN might “see” the entire image. If your receptive field is too small for the patterns you need to detect (say, you need to recognize a full face but your receptive field only covers an eye), the network will struggle — no single neuron can integrate enough context.

Classic CNN Architectures

VGG-16 Implementation


Exercises

Implement and apply these classic filters:
  1. Gaussian blur (5×5)
  2. Laplacian edge detector
  3. Custom “cross” pattern detector
Apply them to real images and visualize results.
Write a function that computes output dimensions for any sequence of conv and pool layers:
Build a CNN for CIFAR-10 (32×32 color images, 10 classes):
  1. Design architecture to achieve >85% accuracy
  2. Use batch normalization and dropout
  3. Visualize learned filters and feature maps
  4. Analyze which classes are confused
Implement depthwise separable convolutions (used in MobileNet):
  1. Depthwise: one filter per input channel
  2. Pointwise: 1×1 convolution to mix channels
Compare parameters and speed to standard convolutions.

Key Takeaways


What’s Next

Module 7: Pooling, Stride & CNN Design

Build modern CNN architectures — VGG, ResNet, EfficientNet design principles.

Interview Deep-Dive

Strong Answer:
  • Weight sharing means the same convolutional filter is applied at every spatial position. This encodes the inductive bias of translation equivariance: a feature detector that recognizes a cat ear in the top-left should recognize it in the bottom-right. Without weight sharing, the network would need to independently learn the same pattern for every possible location, requiring far more parameters and data.
  • Local connectivity means each neuron only connects to a small spatial patch (the receptive field), not the entire image. This encodes the locality bias: nearby pixels are more related than distant ones. An edge at position (10,10)(10, 10) depends on pixels at (9,9)(9,9) through (11,11)(11,11), not on a pixel at (200,200)(200, 200).
  • Together, these biases reduce the parameter count by orders of magnitude: a 3x3 convolution with 32 filters on a 224x224 image uses 896 parameters instead of 150 million for a fully connected layer. This massive reduction acts as strong regularization, preventing overfitting.
  • When they fail: (1) Tasks requiring global context, like counting objects across the entire image — local receptive fields miss long-range dependencies. (2) Data where the same pattern at different locations has different meanings — medical images where a lesion on the left lung has different significance than on the right. (3) Non-grid-structured data — graphs, point clouds, or sets of variable-length items. This is precisely why Vision Transformers, which have global attention without locality bias, can outperform CNNs when sufficient data is available to learn spatial relationships from scratch.
Follow-up: ViTs learn to attend to any position — does this mean locality bias is unnecessary?Not unnecessary, just learnable at a cost. ViTs need much more data (14M+ images for ViT-B) to learn the spatial relationships that CNNs encode for free. With sufficient data, ViTs discover locality patterns similar to CNNs in early layers (attention maps show local attention) and global patterns in later layers. Hybrid architectures like Swin Transformer reintroduce locality through windowed attention, achieving CNN-like data efficiency while maintaining the global reasoning capability for later layers. The trend is toward architectures that use locality bias where it helps (early layers) and global attention where it helps (later layers).
Strong Answer:
  • The receptive field is the region of the input image that can influence a particular neuron’s output. A neuron in the first 3x3 conv layer has a 3x3 receptive field. After stacking two 3x3 conv layers, the effective receptive field is 5x5. After three, it is 7x7.
  • Why it is critical: the receptive field determines what scale of features the network can detect. To recognize a face (roughly 100x100 pixels in a typical image), the final convolutional features must have a receptive field of at least 100x100. If the receptive field is only 50x50, no single neuron can “see” the entire face, and the network must rely on the fully connected layers to integrate partial information.
  • Computing receptive field: for a stack of nn layers with kernel size kk and stride ss, the receptive field grows as rl=rl1+(kl1)i=1l1sir_{l} = r_{l-1} + (k_l - 1) \cdot \prod_{i=1}^{l-1} s_i. Pooling layers with stride 2 are powerful receptive field amplifiers because every subsequent layer’s kernel covers twice as much input space.
  • VGG’s insight: two 3x3 convolutions have the same receptive field as one 5x5, but with fewer parameters (2×32=182 \times 3^2 = 18 vs. 52=255^2 = 25) and more non-linearity (two ReLU activations instead of one). Three 3x3 convolutions match a 7x7 filter (3×9=273 \times 9 = 27 vs. 4949) with even more savings. This is why modern CNNs exclusively use 3x3 kernels stacked deeply.
  • The effective receptive field (what the neuron actually “attends to”) is typically much smaller than the theoretical receptive field because weights near the center have more influence than those at the edges. This follows a Gaussian distribution, not a uniform one.
Follow-up: How do dilated (atrous) convolutions expand the receptive field without increasing parameters?Dilated convolutions insert gaps between kernel elements. A 3x3 kernel with dilation 2 covers a 5x5 area (with gaps), providing a 5x5 receptive field with only 9 parameters. Stacking dilated convolutions with exponentially increasing dilation rates (1, 2, 4, 8, 16) creates very large receptive fields without pooling — preserving spatial resolution. This is essential for tasks like semantic segmentation where you need both global context (large receptive field) and pixel-level precision (no downsampling). The trade-off is that dilated convolutions can create “gridding artifacts” where the gaps in the kernel cause aliasing. DeepLab addresses this with ASPP (Atrous Spatial Pyramid Pooling), which uses multiple dilation rates in parallel and aggregates the results.
Strong Answer:
  • Output spatial dimensions: Hout=(Hin+2PK)/S+1H_{out} = \lfloor (H_{in} + 2P - K) / S \rfloor + 1, where HinH_{in} is input height, PP is padding, KK is kernel size, SS is stride. Same formula for width.
  • Concrete example: input (B,3,224,224)(B, 3, 224, 224), Conv2d(3, 64, kernel_size=7, stride=2, padding=3):
    • Hout=(224+2×37)/2+1=223/2+1=112H_{out} = \lfloor (224 + 2 \times 3 - 7) / 2 \rfloor + 1 = \lfloor 223/2 \rfloor + 1 = 112
    • Output shape: (B,64,112,112)(B, 64, 112, 112)
  • Parameter count: (KH×KW×Cin+1)×Cout(K_H \times K_W \times C_{in} + 1) \times C_{out} (the +1 is for the bias per filter).
    • (7×7×3+1)×64=148×64=9, ⁣472(7 \times 7 \times 3 + 1) \times 64 = 148 \times 64 = 9,\!472 parameters.
    • Without bias: 7×7×3×64=9, ⁣4087 \times 7 \times 3 \times 64 = 9,\!408. Many modern architectures use bias=False when followed by batch normalization, since BN’s learned shift parameter (β\beta) makes the bias redundant.
  • Compute cost (FLOPs): roughly 2×K2×Cin×Cout×Hout×Wout2 \times K^2 \times C_{in} \times C_{out} \times H_{out} \times W_{out} (multiply-accumulate operations). For our example: 2×49×3×64×112×112236M2 \times 49 \times 3 \times 64 \times 112 \times 112 \approx 236M FLOPs. This single layer accounts for a significant fraction of a ResNet’s total compute because of the large spatial dimensions.
Follow-up: Why is it common to double the number of channels when halving spatial dimensions (e.g., 64 channels at 56x56, 128 at 28x28)?This design principle (from VGG and adopted by ResNet) keeps the total “information capacity” roughly constant across layers. When spatial dimensions are halved by stride-2 convolution or pooling, the number of spatial positions drops by 4x (56×56=313656 \times 56 = 3136 vs. 28×28=78428 \times 28 = 784). Doubling the channel count partially compensates, keeping the total number of activations (C×H×WC \times H \times W) from dropping too drastically. If channels were not increased, later layers would represent the input in progressively lower-dimensional spaces, creating information bottlenecks. Conversely, increasing channels beyond 2x would make later layers disproportionately expensive. The 2x rule is a practical sweet spot between information preservation and computational efficiency.