3.4.1Convolutional Neural Networks

Convolution operation and filters

2,423 words11 min readdifficulty · medium2 backlinks

Overview

The convolution operation is the fundamental building block of Convolutional Neural Networks (CNNs). It's a mathematical operation that slides a small matrix (called a filter or kernel) across an input image to detect local patterns like edges, textures, or shapes. Unlike fully connected layers that treat each pixel independently, convolution preserves spatial relationships between neighboring pixels.

Figure — Convolution operation and filters

The Mathematics of Convolution

What Is the Discrete2D Convolution?

(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]

This is technically cross-correlation, but in deep learning we call it "convolution" (true mathematical convolution flips the kernel, but we learn the weights anyway, so the flip is irrelevant).

Derivation from First Principles

WHY this formula? We want to measure "how much does this local patch of the image match the pattern encoded in the filter?"

Step 1: Local receptive field
The filter looks at a k×kk \times k window of the input. For a 3×3 filter at position (i,j)(i,j), it sees pixels I[i:i+3,j:j+3]I[i:i+3, j:j+3].

Step 2: Element-wise multiplication
Each filter weight K[m,n]K[m,n] multiplies the corresponding input pixel I[i+m,j+n]I[i+m, j+n]. This is a weighted sum where the filter weights determine what pattern we're looking for.

Step 3: Accumulation
We sum all k2k^2 products. A large positive sum means "strong match," near-zero means "pattern not present."

Step 4: Sliding the filter
Repeat for every valid position (i,j)(i,j) in the input. The stride ss controls how many pixels we skip: incrementing by ss instead of 1.

where pp is padding (zeros added around input borders), ss is stride.

WHY padding? Without it, the output shrinks by k1k-1 pixels in each dimension. Padding preserves spatial size. WHY stride >1>1? Downsamples the output, reducing computation (like pooling).


What Does a Filter Actually Detect?


Worked Examples

Example 1: 3×3 Filter on 5×5 Input (Stride 1, No Padding)

Input II:

[123010123020121101202101]\begin{bmatrix} 1 & 2 & 3 & 0 & 1 \\ 0 & 1 & 2 & 3 & 0 \\ 2 & 0 & 1 & 2 \\ 1 & 1 & 0 & 1 & 2 \\ 0 & 2 & 1 & 0 & 1 \end{bmatrix}

Filter KK (vertical edge):

[101101101]\begin{bmatrix} -1 & 0 & 1 \\ -1 & 0 & 1 \\ -1 & 0 & 1 \end{bmatrix}

Output size: Hout=(53)/1+1=3H_{out} = (5 - 3)/1 + 1 = 3, so 3×33 \times 3 output.

Compute top-left output element (0,0)(0,0):

(IK)[0,0]=I[0,0]K[0,0]+I[0,1]K[0,1]+I[0,2]K[0,2]+I[1,0]K[1,0]+I[1,1]K[1,1]+I[1,2]K[1,2]+I[2,0]K[2,0]+I[2,1]K[2,1]+I[2,2]K[2,2]=1(1)+2(0)+3(1)+0(1)+1(0)+2(1)+2(1)+0(0)+1(1)=1+0+3+0+0+22+0+1=3\begin{aligned} (I*K)[0,0] &= I[0,0]K[0,0] + I[0,1]K[0,1] + I[0,2]K[0,2] \\ &\quad + I[1,0]K[1,0] + I[1,1]K[1,1] + I[1,2]K[1,2] \\ &\quad + I[2,0]K[2,0] + I[2,1]K[2,1] + I[2,2]K[2,2] \\ &= 1(-1) + 2(0) + 3(1) \\ &\quad + 0(-1) + 1(0) + 2(1) \\ &\quad + 2(-1) + 0(0) + 1(1) \\ &= -1 + 0 + 3 + 0 + 0 + 2 - 2 + 0 + 1 = 3 \end{aligned}

Why this step? We overlay the filter on the top-left 3×3 patch, multiply corresponding elements, and sum. The positive result (3) indicates a weak vertical edge (right side slightly brighter than left).

Full output (computing remaining 8 positions similarly):

