Sign in

U-Net

U-Net (U-shaped encoder-decoder network)

An encoder-decoder network for per-pixel prediction that shrinks the image to gather context, then grows it back while reusing the fine detail saved on the way down.

Overview

Marking which pixels of an image belong to an object needs a wide view to know what the object is, and exact positions to draw its outline. Shrinking the image gives the wide view but blurs positions. A U-Net shrinks the image step by step to learn what is there, then enlarges it step by step back to full size. At each enlarging step it is handed a copy of the sharp feature maps from the matching shrinking step. These copies, the skip connections, let the output combine the wide view with exact locations. This template is a small NumPy version with one convolution per level.

A short history

Olaf Ronneberger, Philipp Fischer and Thomas Brox at the University of Freiburg published U-Net in 2015 for segmenting biomedical images. Their problem was a shortage of annotated images. The design, a contracting path, an expanding path and skip connections between matching levels, trained well from few examples with heavy augmentation and won cell tracking and segmentation challenges. It later became the usual denoising network in diffusion models.

How it works

  1. Encoder: at each level apply a 3x3 convolution and a ReLU, save the result, then halve height and width with 2x2 max pooling. The channel count doubles at each level.
  2. Bottleneck: apply one more convolution and ReLU at the smallest resolution, where each value summarises a large patch of the image.
  3. Decoder: at each level double height and width by repeating each pixel, then concatenate the saved encoder maps of the same resolution along the channel axis.
  4. Apply a 3x3 convolution and a ReLU to the concatenated maps, halving the channel count again.
  5. A final 1x1 convolution maps the full-resolution features to the output channels, one value per pixel.
  6. Score every pixel with sigmoid cross-entropy for masks, or squared error for real-valued targets, and backpropagate. Each saved encoder map receives gradient from both the pooling path and its skip.

Watch out for

  • Height and width must be divisible by 2D2^{D}. Otherwise pooling and upsampling do not return to the original size and the skip maps cannot be concatenated.
  • When the object covers few pixels, a network that predicts background everywhere already has a low mean loss. Check the overlap with the true mask as well as the loss.
  • With use_skips off, all detail must squeeze through the low-resolution bottleneck and output edges come out blurred and blocky.
  • This small version uses one convolution per level and nearest-neighbour upsampling. Full U-Nets use two or more convolutions per level and normalisation layers.

Use cases

When to use it

Tasks whose output is an image aligned with the input: segmentation masks, denoising, depth or edge maps. The same shape of network is the usual noise predictor inside diffusion models.

In industry

Medical imaging
Outlining organs, tumours or cells in scans and microscope images, the task the network was created for.
Remote sensing
Marking buildings, roads or flooded areas pixel by pixel in satellite and aerial images.
Generative imaging
The denoising network inside diffusion models such as Stable Diffusion, which must output an image the same size as its input.

Choosing it: what must hold

  • A task whose output has the same grid layout as the input, such as a mask or a cleaned image.
  • Pixel-level labels for training, which are costly to produce.
  • Input sizes compatible with the repeated halving and doubling of resolution.

When to choose something else

IfUse instead
You need one label for the whole imageA CNN or a ResNet
You need boxes around objects, not exact outlinesAn object detection model
The data is not on a gridA graph neural network (GNN) for graphs, or an MLP for plain feature vectors

