Sign in

ResNet

Residual Network

A convolutional network built from blocks that add their input back to their output, so each block only has to learn a correction to what it received.

Overview

Stacking more layers should make a network at least as good, yet plain deep networks often train worse than shallow ones. The trouble is that every layer must pass the signal on through a transformation, and after many of them both the signal and its gradient degrade. A residual network gives each block a shortcut: the block's input is added to its output. If the best thing a block can do is nothing, it only needs to output zero, which is easy to learn. The shortcut also gives the gradient a direct path back to the early layers. This template is a small NumPy version for tiny images, with no batch normalisation and no downsampling.

A short history

Kaiming He, Xiangyu Zhang, Shaoqing Ren and Jian Sun at Microsoft Research published ResNet in 2015. Very deep plain networks were getting worse, not better, even on their training data. Letting each block learn a correction that is added to its input made networks of more than 100 layers trainable, and a 152-layer ResNet won the ImageNet classification challenge that year. Skip connections are now part of nearly every deep architecture, including Transformers.

How it works

  1. The stem applies one 3x3 convolution and a ReLU to the image, producing the configured number of feature maps.
  2. Each residual block applies a 3x3 convolution, a ReLU, and a second 3x3 convolution to its input. The result is called the residual.
  3. The block adds its input to the residual and applies a ReLU. With use_skip off, the input is not added and the network is a plain stack.
  4. After the last block, average each feature map over height and width to get one number per channel.
  5. A linear layer turns those averages into class scores, and softmax cross-entropy gives the loss.
  6. In the backward pass, the gradient reaching a block's output goes both through the two convolutions and straight across the shortcut, and the two are added.

Watch out for

  • The addition needs the input and the residual to have the same shape. This template keeps channels and resolution fixed so that always holds. Full ResNets need a projection on the shortcut when the shape changes.
  • There is no batch normalisation here, so deep settings of num_blocks can still train unstably. Set zero_init_residual so each block starts as the identity.
  • All convolutions run at full resolution in pure NumPy, so cost grows with height times width times channels squared. Keep images and channel counts small.
  • With only a few blocks, a plain network trains about as well as a residual one. The benefit of the shortcut shows as depth grows.

Use cases

When to use it

Image classification, and more generally any network deep enough that plain stacking stops helping. Skip connections of this kind are now standard in almost every deep architecture, including transformers.

In industry

Computer vision products
The pretrained backbone for image classification, object detection and segmentation in many production systems.
Medical imaging
Transfer learning: fine-tuning a ResNet pretrained on ImageNet to classify scans when labelled medical data is limited.
Game playing
The policy and value network of AlphaGo Zero, which DeepMind built from residual blocks.

Choosing it: what must hold

  • Image-like inputs and a task that benefits from many layers.
  • A large labelled dataset, or pretrained weights to start from.
  • Graphics processor time for training.

When to choose something else

IfUse instead
The images are small and the task is simpleA plain CNN with a few layers
You need a prediction for every pixelA U-Net
You have very large pretraining data and computeA vision Transformer