[302121101]\begin{bmatrix} 3 & 0 & -2 \\ -1 & 2 & 1 \\ -1 & 0 & 1 \end{bmatrix}

Example 2: Effect of Stride and Padding

Same input/filter, stride s=2s=2, padding p=1p=1.

Paded input (add one row/column of zeros on all sides) → 7×77\times 7:

[000012301001230]\begin{bmatrix} 0 & 0 & 0 \\ 0 & 1 & 2 & 3 & 0 & 1 \\ 0 & 0 & 1 & 2 & 3 & 0 \\ \vdots & \vdots & \ddots & & \vdots \end{bmatrix}

Output size: Hout=(73)/2+1=3H_{out} = (7 - 3)/2 + 1 = 3.

Top-left computation now starts at the paded position (0,0)(0,0), but most elements are 0:

(IK)[0,0]=0(1)+0(0)+0(1)+0(1)+1(0)+2(1)+=2(I*K)[0,0] = 0(-1) + 0(0) + 0(1) + 0(-1) + 1(0) + 2(1) + \ldots = 2

Why stride 2? We skip every other position, so the filter moves from (0,0)(0,0) to (0,2)(0,2) to (0,4)(0,4), then (2,0)(2,0), etc. Output is smaller but faster to compute.

Example 3: Multi-Channel Input (RGB Image)

Real images have 3 channels (R, G, B). The filter must also have 3 channels.

Input: 5×5×35 \times 5 \times 3 (height, width, channels)
Filter: 3×3×33 \times 3 \times 3 (one slice per input channel)

Convolution:

(IK)[i,j]=c=02m=02n=02I[i+m,j+n,c]K[m,n,c](I*K)[i,j] = \sum_{c=0}^{2} \sum_{m=0}^{2} \sum_{n=0}^{2} I[i+m, j+n, c] \cdot K[m, n, c]

Why this form? We apply the filter separately to each channel, then sum across channels to produce a single output value. The filter learns correlations across color channels (e.g., "red and green high, blue low" = yellow).

Multiple filters: A CNN layer typically has NN filters (say 64). Each produces its own feature map, so the output is Hout×Wout×64H_{out} \times W_{out} \times 64.


Common Mistakes and Fixes


Active Recall Flashcards

#flashcards/ai-ml

What is the discrete2D convolution formula for position (i,j)? :: (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]

What is the output height formula after convolution?
Hout=(H+2pk)/s+1H_{out} = \lfloor (H + 2p - k)/s \rfloor + 1 where p=padding, k=kernel size, s=stride
Why do we use convolution instead of fully connected layers for images?
1) Parameter sharing: same filter slides across image, drastically fewer weights. 2) Translation invariance: learned feature detectors work anywhere in the image.
What does a vertical edge detection filter look like (3×3)?
[101101101]\begin{bmatrix} -1 & 0 & 1 \\ -1 & 0 & 1 \\ -1 & 0 & 1 \end{bmatrix} (negative left, positive right)
What is the difference between stride and dilation?
Stride controls how far the filter moves across input (downsampling). Dilation controls spacing between filter elements (expands receptive field without adding parameters).
For an RGB image (3 channels), what shape must a filter have?
k×k×3k \times k \times 3 — the third dimension (depth) must match input channels. Output depth = number of filters.
What is translation invariance in CNs?
The same learned filter detects the same feature (edge, texture) regardless of where it appears in the image. A cat is recognized in top-left or bottom-right.
If input is 32×32×3, filter is 5×5×3, stride=1, padding=2 output shape?
Hout=(32+225)/1+1=32H_{out} = (32+2\cdot2-5)/1+1=32, so 32×32×1per filter. If 64 filters, output is 32×32×64.

Feynman Explanation

Recall Explain to a 12-Year-Old

Imagine you have a big photo of your dog, and you want to find all the spots where there's a vertical line (like the edge of a door). You can't look at the whole photo at once—that's too much! Instead, you use a magnifying glass (the filter) that only sees a tiny 3×3 square at a time.

Inside that magnifying glass, you have a special pattern drawn: "If the left side is dark and the right side is bright, this is a vertical edge!" You multiply each pixel you see by this pattern and add them up. If the sum is big, you write "Found an edge here!" on a new sheet of paper.

