The idea: a class for every pixel

A classifier looks at an image and says "cat". Semantic segmentation says, for every pixel, which class it belongs to: this pixel is cat, that one is background. The answer is a mask with the same height and width as the image. U-Net (Ronneberger, Fischer and Brox, 2015) is the classic network for it. It first shrinks the image to a small, deep feature map, then grows it back to full size, and it hands sharp detail across from the way down to the way up.

The U: a 128×128×1 image goes down through enc1 128×128×64, enc2 64×64×128, enc3 32×32×256, enc4 16×16×512 to the bottleneck 8×8×1024, then up through dec4 16×16×512, dec3, dec2 and dec1 128×128×64 to a 128×128 mask with 2 class scores. Four horizontal skip arrows copy each encoder map to the decoder level of the same size
Pools go down, up-convs go up, and skip connections cross the U at every level.

The page follows one network both ways. The network has 4 levels down, a bottleneck and 4 levels up, with two 3×3 convs (each followed by ReLU) at every level. Press Next Block to compute one block at a time.

Down the U: the encoder

The left side of the U is an ordinary CNN. At each level, two 3×3 convs keep the size (padding 1), then a 2×2 max-pool with stride 2 halves it. The number of filters doubles at each level: 64, 128, 256, 512, then 1024 at the bottleneck. So 128×128×1 becomes 8×8×1024. Each value at the bottom sees a large part of the image and knows what is there, but only roughly where. How one conv layer slides over the image is on Convolution in a CNN; how to work out each layer's shape and weight count is on A CNN Layer by Layer (Demo 1).

Up the U: transposed convolution

The decoder must make the map bigger again. U-Net uses a transposed convolution (also called up-convolution) with a 2×2 kernel and stride 2. Think of it as stamping: each input value multiplies a copy of the kernel, and that copy is written into the output. The stamp for input row r, column c starts at output row 2r, column 2c. The output size is

out = (in − 1)·S − 2P + K

With K = 2, S = 2, P = 0 this is (in − 1)·2 + 2 = 2·in: 8 → 16, 16 → 32. In the up-conv panel, X = [1 2 / 3 1] and K = [1 0 / 2 1] give a 4×4 output whose four 2×2 blocks are 1·K, 2·K, 3·K and 1·K (Demo 3). The kernel's weights are learned like any conv filter. The up-conv also halves the channels: 1024 → 512.

Left: kernel 2×2, stride 2. Four stamps tile a 4×4 output with no overlap; every cell gets 1 stamp. Right: kernel 3×3, stride 2. Four stamps overlap on a 5×5 output; the number of stamps per cell is 4 at the centre, 2 along the middle row and column, and 1 everywhere else
When the kernel equals the stride the stamps tile; when it is bigger they overlap unevenly.

If the kernel is bigger than the stride, stamps overlap and their values add up. With a 3×3 kernel and stride 2 the output is 5×5. The centre cell gets 4 stamps, the middle row and column get 2, the other cells 1 (Demo 4). That uneven count is the source of the checkerboard artifacts up-sampled images can show. A common fix is to resize first (nearest or bilinear) and then run an ordinary conv.

Skip connections: concatenate

The bottleneck has lost the fine detail, so up-sampling alone gives blurry, blocky edges. A skip connection copies the encoder map of the same size across the U. The decoder concatenates it with the up-sampled map along the channels, then runs two 3×3 convs on the result:

levelup-conv outputcopied from encoderafter concatafter two convs
dec416×16×512enc4 16×16×51216×16×102416×16×512
dec332×32×256enc3 32×32×25632×32×51232×32×256
dec264×64×128enc2 64×64×12864×64×25664×64×128
dec1128×128×64enc1 128×128×64128×128×128128×128×64

Concatenation stacks the two maps; it does not add them. So the channel counts add: 512 + 512 = 1024. (A ResNet skip adds values instead and keeps the channel count.) Finally a 1×1 conv with one filter per class turns each pixel's 64 numbers into 2 scores: 128×128×2.

The original U-Net: no padding, so crop

The 2015 paper used no padding. Each 3×3 conv then loses 2 pixels, so a 572×572 tile shrinks to 568 at enc1, 280 at enc2, 136, 64 and 28 at the bottleneck. On the way up, 28 → 56, but enc4 is 64×64. The encoder map is cropped to its centre 56×56 before the concat (Demo 2):

levelup-convcrop of encoder mapconcatafter two convs
dec428 → 5664 → 5656×56×102452×52×512
dec352 → 104136 → 104104×104×512100×100×256
dec2100 → 200280 → 200200×200×256196×196×128
dec1196 → 392568 → 392392×392×128388×388×64

So 572×572 in gives a 388×388×2 mask: the centre of the tile. The paper segments big images by sliding overlapping tiles and mirroring the border. Most code today uses padding 1, which keeps the sizes simple: the mask is as big as the image.

The mask and its score: IoU and Dice

Each pixel takes the class with the larger score (argmax). To grade a predicted mask, compare it with the true mask pixel by pixel and count TP (object found), FP (extra), FN (missed) and TN (background, correctly). Two scores look only at the object:

IoU  = TP / (TP + FP + FN)
Dice = 2·TP / (2·TP + FP + FN) = 2·IoU / (1 + IoU)
Two overlapping regions: the truth mask with 26 pixels and the prediction without skips with 24 pixels; they share 20 pixels. FN 6, TP 20, FP 4. IoU = 20 / 30 = 0.667. Dice = 2·20 / (26 + 24) = 40 / 50 = 0.800
IoU divides the overlap by the union; Dice divides twice the overlap by both sizes added.