Math foundations

  1. Encoder level

    ei=relu⁡ ⁣(conv⁡3×3(xi)),xi+1=pool⁡(ei),i=0,…,D−1\mathbf{e}_i = \operatorname{relu}\!\big(\operatorname{conv}_{3 \times 3}(\mathbf{x}_i)\big), \qquad \mathbf{x}_{i+1} = \operatorname{pool}(\mathbf{e}_i), \qquad i = 0, \dots, D - 1

    Each level extracts features, keeps a copy ei\mathbf{e}_i for later, and passes a half-size version down. x0\mathbf{x}_0 is the input image.

  2. Max pooling

    pool⁡(x)i,j=max⁡u,v∈{0,1}x2i+u,  2j+v\operatorname{pool}(\mathbf{x})_{i,j} = \max_{u, v \in \{0, 1\}} x_{2i + u,\; 2j + v}

    Each output pixel is the largest of a 2 by 2 block, per channel. Height and width are halved. Going backward, the gradient goes only to the position that held the maximum.

  3. Upsampling

    up⁡(x)i,j=x⌊i/2⌋,  ⌊j/2⌋\operatorname{up}(\mathbf{x})_{i,j} = x_{\lfloor i/2 \rfloor,\; \lfloor j/2 \rfloor}

    Nearest-neighbour upsampling: every pixel becomes a 2 by 2 block of copies. Going backward, the gradients of the four copies are summed.

  4. Decoder level with skip

    di=relu⁡ ⁣(conv⁡3×3([up⁡(di+1),  ei])),i=D−1,…,0\mathbf{d}_i = \operatorname{relu}\!\Big(\operatorname{conv}_{3 \times 3}\big(\big[\operatorname{up}(\mathbf{d}_{i+1}),\; \mathbf{e}_i\big]\big)\Big), \qquad i = D - 1, \dots, 0

    The square brackets mean concatenation along channels. The convolution sees coarse context from below and fine detail from the encoder side by side. dD\mathbf{d}_D is the bottleneck output.

  5. Sizes at level i

    resolution=H2i×W2i,channels=B⋅2i\text{resolution} = \frac{H}{2^{i}} \times \frac{W}{2^{i}}, \qquad \text{channels} = B \cdot 2^{i}

    Each step down halves the resolution and doubles the channels. The decoder convolution at level ii therefore takes B⋅2i+1+B⋅2iB \cdot 2^{i+1} + B \cdot 2^{i} input channels.

  6. Per-pixel loss for masks

    L=−1N∑j=1N[yjlog⁡σ(oj)+(1−yj)log⁡(1−σ(oj))]L = -\frac{1}{N}\sum_{j=1}^{N} \big[ y_j \log \sigma(o_j) + (1 - y_j) \log\big(1 - \sigma(o_j)\big) \big]

    Binary cross-entropy averaged over all NN output values in the batch. Each pixel is its own small classification problem. With loss set to mse this becomes half the mean squared error.

Symbols

xi\mathbf{x}_i
input to encoder level i
ei\mathbf{e}_i
saved feature maps of encoder level i
di\mathbf{d}_i
feature maps of decoder level i
DD
number of downsampling steps, depth
BB
channels at the first level, base_channels
H,WH, W
height and width of the input image
[⋅,⋅][\cdot, \cdot]
concatenation along the channel axis
oj,yjo_j, y_j
output logit and 0 or 1 target of one output value
σ\sigma
the sigmoid function
NN
number of output values in the batch

Worked by hand

Follow the shapes through the default network (depth 2, base_channels 8) for one 16 by 16 single-channel image. Shapes are height by width by channels.

e0:16×16×8  →  pool  →  8×8×8\mathbf{e}_0: 16 \times 16 \times 8 \;\to\; \text{pool} \;\to\; 8 \times 8 \times 8
e1:8×8×16  →  pool  →  4×4×16\mathbf{e}_1: 8 \times 8 \times 16 \;\to\; \text{pool} \;\to\; 4 \times 4 \times 16
bottleneck:4×4×32\text{bottleneck}: 4 \times 4 \times 32
level 1: up→8×8×32,concat e1→8×8×48,conv→8×8×16\text{level 1: up} \to 8 \times 8 \times 32, \quad \text{concat } \mathbf{e}_1 \to 8 \times 8 \times 48, \quad \text{conv} \to 8 \times 8 \times 16
level 0: up→16×16×16,concat e0→16×16×24,conv→16×16×8\text{level 0: up} \to 16 \times 16 \times 16, \quad \text{concat } \mathbf{e}_0 \to 16 \times 16 \times 24, \quad \text{conv} \to 16 \times 16 \times 8
output:16×16×1\text{output}: 16 \times 16 \times 1

