Skip to content
AI360XpertBeta

Convolutional Neural Networks

Small shared kernels scan the whole image for local patterns, pooling shrinks those maps while growing depth, and a classifier votes one label from what is left.

Two conv-pool stages shrink 28 by 28 by 1 to 7 by 7 by 16, which flattens to 784 votes for one label
Two conv-pool stages shrink 28 by 28 by 1 to 7 by 7 by 16, which flattens to 784 votes for one label

Why Does This Exist?

Say you must sort phone photos into cats and dogs. Each photo is 28 by 28 gray values, 784 numbers, and the cat can sit anywhere in the frame. A multi-layer perceptron gives every pixel its own weight for every hidden unit, so it must relearn a pointy ear at each of 784 positions. Shift the cat one pixel and the whole input pattern changes.

You need three things at once. Spot a local pattern wherever it lands. Tolerate small shifts. Grow the view from edges to whole objects. Convolution spots the pattern with shared weights. Pooling buys shift tolerance and shrinks the map. Depth grows receptive fields until a late unit sees enough to vote.

This page stacks those pieces into one classifier. The single slide lives in convolution. The shrink step lives in pooling. Field growth lives in receptive fields. The famous stacks that followed live in CNN architectures.

Think of It Like This

Cookie cutters, tray notes, and one vote

You bake with friends. You press small cookie cutters across a big sheet of dough, same cutters everywhere, and note where each shape pressed cleanly. You then summarize each tray quadrant with one line, strongest press wins, and toss the exact positions. From those short notes you vote one label for the whole sheet, cat batch or dog batch.

The cutters are kernels, pressing everywhere is weight sharing, tray notes are pooling, and the final vote is the dense head. Early notes record edges, later notes built from earlier ones record ears and snouts.

Where it stops: dough never learns, while kernels do. You picked the cutters by hand, while a CNN learns its cutters from labeled photos by gradient descent.

How It Actually Works

A CNN keeps the image as a grid until the last moment. Call the input XX, meaning the array of pixel values. Call one kernel KK, meaning a small grid of learned weights such as 3 by 3. The network slides the same KK everywhere, applies activation functions such as ReLU, shrinks with pooling, repeats, then flattens once for a dense vote.

The shared kernel and the size rule

Call the input edge nn, meaning how wide the map is. Call the kernel edge kk, meaning how wide one kernel is. Call the zero border pp, meaning how many zeros pad each side. Call the step ss, meaning how far the window jumps. One conv layer maps edge to edge by:

output size=⌊n+2p−ks⌋+1\text{output size} = \left\lfloor \frac{n + 2p - k}{s} \right\rfloor + 1

With n=28n = 28, k=3k = 3, p=1p = 1, s=1s = 1, you get (28+2−3)+1=28(28 + 2 - 3) + 1 = 28. Same padding keeps the size. Channels set the price. Call incoming maps CinC_{in}, meaning how many feature maps enter, and outgoing detectors CoutC_{out}, meaning how many kernels run:

params=k×k×Cin×Cout\text{params} = k \times k \times C_{in} \times C_{out}

First layer here reads 1 map and writes 8 with 3 by 3 kernels, so 9×1×8=729 \times 1 \times 8 = 72 weights plus 8 biases for 80 parameters. Every position learns from every example because the same 80 numbers slide everywhere.

Pooling and the halving rule

Pooling has no weights. A 2 by 2 window with stride 2 keeps one summary per patch and halves each side. Max keeps the largest of the four, which preserves a sharp hit. Average keeps the mean, which softens it. Either way 28 by 28 becomes 14 by 14, and later 14 by 14 becomes 7 by 7. You trade exact position for tolerance inside one window and for cheaper maps downstream.

Worked example: 28 by 28 by 1 to 784 votes

Start with 28×28×128 \times 28 \times 1. Conv with eight 3 by 3 kernels, padding 1, stride 1 keeps 28×28×828 \times 28 \times 8. Pool 2 by 2, stride 2 halves to 14×14×814 \times 14 \times 8. Conv with sixteen 3 by 3 kernels, padding 1, stride 1 keeps 14×14×1614 \times 14 \times 16. Pool again to 7×7×167 \times 7 \times 16.

Flattening unrolls that block with no math, just a reshape:

7×7×16=7847 \times 7 \times 16 = 784

Those 784 numbers feed dense layers ending in 2 scores, one per class, turned into probabilities by softmax. ReLU sits between conv layers as f(z)=max⁡(0,z)f(z) = \max(0, z), meaning keep positives and zero out negatives, so stacked layers cannot collapse into one linear map. The diagram draws this exact trace, 28 to 14 to 7 to 784.

Code

The point is the check: recompute the trace from kernel, padding, stride, and filter counts, then confirm the hand numbers above.

def conv_output(size: int, kernel: int, padding: int, stride: int) -> int:    return (size + 2 * padding - kernel) // stride + 1

def cnn_shape_trace(h: int, w: int, c: int) -> None:    h = conv_output(h, 3, 1, 1)    w = conv_output(w, 3, 1, 1)    c = 8    h, w = h // 2, w // 2    print(f"after block 1: {h}x{w}x{c}")  # -> after block 1: 14x14x8
    h = conv_output(h, 3, 1, 1)    w = conv_output(w, 3, 1, 1)    c = 16    h, w = h // 2, w // 2    print(f"after block 2: {h}x{w}x{c}")  # -> after block 2: 7x7x16
    print(f"flattened length: {h * w * c}")  # -> flattened length: 784

cnn_shape_trace(h=28, w=28, c=1)

The printout matches the hand trace: 14 by 14 by 8, then 7 by 7 by 16, then 784. Change the input to 32 and the same code shows where a hardcoded dense head would break.

Watch Out For

Hardcoded flatten length breaks on a new image size

You write a dense layer for 784 because that fit 28 by 28 inputs, then feed 32 by 32 images and the first forward pass dies with a matrix shape complaint naming two numbers and no clear cause.

Symptom: training never starts, the error points at the first dense matrix. Fix: compute the trace above from your true input size, or run one dummy forward pass and read the flattened width before writing the dense head.

Pooling a small map down to nothing

Two pools turn 28 into 7, which still holds shape. Four pools turn 8 into 4, then 2, then 1, then gone. Copy a big image recipe onto tiny crops and spatial structure vanishes before the classifier sees it.

Symptom: accuracy sits near chance on small inputs while the same net works on larger ones. Fix: fit pool count to input edge, check width after each stage, and pool less or use stride 1 convs when the map is already small.

The Quick Version

  • A CNN keeps images as grids through shared convolution and pooling, then flattens once for a dense classifier that votes one label.
  • Shared 3 by 3 kernels with padding 1 keep 28 by 28 at 28 by 28, and 2 by 2 pooling with stride 2 halves each side to 14 by 14.
  • Two such stages turn 28 by 28 by 1 into 14 by 14 by 8 into 7 by 7 by 16, which flattens to 784 numbers.
  • Eight 3 by 3 kernels on one input channel cost 72 weights plus 8 biases, 80 parameters in total.
  • Pooling forgives shifts inside one window only, and too many pools on a small image leave no map to classify.