Math foundations

  1. A 3x3 convolution

    zi,j,c=∑u=−11∑v=−11∑c′=1CinKu,v,c′,c  xi+u, j+v, c′+bcz_{i,j,c} = \sum_{u=-1}^{1}\sum_{v=-1}^{1}\sum_{c'=1}^{C_{\text{in}}} K_{u,v,c',c}\; x_{i+u,\,j+v,\,c'} + b_c

    Each output value is a weighted sum of a 3 by 3 neighbourhood across all input channels. The same kernel KK is used at every position. Zero padding keeps height and width unchanged.

  2. The residual block

    al+1=relu⁡ ⁣(al+F(al)),F(a)=conv⁡2 ⁣(relu⁡(conv⁡1(a)))\mathbf{a}_{l+1} = \operatorname{relu}\!\big(\mathbf{a}_l + F(\mathbf{a}_l)\big), \qquad F(\mathbf{a}) = \operatorname{conv}_2\!\big(\operatorname{relu}(\operatorname{conv}_1(\mathbf{a}))\big)

    The block outputs its input plus a learned correction FF. If FF is zero the block passes its (non-negative) input through unchanged.

  3. Gradient through a block

    ∂L∂al=(I+JF⊤)(ml+1⊙∂L∂al+1)\frac{\partial L}{\partial \mathbf{a}_l} = \left(I + J_F^\top\right)\left(\mathbf{m}_{l+1} \odot \frac{\partial L}{\partial \mathbf{a}_{l+1}}\right)

    ml+1\mathbf{m}_{l+1} is the 0 or 1 mask of the block's final ReLU. The identity term II carries the gradient straight back even when JFJ_F is small. A plain block has only the JF⊤J_F^\top term.

  4. Global average pooling

    aˉc=1HW∑i=1H∑j=1Wai,j,c\bar{a}_c = \frac{1}{HW}\sum_{i=1}^{H}\sum_{j=1}^{W} a_{i,j,c}

    Each feature map is reduced to its mean, so the classifier sees one number per channel regardless of image size. Going backward, each position receives an equal 1/(HW)1/(HW) share of the gradient.

  5. The classifier and loss

    pk=eok∑jeoj,o=aˉ Wfc+bfc,L=−1n∑i=1nlog⁡pi,yip_k = \frac{e^{o_k}}{\sum_j e^{o_j}}, \quad \mathbf{o} = \bar{\mathbf{a}}\, W_{\text{fc}} + \mathbf{b}_{\text{fc}}, \qquad L = -\frac{1}{n}\sum_{i=1}^{n} \log p_{i, y_i}

    A linear layer on the pooled features, a softmax, and the mean cross-entropy over the batch.

  6. Parameters of one convolution

    Nconv=9 Cin Cout+CoutN_{\text{conv}} = 9\, C_{\text{in}}\, C_{\text{out}} + C_{\text{out}}

    Nine kernel weights for every pair of input and output channel, plus one bias per output channel. The count does not depend on the image size.

Symbols

al\mathbf{a}_l
feature maps entering block l (height by width by channels)
FF
the residual function: two convolutions with a ReLU between
K,bcK, b_c
convolution kernel and the bias of output channel c
Cin,CoutC_{\text{in}}, C_{\text{out}}
number of input and output channels
JFJ_F
Jacobian of F: how each output of F changes with each input
ml+1\mathbf{m}_{l+1}
mask that is 1 where the block's output is positive
H,WH, W
height and width of the feature maps
aˉ\bar{\mathbf{a}}
pooled features, one per channel
Wfc,bfcW_{\text{fc}}, \mathbf{b}_{\text{fc}}
weights and bias of the final linear layer
pkp_k
predicted probability of class k

Worked by hand

Count the parameters of the default network (channels 8, num_blocks 2) for single-channel images and 10 classes.

stem: 9×1×8+8=80\text{stem: } 9 \times 1 \times 8 + 8 = 80
one convolution inside a block: 9×8×8+8=584\text{one convolution inside a block: } 9 \times 8 \times 8 + 8 = 584
two blocks: 2×2×584=2336\text{two blocks: } 2 \times 2 \times 584 = 2336
classifier: 8×10+10=90\text{classifier: } 8 \times 10 + 10 = 90
total: 80+2336+90=2506\text{total: } 80 + 2336 + 90 = 2506

The network has 2506 parameters whether the images are 8 by 8 or 64 by 64, because convolutions share their weights across positions and the pooling removes the spatial size.

Visual example

Loading the example.

Try this

  • Raise the number of blocks from 2 to 12 and compare the two lines at block 1.
  • Switch the diagram to the network without shortcuts and click Shortcut to read how much gradient gets through.
  • Lower the starting weights to 0.4: the plain network loses about one power of ten per block.

Code sample

import numpy as np
from impl import ResNet
from config import ResNetConfig

rng = np.random.default_rng(0)
labels = rng.integers(0, 2, size=200)
images = 0.2 * rng.normal(size=(200, 8, 8))               # (n, height, width), one channel
for i, label in enumerate(labels):
    pos = rng.integers(0, 8)
    if label == 0:
        images[i, pos, :] += 1.0                           # class 0: a horizontal bar
    else:
        images[i, :, pos] += 1.0                           # class 1: a vertical bar

model = ResNet(ResNetConfig(channels=8, num_blocks=2, epochs=10)).fit(images, labels)
print((model.predict(images) == labels).mean())            # training accuracy, about 1.0
print(model.predict_proba(images[:2]).round(2))            # (2, 2), rows sum to 1
Read the implementation (199 lines)
"""Small residual network for image classification, with manual backpropagation and Adam.

NumPy only. Images are stored channels-last: (n, height, width, channels). The network is

    a_0     = relu(conv3x3(x))                               stem
    a_{i+1} = relu(a_i + conv3x3(relu(conv3x3(a_i))))        residual block, repeated num_blocks times
    logits  = mean over height and width of a_last, times fc_W, plus fc_b

Every convolution is 3x3 with stride 1 and zero padding 1, so height and width never change.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import ResNetConfig
except ImportError:  # run from the template's own folder
    from config import ResNetConfig


class _Adam:
    """Adam optimizer over a dict of NumPy arrays; `step` updates the arrays in place."""

    def __init__(self, params: dict, lr: float, beta1: float = 0.9, beta2: float = 0.999, eps: float = 1e-8) -> None:
        self.params, self.lr, self.beta1, self.beta2, self.eps = params, lr, beta1, beta2, eps
        self.m = {k: np.zeros_like(v) for k, v in params.items()}
        self.v = {k: np.zeros_like(v) for k, v in params.items()}
        self.t = 0

    def step(self, grads: dict) -> None:
        """Apply one update. grads: same keys and shapes as the parameters."""
        self.t += 1
        for k, g in grads.items():
            self.m[k] = self.beta1 * self.m[k] + (1 - self.beta1) * g
            self.v[k] = self.beta2 * self.v[k] + (1 - self.beta2) * g * g
            m_hat = self.m[k] / (1 - self.beta1**self.t)
            v_hat = self.v[k] / (1 - self.beta2**self.t)
            self.params[k] -= self.lr * m_hat / (np.sqrt(v_hat) + self.eps)

def conv3x3_forward(X: np.ndarray, W: np.ndarray, b: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    """3x3 convolution, stride 1, zero padding 1.

    X: (n, H, W, c_in). W: (c_in * 9, c_out), row index = channel * 9 + kernel_row * 3 + kernel_col.
    b: (c_out,). Returns (output (n, H, W, c_out), patches (n, H, W, c_in * 9)); the patches are needed by
    the backward pass.
    """
    n, height, width, c_in = X.shape
    padded = np.pad(X, ((0, 0), (1, 1), (1, 1), (0, 0)))
    windows = np.lib.stride_tricks.sliding_window_view(padded, (3, 3), axis=(1, 2))  # (n, H, W, c_in, 3, 3)
    patches = windows.reshape(n, height, width, c_in * 9)
    return patches @ W + b, patches


def conv3x3_backward(d_out: np.ndarray, patches: np.ndarray, W: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Backward pass of `conv3x3_forward`.

    d_out: gradient at the output, (n, H, W, c_out). patches, W: as returned by and given to the forward pass.
    Returns (dX (n, H, W, c_in), dW (c_in * 9, c_out), db (c_out,)).
    """
    n, height, width, c_out = d_out.shape
    c_in = W.shape[0] // 9
    dW = patches.reshape(-1, c_in * 9).T @ d_out.reshape(-1, c_out)
    db = d_out.sum(axis=(0, 1, 2))
    d_patches = (d_out @ W.T).reshape(n, height, width, c_in, 3, 3)
    d_padded = np.zeros((n, height + 2, width + 2, c_in))
    for i in range(3):
        for j in range(3):
            d_padded[:, i : i + height, j : j + width, :] += d_patches[..., i, j]
    return d_padded[:, 1:-1, 1:-1, :], dW, db


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)