The output has the input's height and width. The decoder convolutions take 48 and 24 input channels because of the skips. Without skips they would take 32 and 16.

Visual example

Loading the example.

Try this

  • Press Run and watch the predicted mask form. It stays nearly empty for the first 50 steps or so.
  • Switch the skip connections off, press Run again, and compare the overlap on the thin bar.
  • Click Bottleneck, then Encoder level 0, to see how coarse each level is.

Code sample

import numpy as np
from impl import UNet
from config import UNetConfig

rng = np.random.default_rng(0)
images = 0.3 * rng.normal(size=(120, 16, 16))             # (n, height, width), one channel
masks = np.zeros((120, 16, 16))
for i in range(120):
    r, c = rng.integers(0, 10, size=2)
    size = rng.integers(4, 7)
    masks[i, r : r + size, c : c + size] = 1.0             # the target: a square
    images[i] += masks[i]                                  # the square is brighter than the noisy background

model = UNet(UNetConfig(base_channels=4, depth=2, epochs=15)).fit(images, masks)
pred = model.predict(images[:1])                           # (1, 16, 16, 1) probabilities
print(((pred[..., 0] > 0.5) == (masks[:1] > 0.5)).mean())  # share of pixels labelled correctly, about 0.99
Read the implementation (240 lines)
"""Small U-Net with manual backpropagation and Adam.

NumPy only. Images are stored channels-last: (n, height, width, channels). With depth D and base width B:

    encoder level i (i = 0..D-1):  e_i = relu(conv3x3(x)) with B * 2^i channels, then x = maxpool2x2(e_i)
    bottleneck:                    x = relu(conv3x3(x)) with B * 2^D channels
    decoder level i (i = D-1..0):  x = relu(conv3x3(concat(upsample2x(x), e_i))) with B * 2^i channels
    output:                        x W_out + b_out, a 1x1 convolution to out_channels

Convolutions are 3x3, stride 1, zero padding 1, so only pooling and upsampling change the resolution.
"""
from __future__ import annotations