On the 8×8 toy image the true object has 26 pixels. The predictions are made by hand to show the effect; they are not the output of a trained net.

predictionTPFPFNTNIoUDicepixel accuracy
with skips (Demo 5)2511370.9260.96296.9%
without skips, blocky (Demo 6)2046340.6670.80084.4%
all background (Demo 7)0026380059.4%

Dice is never below IoU, and both are 1 only for a perfect mask. Pixel accuracy is misleading: the mask that finds nothing still gets 59.4%, because most pixels are background. In medical images the object can be 1% of the pixels, and then "all background" scores 99%. That is why segmentation is scored with IoU or Dice, and why many nets are trained with a Dice loss next to the per-pixel cross-entropy. IoU for boxes and how detection uses it is on Object Detection: IoU and NMS; Dice is the F1 score of the object pixels (see Precision and Recall).

U-Net is not an autoencoder

An autoencoder also goes down to a small code and back up, but it must rebuild its own input through that code. A U-Net predicts something else (a mask), and the skip connections let detail bypass the bottleneck. The page on autoencoders covers the bottleneck itself.

See also the autoencoder, the same encoder–decoder shape without skip connections, trained to rebuild its input instead of predicting a mask.

See also the autoencoder, the same encoder–decoder shape without skip connections, trained to rebuild its input instead of predicting a mask.

What the page leaves out

Training: the per-pixel cross-entropy and Dice losses, and the paper's weight map that makes the thin borders between touching cells count more; data augmentation by elastic deformation; batch normalization and dropout; more than 2 classes (one score map per class, the same argmax); instance segmentation, which separates two touching objects of the same class (Mask R-CNN); later variants such as U-Net++, attention U-Net and 3D U-Net; and the overlap-tile strategy in detail.

On the mind map

Open the Machine Learning mind mapMachine LearningLearning setup: what feedback, how to scoreLearning setupLinear models: weighted sum w·x + bLinear modelsOther classic models: trees, margins, neighboursOther classic modelsUnsupervised: find structure without labelsUnsupervisedTraining: loss, gradient, small stepTrainingNeural networks: layers of σ(W·a + b)Neural networksArchitectures: how layers share informationArchitecturesLanguage models: predict the next tokenLanguage modelsLLM speed and tuning: cheaper to run, safer to useLLM speed and tuningRetrieval and agents: give the model data and toolsRetrieval and agentsConvolutionConvolutionslide a small kernel over the imageCNN layer by layerCNN layer by layerfc1 holds 78% of the weightsU-Net SegmentationSkips concat channels; score masks with DiceCanny Edge DetectionCanny Edge DetectionBlur, gradient, thin, two thresholds, linkHarris CornersHarris CornersR = det − k·trace² large: cornerHistogram EqualizationHistogram Equalizationrunning sum of counts = new levelsFrequency-domain filteringFrequency-domain filteringSharp cut in H rings; Gaussian does notOtsu ThresholdingOtsu ThresholdingMax between-class variance picks tHough TransformHough TransformCollinear pixels' curves cross in one cellErosion and DilationErosion and DilationErode = B fits, dilate = B hitsCNN vs TransformerCNN vs Transformerlocal field vs attention to allRNN, LSTM, GRURNN, LSTM, GRUhidden state; gates fight vanishingSelf-attentionSelf-attentionsoftmax(QKᵀ/√d_k) weights the VDiffusion modelDiffusion modellearn to predict the added noiseVAE vs GANVAE vs GANELBO loss vs generator-discriminator gameAutoencoderAutoencoder2-number bottleneck; rebuild inputContrastive learning, CLIPContrastive learning, CLIPmatch pairs in one space, InfoNCE lossResidual connectionsResidual connectionsx + F(x) lets gradients skip layersOpen the Machine Learning mind mapMachine Learninghow layers share informationArchitecturesConvolutionConvolutionslide a small kernel over the imageCNN layer by layerCNN layer by layerfc1 holds 78% of the weightsU-Net SegmentationSkips concat channels; score masks with DiceCanny Edge DetectionCanny Edge DetectionBlur, gradient, thin, two thresholds, linkHarris CornersHarris CornersR = det − k·trace² large: cornerHistogram EqualizationHistogram Equalizationrunning sum of counts = new levelsFrequency-domain filteringFrequency-domain filteringSharp cut in H rings; Gaussian does notOtsu ThresholdingOtsu ThresholdingMax between-class variance picks tHough TransformHough TransformCollinear pixels' curves cross in one cellErosion and DilationErosion and DilationErode = B fits, dilate = B hitsCNN vs TransformerCNN vs Transformerlocal field vs attention to allRNN, LSTM, GRURNN, LSTM, GRUhidden state; gates fight vanishingSelf-attentionSelf-attentionsoftmax(QKᵀ/√d_k) weights the VDiffusion modelDiffusion modellearn to predict the added noiseVAE vs GANVAE vs GANELBO loss vs generator-discriminator gameAutoencoderAutoencoder2-number bottleneck; rebuild inputContrastive learning, CLIPContrastive learning, CLIPmatch pairs in one space, InfoNCE lossResidual connectionsResidual connectionsx + F(x) lets gradients skip layers
This page on the Machine Learning mind map · 88 pages in 10 branches · open it to see the whole map and test yourself in recall mode.