Overview
In an image, a pattern such as an edge means the same thing wherever it appears. A convolutional network uses that fact. Instead of one weight per pixel, it learns a small filter, a few pixels wide, and slides it over the whole image. At each position the filter reports how strongly its pattern is present, which gives a new grid called a feature map. Max-pooling then shrinks each map by keeping only the strongest response in each small block. After one or more of these blocks, the maps are flattened and an ordinary dense layer decides the class.
A short history
Kunihiko Fukushima's neocognitron of 1980 introduced layers of local feature detectors inspired by the visual cortex. Yann LeCun and colleagues trained such networks with backpropagation in 1989 to read handwritten zip codes, and published LeNet-5 in 1998. The approach took over computer vision in 2012, when AlexNet by Alex Krizhevsky, Ilya Sutskever and Geoffrey Hinton won the ImageNet competition by a wide margin using graphics processors.
How it works
- Slide each filter over the input and compute a weighted sum at every position. This gives one feature map per filter.
- Apply ReLU, which sets negative responses to zero.
- Max-pool: cut each map into non-overlapping blocks and keep the largest value of each block.
- Repeat convolution, ReLU and pooling for each entry of
conv_channels. - Flatten the final maps into one vector and pass it through a dense ReLU layer of
hidden_sizeunits and a softmax output. - Compute the cross-entropy loss, backpropagate through the dense layers, the pooling (gradient goes only to each block's maximum) and the convolutions, and update with Adam.
Watch out for
- Each valid convolution removes pixels per side length and each pool divides it by , so a small image runs out of pixels after a few blocks and the model cannot be built.
- Pooling drops rows and columns that do not fill a whole window, so information at the right and bottom edges can be lost when the size is not a multiple of the pool size.
- A CNN assumes that position does not change meaning. On tabular data, where neighbouring columns are unrelated, sliding filters bring no benefit.
- This template is a teaching-size NumPy version: CPU only, no padding, strides, batch normalisation or residual connections. It suits images of a few dozen pixels a side.
Use cases
When to use it
Inputs on a grid where a pattern means the same thing wherever it appears: images, spectrograms, board states. Weight sharing makes it far more data-efficient than a dense network there.
In industry
- Postal and banking
- Reading handwritten digits on envelopes and cheques, the original commercial use of LeNet in the 1990s.
- Medical imaging
- Classifying X-rays, skin lesion photographs or pathology slides to support a clinician's reading.
- Manufacturing
- Visual inspection: spotting scratches, cracks or missing parts in camera images of products on a line.
Choosing it: what must hold
- Inputs with a grid layout, such as images or spectrograms, where nearby values are related.
- Patterns that mean the same thing wherever they appear in the input.
- Thousands of labelled examples, or a pretrained network to fine-tune.
- A graphics processor for anything beyond small images.
When to choose something else
| If | Use instead |
|---|---|
| The network needs to be deep (dozens of layers) | A residual network (ResNet) |
| You need a label for every pixel, not one per image | A U-Net |
| The data is a table of unrelated columns | Gradient boosted trees or an MLP |
Math foundations
Convolution (cross-correlation)
The response of filter at position : a weighted sum over a window across all input channels. The same weights are used at every position.
Output size
A valid convolution with stride 1 only places the filter where it fits fully, so the map shrinks by . Pooling then divides the side by , rounding down. The same holds for the width.
Max-pooling
Keeps the strongest response in each block. This makes the output smaller and less sensitive to small shifts of the pattern.
Parameter count of a conv layer
The count does not depend on the image size. A dense layer from the same input to the same output would need one weight for every pair of input and output pixels.
Gradient of a filter weight
Because the weight is shared, its gradient adds up the contributions from every position where it was used. is the gradient arriving at the feature map.
Symbols
- input value in channel c at row i, column j
- weight of filter f for channel c at offset (u, v)
- bias of filter f
- output feature map f at position (i, j)
- kernel_size, the side of the square filter
- pool_size, the side of the pooling window
- number of input channels and number of filters
- height of the input map
- gradient of the loss with respect to the output y at that position
Worked by hand
A single-channel input with rows , , , one filter with rows , and zero bias. The filter adds the top-left and bottom-right values of each window.
The convolution gives a map and a max-pool reduces it to the single value 5. In the backward pass the whole gradient of that value goes to position , the block's maximum.
Visual example
Loading the example.
Try this
- Keep the vertical edge filter and switch the image to the horizontal bar: the feature map goes dark.
- Choose a cell of the feature map to see the window it came from and the sum that made it.
- Set kernel_size to 2 and pool_size to 3 and check the new sizes against H - K + 1 and the rounding down.
Code sample
import numpy as np
from impl import CNN
from config import CNNConfig
rng = np.random.default_rng(0)
X = rng.normal(0, 0.3, size=(200, 1, 8, 8)) # (n, channels, height, width)
y = rng.integers(0, 2, size=200)
for i in range(200): # class 0: bright row, class 1: bright column
if y[i] == 0:
X[i, 0, rng.integers(8), :] += 1.0
else:
X[i, 0, :, rng.integers(8)] += 1.0
net = CNN(CNNConfig(conv_channels=(4,), hidden_size=16, epochs=8)).fit(X, y)
print((net.predict(X) == y).mean()) # training accuracyRead the implementation (181 lines)
"""CNN: a small convolutional network for image classification.
NumPy only, manual backpropagation. Architecture:
[conv k x k (valid, stride 1) -> ReLU -> max-pool p x p] per entry of conv_channels
-> flatten -> dense(hidden_size) -> ReLU -> dense(n_classes) -> softmax
The layer functions (`conv2d_forward`, `conv2d_backward`, `maxpool_forward`, `maxpool_backward`) are plain
functions so they can be reused or checked on their own.
"""
from __future__ import annotations
import numpy as np
from numpy.lib.stride_tricks import sliding_window_view
try:
from .config import CNNConfig
except ImportError: # run from the template's own folder
from config import CNNConfig
def conv2d_forward(x: np.ndarray, W: np.ndarray, b: np.ndarray) -> np.ndarray:
"""Valid cross-correlation, stride 1.
x: (n, C, H, W) input. W: (F, C, k, k) filters. b: (F,) biases. Returns (n, F, H - k + 1, W - k + 1).
"""
k = W.shape[2]
windows = sliding_window_view(x, (k, k), axis=(2, 3)) # (n, C, Ho, Wo, k, k)
return np.einsum("nchwij,fcij->nfhw", windows, W, optimize=True) + b[None, :, None, None]
def conv2d_backward(x: np.ndarray, W: np.ndarray, dout: np.ndarray):
"""Gradients of a scalar loss through `conv2d_forward`.
x, W: the forward inputs. dout: (n, F, Ho, Wo) gradient of the loss with respect to the output.
Returns (dx, dW, db) with the shapes of x, W and b.
"""
k = W.shape[2]
windows = sliding_window_view(x, (k, k), axis=(2, 3))
dW = np.einsum("nchwij,nfhw->fcij", windows, dout, optimize=True)
db = dout.sum(axis=(0, 2, 3))
padded = np.pad(dout, ((0, 0), (0, 0), (k - 1, k - 1), (k - 1, k - 1)))
dwindows = sliding_window_view(padded, (k, k), axis=(2, 3)) # (n, F, H, W, k, k)
dx = np.einsum("nfhwij,fcij->nchw", dwindows, W[:, :, ::-1, ::-1], optimize=True)
return dx, dW, db
def maxpool_forward(x: np.ndarray, p: int) -> tuple[np.ndarray, np.ndarray]:
"""Non-overlapping p x p max pooling. Rows and columns that do not fill a window are dropped.
x: (n, C, H, W). Returns (out (n, C, H // p, W // p), argmax (n, C, H // p, W // p) index inside each window).
"""
n, c, h, w = x.shape
ho, wo = h // p, w // p
blocks = x[:, :, :ho * p, :wo * p].reshape(n, c, ho, p, wo, p).transpose(0, 1, 2, 4, 3, 5).reshape(n, c, ho, wo, p * p)
arg = blocks.argmax(axis=4)
return np.take_along_axis(blocks, arg[..., None], axis=4)[..., 0], arg
def maxpool_backward(dout: np.ndarray, arg: np.ndarray, x_shape: tuple, p: int) -> np.ndarray:
"""Route each output gradient to the input position that was the maximum. Returns dx with shape x_shape."""
n, c, ho, wo = dout.shape
blocks = np.zeros((n, c, ho, wo, p * p))
np.put_along_axis(blocks, arg[..., None], dout[..., None], axis=4)
dx = np.zeros(x_shape)
dx[:, :, :ho * p, :wo * p] = blocks.reshape(n, c, ho, wo, p, p).transpose(0, 1, 2, 4, 3, 5).reshape(n, c, ho * p, wo * p)
return dx
def _softmax(z: np.ndarray) -> np.ndarray:
e = np.exp(z - z.max(axis=1, keepdims=True))
return e / e.sum(axis=1, keepdims=True)
class CNN:
"""Convolutional classifier. Inputs are (n, channels, height, width) float arrays."""
def __init__(self, config: CNNConfig | None = None) -> None:
self.config = config or CNNConfig()
self.params: dict[str, np.ndarray] = {}
self.classes_: np.ndarray | None = None
self.loss_history: list[float] = []
def _init_params(self, input_shape: tuple, n_classes: int) -> None:
"""input_shape: (C, H, W) of one image."""
cfg = self.config
rng = np.random.default_rng(cfg.seed)
c, h, w = input_shape
k = cfg.kernel_size
self.params = {}
for i, f in enumerate(cfg.conv_channels):
self.params[f"conv{i}_W"] = rng.normal(0.0, np.sqrt(2.0 / (c * k * k)), size=(f, c, k, k))
self.params[f"conv{i}_b"] = np.zeros(f)
h, w, c = (h - k + 1) // cfg.pool_size, (w - k + 1) // cfg.pool_size, f
if h < 1 or w < 1:
raise ValueError("the image is too small for this many conv and pool layers")
flat = c * h * w
self.params["fc1_W"] = rng.normal(0.0, np.sqrt(2.0 / flat), size=(flat, cfg.hidden_size))
self.params["fc1_b"] = np.zeros(cfg.hidden_size)
self.params["fc2_W"] = rng.normal(0.0, np.sqrt(1.0 / cfg.hidden_size), size=(cfg.hidden_size, n_classes))
self.params["fc2_b"] = np.zeros(n_classes)
def forward(self, X: np.ndarray) -> tuple[np.ndarray, list]:
"""X: (n, C, H, W) -> (logits (n, n_classes), cache for the backward pass)."""
cfg = self.config
a = np.asarray(X, dtype=float)
cache = []
for i in range(len(cfg.conv_channels)):
z = conv2d_forward(a, self.params[f"conv{i}_W"], self.params[f"conv{i}_b"])
r = np.maximum(z, 0.0)
pooled, arg = maxpool_forward(r, cfg.pool_size)
cache.append((a, z, arg))
a = pooled
flat = a.reshape(len(a), -1)
h = np.maximum(flat @ self.params["fc1_W"] + self.params["fc1_b"], 0.0)
logits = h @ self.params["fc2_W"] + self.params["fc2_b"]
cache.append((a.shape, flat, h))
return logits, cache
def loss_and_grads(self, X: np.ndarray, T: np.ndarray) -> tuple[float, dict]:
"""Mean cross-entropy on a batch and its gradient for every parameter.
X: (n, C, H, W). T: (n, n_classes) one-hot targets. Returns (loss, {parameter name: gradient}).
"""
cfg = self.config
logits, cache = self.forward(X)
n = len(X)
P = _softmax(logits)
loss = float(-np.sum(T * np.log(P + 1e-12)) / n)
pooled_shape, flat, h = cache[-1]
grads = {}
d = (P - T) / n
grads["fc2_W"] = h.T @ d
grads["fc2_b"] = d.sum(axis=0)
d = (d @ self.params["fc2_W"].T) * (h > 0)
grads["fc1_W"] = flat.T @ d
grads["fc1_b"] = d.sum(axis=0)
d = (d @ self.params["fc1_W"].T).reshape(pooled_shape)
for i in range(len(cfg.conv_channels) - 1, -1, -1):
a_in, z, arg = cache[i]
d = maxpool_backward(d, arg, z.shape, cfg.pool_size) * (z > 0)
d, grads[f"conv{i}_W"], grads[f"conv{i}_b"] = conv2d_backward(a_in, self.params[f"conv{i}_W"], d)
return loss, grads
def fit(self, X: np.ndarray, y: np.ndarray) -> "CNN":
"""Train with mini-batch Adam. X: (n, C, H, W) images. y: (n,) class labels."""
cfg = self.config
X = np.asarray(X, dtype=float)
if X.ndim != 4:
raise ValueError(f"X must have shape (n, channels, height, width), got {X.shape}")
self.classes_, idx = np.unique(np.asarray(y), return_inverse=True)
T = np.eye(len(self.classes_))[idx]
self._init_params(X.shape[1:], len(self.classes_))
rng = np.random.default_rng(cfg.seed + 1)
m = {k: np.zeros_like(v) for k, v in self.params.items()}
v = {k: np.zeros_like(p) for k, p in self.params.items()}
step = 0
self.loss_history = []
for _ in range(cfg.epochs):
order = rng.permutation(len(X))
total = 0.0
for start in range(0, len(X), cfg.batch_size):
rows = order[start:start + cfg.batch_size]
loss, grads = self.loss_and_grads(X[rows], T[rows])
total += loss * len(rows)
step += 1
for name, g in grads.items():
m[name] = 0.9 * m[name] + 0.1 * g
v[name] = 0.999 * v[name] + 0.001 * g * g
self.params[name] -= cfg.learning_rate * (m[name] / (1 - 0.9**step)) / (
np.sqrt(v[name] / (1 - 0.999**step)) + 1e-8)
self.loss_history.append(total / len(X))
return self
def predict_proba(self, X: np.ndarray) -> np.ndarray:
"""Class probabilities. X: (n, C, H, W) -> (n, n_classes)."""
return _softmax(self.forward(X)[0])
def predict(self, X: np.ndarray) -> np.ndarray:
"""Class labels. X: (n, C, H, W) -> (n,)."""
return self.classes_[self.forward(X)[0].argmax(axis=1)]- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 6, run with
python3 -m unittest -v
Practice
Call conv2d_forward on the 3 by 3 input and 2 by 2 filter above (shapes (1, 1, 3, 3) and (1, 1, 2, 2)) and maxpool_forward on the result, and check the numbers against the hand calculation. Then train CNN on the bright-row versus bright-column images from the README and plot loss_history.
Check on learning
- A dense layer from an 8 by 8 image to 4 feature maps of 6 by 6 needs thousands of weights, while a conv layer with four 3 by 3 filters needs 40. What assumption lets the CNN use so few, and when is that assumption wrong?
A way to think about it
Count how often each filter weight is reused across the image. Then think of data where the same local pattern means different things in different places.
- Why does max-pooling make the network tolerant of small shifts in the input, and what information does it throw away?
A way to think about it
Shift a bright pixel by one position inside the same pooling block and compare the outputs. Then ask what you can no longer tell from the pooled map.
- In the README example one class has a bright row and the other a bright column, at a random position. Why is a CNN a better fit for this task than a dense network of similar size?
A way to think about it
A dense network would have to learn the pattern separately for each position. Consider how a single horizontal filter responds as the row moves.
- During backpropagation through a max-pool, only one input of each block receives gradient. What does that imply for the filters that produced the other values?
A way to think about it
Follow the chain rule: a value that did not affect the output cannot affect the loss for that example. Think about whether this is permanent or changes from image to image.