Now you slide the magnifying glass one step to the right, and check again. Slide, check, slide, check—all the way across the photo, row by row. The new sheet of paper (the feature map) shows you everywhere the vertical edge pattern appeared.

The amazing part? You only designed the magnifying glass pattern once, but you used it thousands of times across the photo. That's way easier than making a separate magnifying glass for every single pixel!

In a CNN, the computer learns what patterns to look for (edges, colors, shapes) by trying millions of examples. Early layers find simple stuff like edges. Deeper layers combine those edges into complex things like "dog ears" or "bicycle wheels."


Connections

  • 3.4.02-Pooling-layers — After convolution, pooling downsamples feature maps
  • 3.4.03-CNN-architectures — Stack convolution + pooling to build networks like LeNet, AlexNet
  • 3.3.01-Backpropagation — How filters learn: gradients flow back through convolution
  • 2.2.05-Receptive-fields — Each output neuron "sees" a local input region
  • 3.4.10-Depthwise-separable-convolutions — Efficient variant splitting spatial and channel-wise convolution
  • 4.1.03-Transfer-learning — Pretrained filters (ImageNet) transfer low-level features to new tasks
  • 3.4.06-Batch-normalization — Normalizes feature maps to stabilize training

Mnemonic

Channels: "Filter Depth Must Match Input Depth" (FD = ID).


Key Takeaways

  1. Convolution = local pattern matching: Filters encode templates (edges, textures), output measures match strength at each location.
  2. Parameter sharing: Same small filter reused across entire image → far fewer weights than fully connected.
  3. Translation invariance: Learned features work anywhere in the image.
  4. Dimensions matter: Filter depth = input channels. Output channels = number of filters.
  5. Stride & padding control: Stride downsamples, padding preserves size. Formula: Hout=(H+2pk)/s+1H_{out} = \lfloor (H+2p-k)/s \rfloor + 1.
  6. Learned representations: Backprop tunes filter weights to extract useful features for the task.

Master convolution, and you understand the heart of computer vision models.

Concept Map

built from

slides

replaces

preserves

enforces

acts as

scores produce

controlled by

uses

affects

affects

reuses weights so reduces params

Convolutional Neural Networks

Convolution Operation

Filter / Kernel

Fully Connected Layers

Spatial Relationships

Translation Invariance

Feature Map

Template Matching

Stride s

Padding p

Output Dimensions

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Convolution ka matlab hai ek chhoti si template (filter) ko puri image par slide karna aur dekhna ki kahin pattern match ho raha hai ya nahi. Socho tumhare pas ek photo hai aur tumhe sare vertical edges (jaise door ki boundary) dhundhne hain. Agar tum pori image koek sath dekho toh bohot complicated ho jayega. Instead, ek3×3 ka magnifying glass lo jo sirf thoda sa area dekhta hai. Us magnifying glass mein ek pattern likha hua hai: "agar left side dark hai aur right side bright hai, toh yeh edge hai!" Ab tum us glass ko left-se-right slide karte jao, har jagah check karo, aur jahan match mile wahan "edge mila!" likh do. Yeh convolution operation hai.

CNN mein yeh filters khud seekhte hain. Matlab tumhe manually edge detector banana nahi padta—network khud training data se samajh jata hai ki kaunsa pattern useful hai. Pehli layer simple chezein seekhti hai (edges, colors), deeper layers complex cheezein seekhti hain (dog ka face, car ka wheel). Translation invariance ka fayda yeh hai ki agar tumne top-left corner mein cat detect karna seekha, toh bottom-right mein bhi kaam karega—same filter reuse hota hai. Isliye CNN billions of parameters ki jagah thousands mein kaam kar lete hain. Stride bata hai kitne pixels chhod kar filter move karega (faster computation), aur padding image ke size ko preserve karta hai taki output chhota na ho jaye. RGB images ke liye filter ko bhi teen channels chahiye (R, G, B)—yeh teno channels ka weighted sum output deta hai. Yeh technique hi computer vision ka foundation hai!

Go deeper — visual, from zero

Test yourself — Convolutional Neural Networks

Connections