def _as_images(X: np.ndarray) -> np.ndarray:
    """Accept (n, H, W) or (n, H, W, c) and return float (n, H, W, c)."""
    X = np.asarray(X, dtype=float)
    if X.ndim == 3:
        X = X[..., None]
    if X.ndim != 4:
        raise ValueError("images must have shape (n, H, W) or (n, H, W, channels)")
    return X


class ResNet:
    """Residual image classifier. After `fit`: `params`, `classes_`, `loss_history_` (mean loss per epoch)."""

    def __init__(self, config: ResNetConfig | None = None) -> None:
        self.config = config or ResNetConfig()
        self.params: dict[str, np.ndarray] = {}
        self.classes_: np.ndarray | None = None
        self.loss_history_: list[float] = []

    def initialize(self, in_channels: int, n_classes: int) -> None:
        """Create the weights for images with `in_channels` channels and `n_classes` classes (He initialisation)."""
        cfg = self.config
        rng = np.random.default_rng(cfg.seed)
        c = cfg.channels

        def conv_weight(c_in: int) -> np.ndarray:
            return np.sqrt(2.0 / (c_in * 9)) * rng.normal(size=(c_in * 9, c))

        self.params = {"stem_W": conv_weight(in_channels), "stem_b": np.zeros(c)}
        for i in range(cfg.num_blocks):
            self.params[f"block{i}_W1"] = conv_weight(c)
            self.params[f"block{i}_b1"] = np.zeros(c)
            self.params[f"block{i}_W2"] = np.zeros((c * 9, c)) if cfg.zero_init_residual else conv_weight(c)
            self.params[f"block{i}_b2"] = np.zeros(c)
        self.params["fc_W"] = np.sqrt(1.0 / c) * rng.normal(size=(c, n_classes))
        self.params["fc_b"] = np.zeros(n_classes)

    def _forward(self, X: np.ndarray) -> tuple[np.ndarray, dict]:
        """X: (n, H, W, c_in). Returns logits (n, n_classes) and the values the backward pass needs."""
        p = self.params
        cache: dict = {}
        z, cache["stem_patches"] = conv3x3_forward(X, p["stem_W"], p["stem_b"])
        a = np.maximum(z, 0.0)
        cache["a0"] = a
        for i in range(self.config.num_blocks):
            z1, cache[f"patches1_{i}"] = conv3x3_forward(a, p[f"block{i}_W1"], p[f"block{i}_b1"])
            h = np.maximum(z1, 0.0)
            residual, cache[f"patches2_{i}"] = conv3x3_forward(h, p[f"block{i}_W2"], p[f"block{i}_b2"])
            a = np.maximum(a + residual if self.config.use_skip else residual, 0.0)
            cache[f"h{i}"] = h
            cache[f"a{i + 1}"] = a
        pooled = a.mean(axis=(1, 2))  # global average pooling, (n, channels)
        cache["pooled"] = pooled
        return pooled @ p["fc_W"] + p["fc_b"], cache

    def loss_and_grads(self, X: np.ndarray, y: np.ndarray) -> tuple[float, dict]:
        """Mean cross-entropy on a batch and its gradient for every parameter.

        X: (n, H, W, c_in). y: class indices in 0..n_classes-1, shape (n,).
        """
        p = self.params
        n, height, width, _ = X.shape
        logits, cache = self._forward(X)
        prob = _softmax(logits)
        loss = -np.mean(np.log(prob[np.arange(n), y] + 1e-300))
        d_logits = prob
        d_logits[np.arange(n), y] -= 1.0
        d_logits /= n
        grads = {"fc_W": cache["pooled"].T @ d_logits, "fc_b": d_logits.sum(axis=0)}
        # Back through the average pooling: every position gets an equal share.
        d_pooled = d_logits @ p["fc_W"].T
        da = np.broadcast_to(d_pooled[:, None, None, :] / (height * width), cache["a0"].shape).copy()
        for i in reversed(range(self.config.num_blocks)):
            d_sum = da * (cache[f"a{i + 1}"] > 0)  # through the block's final relu
            dh, grads[f"block{i}_W2"], grads[f"block{i}_b2"] = conv3x3_backward(d_sum, cache[f"patches2_{i}"], p[f"block{i}_W2"])
            dz1 = dh * (cache[f"h{i}"] > 0)
            da, grads[f"block{i}_W1"], grads[f"block{i}_b1"] = conv3x3_backward(dz1, cache[f"patches1_{i}"], p[f"block{i}_W1"])
            if self.config.use_skip:
                da = da + d_sum  # the skip connection carries the gradient straight through
        dz = da * (cache["a0"] > 0)
        _, grads["stem_W"], grads["stem_b"] = conv3x3_backward(dz, cache["stem_patches"], p["stem_W"])
        return float(loss), grads

    def fit(self, X: np.ndarray, y: np.ndarray) -> "ResNet":
        """Train with mini-batch Adam. X: images, (n, H, W) or (n, H, W, c). y: labels of any hashable type, (n,)."""
        cfg = self.config
        X = _as_images(X)
        y = np.asarray(y)
        if len(X) != len(y):
            raise ValueError("X and y must have the same number of rows")
        self.classes_, target = np.unique(y, return_inverse=True)
        self.initialize(X.shape[3], len(self.classes_))
        optimizer = _Adam(self.params, cfg.lr)
        rng = np.random.default_rng(cfg.seed + 1)
        self.loss_history_ = []
        n = len(X)
        for _ in range(cfg.epochs):
            order = rng.permutation(n)
            total = 0.0
            for start in range(0, n, cfg.batch_size):
                rows = order[start : start + cfg.batch_size]
                loss, grads = self.loss_and_grads(X[rows], target[rows])
                optimizer.step(grads)
                total += loss * len(rows)
            self.loss_history_.append(total / n)
        return self

    def features(self, X: np.ndarray) -> np.ndarray:
        """Feature maps after the last block. X: (n, H, W) or (n, H, W, c). Returns (n, H, W, channels)."""
        if not self.params:
            raise RuntimeError("call fit (or initialize) before predicting")
        return self._forward(_as_images(X))[1][f"a{self.config.num_blocks}"]

    def predict_proba(self, X: np.ndarray) -> np.ndarray:
        """Class probabilities. X: (n, H, W) or (n, H, W, c). Returns (n, n_classes); columns follow `classes_`."""
        if not self.params:
            raise RuntimeError("call fit (or initialize) before predicting")
        return _softmax(self._forward(_as_images(X))[0])

    def predict(self, X: np.ndarray) -> np.ndarray:
        """Predicted labels. X: (n, H, W) or (n, H, W, c). Returns shape (n,), values from `classes_`."""
        index = self.predict_proba(X).argmax(axis=1)
        return self.classes_[index] if self.classes_ is not None else index
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
7, run with python3 -m unittest -v