import numpy as np

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


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.
    Returns (output (n, H, W, c_out), patches (n, H, W, c_in * 9)); the patches are needed going backward.
    """
    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: (n, H, W, c_out). Returns (dX (n, H, W, c_in), dW, db)."""
    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 maxpool2x2_forward(X: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    """2x2 max pooling, stride 2. X: (n, H, W, c) with even H and W.

    Returns (pooled (n, H/2, W/2, c), share (n, H/2, 2, W/2, 2, c)). `share` says how much of each output's
    gradient goes to each of its four inputs: 1 for the maximum, split equally between tied maxima.
    """
    n, height, width, c = X.shape
    blocks = X.reshape(n, height // 2, 2, width // 2, 2, c)
    pooled = blocks.max(axis=(2, 4))
    is_max = blocks == pooled[:, :, None, :, None, :]
    return pooled, is_max / is_max.sum(axis=(2, 4), keepdims=True)


def maxpool2x2_backward(d_pooled: np.ndarray, share: np.ndarray) -> np.ndarray:
    """Send each pooled gradient back to the position(s) of the maximum. Returns (n, H, W, c)."""
    n, half_h, _, half_w, _, c = share.shape
    return (share * d_pooled[:, :, None, :, None, :]).reshape(n, half_h * 2, half_w * 2, c)


def upsample2x_forward(X: np.ndarray) -> np.ndarray:
    """Nearest-neighbour upsampling: every pixel becomes a 2x2 block. (n, H, W, c) -> (n, 2H, 2W, c)."""
    return X.repeat(2, axis=1).repeat(2, axis=2)


def upsample2x_backward(d_out: np.ndarray) -> np.ndarray:
    """Sum the gradient over each 2x2 block. (n, 2H, 2W, c) -> (n, H, W, c)."""
    n, height, width, c = d_out.shape
    return d_out.reshape(n, height // 2, 2, width // 2, 2, c).sum(axis=(2, 4))


def _sigmoid(z: np.ndarray) -> np.ndarray:
    e = np.exp(-np.abs(z))
    return np.where(z >= 0, 1.0 / (1.0 + e), e / (1.0 + e))


class UNet:
    """U-Net for per-pixel prediction. After `fit`: `params`, `loss_history_` (mean loss per epoch)."""

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

    def initialize(self) -> None:
        """Create the weights from the config (He initialisation, zero biases)."""
        cfg = self.config
        rng = np.random.default_rng(cfg.seed)

        def conv(name: str, c_in: int, c_out: int) -> None:
            self.params[f"{name}_W"] = np.sqrt(2.0 / (c_in * 9)) * rng.normal(size=(c_in * 9, c_out))
            self.params[f"{name}_b"] = np.zeros(c_out)

        self.params = {}
        widths = [cfg.base_channels * 2**i for i in range(cfg.depth + 1)]
        c_in = cfg.in_channels
        for i in range(cfg.depth):
            conv(f"enc{i}", c_in, widths[i])
            c_in = widths[i]
        conv("mid", c_in, widths[cfg.depth])
        for i in reversed(range(cfg.depth)):
            skip = widths[i] if cfg.use_skips else 0
            conv(f"dec{i}", widths[i + 1] + skip, widths[i])
        self.params["out_W"] = np.sqrt(1.0 / widths[0]) * rng.normal(size=(widths[0], cfg.out_channels))
        self.params["out_b"] = np.zeros(cfg.out_channels)

    def _images(self, X: np.ndarray, channels: int, what: str) -> np.ndarray:
        """Accept (n, H, W) or (n, H, W, c), check the sizes, return float (n, H, W, c)."""
        X = np.asarray(X, dtype=float)
        if X.ndim == 3:
            X = X[..., None]
        if X.ndim != 4 or X.shape[3] != channels:
            raise ValueError(f"{what} must have shape (n, H, W, {channels})")
        factor = 2**self.config.depth
        if X.shape[1] % factor or X.shape[2] % factor:
            raise ValueError(f"height and width must be divisible by {factor} for depth {self.config.depth}")
        return X

    def _forward(self, X: np.ndarray) -> tuple[np.ndarray, dict]:
        """X: (n, H, W, in_channels). Returns the output map (n, H, W, out_channels) and the backward cache."""
        p = self.params
        cfg = self.config
        cache: dict = {}
        x = X
        for i in range(cfg.depth):
            z, cache[f"enc{i}_patches"] = conv3x3_forward(x, p[f"enc{i}_W"], p[f"enc{i}_b"])
            cache[f"enc{i}"] = np.maximum(z, 0.0)
            x, cache[f"pool{i}"] = maxpool2x2_forward(cache[f"enc{i}"])
        z, cache["mid_patches"] = conv3x3_forward(x, p["mid_W"], p["mid_b"])
        x = cache["mid"] = np.maximum(z, 0.0)
        for i in reversed(range(cfg.depth)):
            x = upsample2x_forward(x)
            if cfg.use_skips:
                x = np.concatenate([x, cache[f"enc{i}"]], axis=3)
            z, cache[f"dec{i}_patches"] = conv3x3_forward(x, p[f"dec{i}_W"], p[f"dec{i}_b"])
            x = cache[f"dec{i}"] = np.maximum(z, 0.0)
        return x @ p["out_W"] + p["out_b"], cache

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

        X: (n, H, W, in_channels). Y: (n, H, W, out_channels); 0/1 masks for `bce`, real values for `mse`.
        """
        p = self.params
        cfg = self.config
        out, cache = self._forward(X)
        if cfg.loss == "bce":
            loss = np.mean(np.logaddexp(0.0, out) - Y * out)
            d_out = (_sigmoid(out) - Y) / out.size
        else:
            loss = 0.5 * np.mean((out - Y) ** 2)
            d_out = (out - Y) / out.size
        last = cache["dec0"]
        grads = {
            "out_W": last.reshape(-1, last.shape[3]).T @ d_out.reshape(-1, cfg.out_channels),
            "out_b": d_out.sum(axis=(0, 1, 2)),
        }
        dx = d_out @ p["out_W"].T
        d_skip: dict[int, np.ndarray] = {}
        for i in range(cfg.depth):
            dz = dx * (cache[f"dec{i}"] > 0)
            d_cat, grads[f"dec{i}_W"], grads[f"dec{i}_b"] = conv3x3_backward(dz, cache[f"dec{i}_patches"], p[f"dec{i}_W"])
            if cfg.use_skips:
                # The concatenation splits the gradient: first the upsampled channels, then the skip channels.
                c_up = d_cat.shape[3] - cache[f"enc{i}"].shape[3]
                d_skip[i] = d_cat[..., c_up:]
                d_cat = d_cat[..., :c_up]
            dx = upsample2x_backward(d_cat)
        dz = dx * (cache["mid"] > 0)
        dx, grads["mid_W"], grads["mid_b"] = conv3x3_backward(dz, cache["mid_patches"], p["mid_W"])
        for i in reversed(range(cfg.depth)):
            d_enc = maxpool2x2_backward(dx, cache[f"pool{i}"])
            if cfg.use_skips:
                d_enc = d_enc + d_skip[i]  # the encoder output feeds both the pooling and the skip
            dz = d_enc * (cache[f"enc{i}"] > 0)
            dx, grads[f"enc{i}_W"], grads[f"enc{i}_b"] = conv3x3_backward(dz, cache[f"enc{i}_patches"], p[f"enc{i}_W"])
        return float(loss), grads

    def fit(self, X: np.ndarray, Y: np.ndarray) -> "UNet":
        """Train with mini-batch Adam.

        X: images, (n, H, W) or (n, H, W, in_channels). Y: targets with the same height and width, (n, H, W)
        or (n, H, W, out_channels).
        """
        cfg = self.config
        X = self._images(X, cfg.in_channels, "X")
        Y = self._images(Y, cfg.out_channels, "Y")
        if X.shape[:3] != Y.shape[:3]:
            raise ValueError("X and Y must have the same number of images, height and width")
        self.initialize()
        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], Y[rows])
                optimizer.step(grads)
                total += loss * len(rows)
            self.loss_history_.append(total / n)
        return self

    def forward(self, X: np.ndarray) -> np.ndarray:
        """Raw output map (logits for `bce`). X: (n, H, W) or (n, H, W, in_channels). Returns (n, H, W, out_channels)."""
        return self._forward(self._images(X, self.config.in_channels, "X"))[0]

    def predict(self, X: np.ndarray) -> np.ndarray:
        """Per-pixel probabilities for `bce`, values for `mse`. Returns (n, H, W, out_channels)."""
        out = self.forward(X)
        return _sigmoid(out) if self.config.loss == "bce" else out
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
7, run with python3 -m unittest -v

Practice

Generate 16 by 16 images containing one bright rectangle on a noisy background, with the rectangle's mask as the target. Fit UNet with the default UNetConfig and compare predict against the true masks. Train again with use_skips set to false, and look closely at the rectangle's edges in the two outputs. Compare the final values of loss_history_.

Check on learning

  1. Why does the network shrink the image at all? What would a stack of 3x3 convolutions at full resolution be unable to see?
    A way to think about it

    Work out how many pixels of the input one output value depends on after three 3x3 convolutions, with and without pooling between them.

  2. The skip connection concatenates encoder features rather than adding them as a ResNet does. What does concatenation let the next convolution do?
    A way to think about it

    After a sum the two sources can no longer be told apart. With concatenation the convolution has separate weights for each source and can weigh them differently.

  3. With the skips turned off, the mask's edges come out blocky. Explain where the exact edge position was lost.
    A way to think about it

    After two poolings one bottleneck value covers a 4 by 4 patch. Ask what information remains about where inside that patch the edge was.

  4. An object covers 2 percent of each image. The loss is low but the predicted mask is empty. Why, and what would you change?
    A way to think about it

    Compute the mean loss of predicting background everywhere. The 98 percent of easy pixels dominate the average, so consider reweighting or a loss based on overlap.