Practice

Make a small image data set, for example 8 by 8 images with a bright horizontal or vertical bar, labelled by the bar's direction. Train ResNet with ResNetConfig num_blocks 6 and use_skip true, then with use_skip false, and plot both loss_history_ curves. Use loss_and_grads on one batch to compare the size of the stem_W gradient in the two networks.

Check on learning

  1. A plain 20-layer network can represent anything a 10-layer one can, by making 10 layers do nothing. Why is that hard for a plain network and easy for a residual one?
    A way to think about it

    Ask what weights a pair of convolutions with a ReLU would need in order to copy their input exactly, and compare with what a residual block needs to output.

  2. With zero_init_residual on, every block starts as the identity. What does the whole network compute at the first step, and why might that help training?
    A way to think about it

    Follow a signal through blocks whose residual is exactly zero. The network starts shallow in effect and grows deeper as the residuals move away from zero.

  3. In the gradient formula, what happens to the gradient at the stem after many blocks if the II term is removed and JFJ_F has entries well below 1?
    A way to think about it

    Multiply a small factor by itself once per block. Then put the II back and expand the product: one of its terms has no JFJ_F in it at all.

  4. The template uses global average pooling before the classifier. What would change if you flattened the feature maps instead?
    A way to think about it

    Count the classifier's parameters in both cases, and consider what happens when a test image has a different size or the object moves to a different corner.