Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 5: Computer Vision and CNNs

Semantic and instance segmentation

P5.1345 min●●○ IntermediateReviewed Dec 3, 2026

Why this matters for machine learning

A segmentation network labels every pixel, which gives shapes where a detector gives boxes. Its encoder-decoder with skip connections is one of the most reused designs in deep learning.

  • The original latent diffusion models use a U-Net with the same skip pattern to remove noise from an image. (P8.11: Latent diffusion (Stable Diffusion), coming soon)
  • Promptable and open-vocabulary segmentation models output masks and are judged with the same mask IoU. (P5.14: Foundation models for vision)
  • Vision Transformers are adapted to dense prediction with decoders and losses like these. (P5.15: Vision Transformers)

Before this: Padding, stride and dilation, Pooling and receptive fields, Object detection basics, Detection architectures

After this lesson you can

  • Tell semantic, instance and panoptic segmentation apart, and give the output shape and loss of a semantic network
  • Compute a transposed convolution by hand and give its output size (output padding included), and say what causes checkerboard artifacts
  • Describe FCN, U-Net and Mask R-CNN, including what a skip connection carries and what RoIAlign changes
  • Compute IoU, mean IoU, Dice and pixel accuracy, and say why pixel accuracy misleads

A detector draws a box around a pedestrian. A driving system also needs to know which pixels inside the box are the pedestrian and which are the road behind. A classifier gives one label for a whole picture. A segmentation network gives one label for each pixel. The problem is that the pooling and strides that made a classifier work (P5.6) threw the exact position away, and the output must be at full size again.

This lesson shows how three landmark designs get the resolution back: FCN (a fully convolutional classifier with up-sampling), U-Net (skip connections) and Mask R-CNN (a mask for every box of a detector). On the way it teaches the transposed convolution that P5.2 and P5.4 pointed to, and the losses and metrics for masks. Segment Anything is P5.14, Vision Transformers are P5.15, and training a segmentation network end to end is left out.

Three kinds of segmentation

Take a tiny 6×86\times8 picture with three objects: two of class 1 and one of class 2. The three tasks give different maps for it.

class map         object number
0 0 0 0 0 0 0 0   0 0 0 0 0 0 0 0
0 1 1 0 0 2 2 0   0 1 1 0 0 3 3 0
0 1 1 0 0 2 2 0   0 1 1 0 0 3 3 0
0 0 0 0 0 0 0 0   0 0 0 0 0 0 0 0
0 1 1 0 0 0 0 0   0 2 2 0 0 0 0 0
0 1 1 0 0 0 0 0   0 2 2 0 0 0 0 0
  • Semantic segmentation returns the left map: a class for every pixel, with 0 for the background. It does not count objects. If two objects of class 1 touch, they form one blob with no border between them.
  • Instance segmentation returns a separate mask for each detected object (the right map shows the same objects in one picture), with a class and a score, as a detector does (P5.11). Pixels that belong to no object get nothing, and two masks may overlap.
  • Panoptic segmentation (Kirillov, He, Girshick, Rother and Dollár, CVPR 2019) asks for both at once: every pixel gets a class, and a pixel of a countable thing (a person, a car) also gets an object number, while an amorphous stuff region (sky, road, grass) has a class and no number. This lesson only defines it.

The output: a label for every pixel

A semantic network takes an image (3,H,W)(3,H,W) (channels first, P5.1) and returns logits (C,H,W)(C,H,W) for CC classes: a vector of CC scores at each pixel. A softmax over the channel axis gives probabilities and the argmax over channels gives the label map (H,W)(H,W). For a batch the shapes are (N,3,H,W)(N,3,H,W), (N,C,H,W)(N,C,H,W) and (N,H,W)(N,H,W).

The target is a map of integer class numbers (N,H,W)(N,H,W), not one-hot. The loss is the cross-entropy of P1.E3 at every pixel, averaged:

L=−1HW∑i=1H∑j=1Wlog⁡p^i,j, yi,j,L=-\frac{1}{HW}\sum_{i=1}^{H}\sum_{j=1}^{W}\log \hat{p}_{i,j,\,y_{i,j}},

with p^i,j,c\hat{p}_{i,j,c} the softmax probability of class cc at pixel (i,j)(i,j) and yi,jy_{i,j} the true class. nn.CrossEntropyLoss takes the logits and the integer target directly, and skips pixels with a special label through ignore_index. When images are augmented (P4.18), each mask is flipped, cropped or scaled together with its image.

Here is the difficulty. Deep layers know what is in the image (large receptive fields, small maps, P5.6); shallow layers know where (large maps, small patches). A classifier backbone, 224×224224\times224 in and 7×77\times7 out (P5.9), keeps what and loses where. Two answers follow: get the resolution back with up-sampling and skips (FCN, U-Net), or never lose it with dilated convolutions (DeepLab).

Getting the resolution back

The simplest way to enlarge a map has no weights. Nearest-neighbour up-sampling copies each value into a block. Bilinear up-sampling lets each new value be a weighted mean of the four nearest old values, with larger weights for nearer ones. In one dimension, with the usual half-pixel convention (align_corners=False in PyTorch), doubling the size gives each new value the weights 0.750.75 and 0.250.25 on its two nearest old values. For the 2×22\times2 map (04812)\begin{pmatrix}0&4\\8&12\end{pmatrix} bilinear doubling gives a smooth ramp with rows 0,1,3,40,1,3,4, 2,3,5,62,3,5,6, 6,7,9,106,7,9,10 and 8,9,11,128,9,11,12; nearest-neighbour gives four flat 2×22\times2 blocks. Neither learns anything. A transposed convolution is a layer that up-samples and has weights to learn.

Transposed convolution: scatter

A convolution gathers: each output value is a dot product over a window of the input (P5.2). A transposed convolution scatters: each input value is multiplied by the whole kernel and the resulting block is added into the output, and the blocks are placed ss cells apart. It uses the same notation as P5.4: kernel size kk, stride ss, padding pp, dilation dd.

Take the input X=(1234)\mathbf{X}=\begin{pmatrix}1&2\\3&4\end{pmatrix}, the kernel K=(120012201)\mathbf{K}=\begin{pmatrix}1&2&0\\0&1&2\\2&0&1\end{pmatrix}, stride s=2s=2 and no padding.

The value 11 goes to the block at rows 0 to 2 and columns 0 to 2 as 1⋅K1\cdot\mathbf{K}; the value 22 goes two columns to the right (columns 2 to 4) as 2⋅K2\cdot\mathbf{K}; 33 goes two rows down as 3⋅K3\cdot\mathbf{K}; 44 goes two rows down and two columns right as 4⋅K4\cdot\mathbf{K}.

The four 3×33\times3 blocks cover a 5×55\times5 output. They overlap in row 2 and in column 2, and overlapping values add. The centre cell is reached by all four blocks: 1⋅K2,2+2⋅K2,0+3⋅K0,2+4⋅K0,0=1+4+0+4=91\cdot K_{2,2}+2\cdot K_{2,0}+3\cdot K_{0,2}+4\cdot K_{0,0}=1+4+0+4=9. The whole output is

Y=(12240012245698203648601104).\mathbf{Y}=\begin{pmatrix}1&2&2&4&0\\0&1&2&2&4\\5&6&9&8&2\\0&3&6&4&8\\6&0&11&0&4\end{pmatrix}.

As a formula (p=0p=0, d=1d=1): Ya,b=∑i,jXi,j Ka−is,  b−jsY_{a,b}=\sum_{i,j}X_{i,j}\,K_{a-is,\;b-js}, with kernel indices outside 0…k−10\ldots k-1 counting as 0. Nothing is flipped.

Why it is called transposed. A convolution is a matrix product y=Mx\mathbf{y}=\mathbf{M}\mathbf{x} (P5.2), and the transposed convolution multiplies by M⊤\mathbf{M}^\top with the same weights. This is what backpropagation does (P4.8): the transposed convolution is the gradient of a strided convolution with respect to its input. Put the 2×22\times2 map X\mathbf{X} in as the upstream gradient of the stride-2 convolution of a 5×55\times5 map with this kernel, and the gradient that comes out is the matrix Y\mathbf{Y} (the Code tab checks it with autograd).

The output size

Along one axis the output size is

Hout=(H−1) s−2p+d (k−1)+o+1,\begin{aligned} H_{\text{out}}&=(H-1)\,s-2p\\ &\quad+d\,(k-1)+o+1, \end{aligned}

the formula in the PyTorch nn.ConvTranspose2d documentation. (H−1)s+d(k−1)+1(H-1)s+d(k-1)+1 is where the last block ends (blocks start ss apart and span an effective kernel of d(k−1)+1d(k-1)+1 cells, P5.4), padding pp cuts pp rows and columns off each side (the opposite of a convolution), and oo is the output padding. For the example, (2−1)⋅2−0+2+0+1=5(2-1)\cdot2-0+2+0+1=5.

Output padding. With k=3k=3, s=2s=2, p=1p=1 a convolution maps both an 8-wide and a 7-wide input to 4, because of its floor (P5.4). Going back from 4, the transposed convolution gives 7 with o=0o=0 and 8 with o=1o=1: oo keeps oo more rows and columns at the bottom and right (zeros when p=0p=0, cells the padding would have cut off when p>0p>0). PyTorch requires oo to be smaller than the stride or the dilation.

The settings k=2k=2, s=2s=2, p=0p=0 and k=4k=4, s=2s=2, p=1p=1 double the size. A result of 0 or less is an error, as in P5.4.

See it: the transposed-convolution widget

Input Kernel k
Stride s Padding p Output padding

Output size: (2 − 1)·2 − 2·0 + (3 − 1) + 0 + 1 = 5
k is not divisible by s: uneven overlap

Input 2×2. Pick a cell, or use the arrow keys.
1234
Kernel 3×3 (the same for every input)
120012201
Output 5×5
12240012245698203648601104

Input cell (0, 0) has the value 1. It adds 1 × kernel to the dashed block: output rows 0 to 2, columns 0 to 2.

Dashed block: written by the picked input. Grey: cut off by padding.

Transposed convolution by scattering. Choose the input size, k, s, p and output padding; click a cell (or use the arrow keys) to pick an input. The dashed block is what that input writes, the blue frame is the part kept, grey is cut off. The second button shows how many inputs reach each cell. Nothing is animated.

Try it.

  1. The widget opens on the example above: input 2×22\times2, k=3k=3, s=2s=2. The output is 5×55\times5 and equals the matrix Y\mathbf{Y}. Pick the input cell with the value 4 and see the dashed block cover rows 2 to 4 and columns 2 to 4.
  2. Press How many inputs reach each cell. The cells of the middle row and column get 2, the centre gets 4 (all four blocks), and every other cell gets 1. The widget says that kk is not divisible by ss.
  3. Set k=4k=4 and p=1p=1 with the 3×33\times3 input: the size is (3−1)⋅2−2+3+0+1=6(3-1)\cdot2-2+3+0+1=6, double the input, and in the counts view every inner cell is reached by 4 inputs (2 along each axis).

Checkerboard artifacts

Look at the counts of step 2 along one axis. With k=3k=3 and s=2s=2 the overlap is 1, 1, 2, 1, 2, 1, 2, … , and in two dimensions the counts are 1, 2 and 4, so even an all-ones kernel gives a regular pattern. Odena, Dumoulin and Olah (“Deconvolution and Checkerboard Artifacts”, Distill, 2016) showed that such patterns appear when the kernel size is not divisible by the stride. Choosing kk divisible by ss (k=4k=4, s=2s=2 gives 2; k=sk=s gives 1) evens the count, though artifacts can still appear, because the learned weights are not uniform.

Their alternative is to resize first with a fixed method (nearest-neighbour gave the best results), then apply an ordinary stride-1 convolution: nn.Upsample(scale_factor=2, mode="nearest") followed by nn.Conv2d(c, c2, 3, padding=1). Away from the border every output cell is then reached by the same number of kernel positions.

Go deeper The same operation as an ordinary convolution

Insert s−1s-1 zeros between the input values, pad, and slide the flipped kernel with stride 1: this gives the same output, which is why the layer is also called a convolution with a fractional stride. P5.4 has the related full convolution.

FCN: the classifier that outputs a map

A landmark design for per-pixel prediction is the fully convolutional network (FCN) of Long, Shelhamer and Darrell (CVPR 2015). It combined three ideas.

  1. Convolutionalise the classifier. A fully connected layer on a C×h×wC\times h\times w map is a convolution whose kernel covers the whole map. The authors converted AlexNet, VGG and GoogLeNet this way, so the network accepts any image size and returns a grid of class scores. A 1×11\times1 convolution with CC channels gives the scores (21 for PASCAL VOC: 20 classes and background).
  2. Upsample the scores. The 2×2\times upsampling layers that fuse the skips start as bilinear interpolation and are learned; the final upsampling to the image size is fixed to bilinear.
  3. Add scores from earlier layers. The deepest layer has stride 32, so its prediction is coarse. The versions are named by the stride of the last upsampling: FCN-32s upsamples the stride-32 scores by 32 in one step. FCN-16s adds a 1×11\times1 score layer on the stride-16 layer (pool4) to the 2×2\times upsampled stride-32 scores, then upsamples by 16. FCN-8s repeats this with the stride-8 layer (pool3). The fusion is a sum of class scores.

The pattern stays: a deep path for meaning, a shallow path for position, and a fusion. The next network fuses features, at every level.

U-Net: a mirror image with skips

U-Net (Ronneberger, Fischer and Brox, MICCAI 2015) was made for segmenting cells in microscope images, where there are few labelled images. It has a contracting path (the encoder) and a mirror-image expanding path (the decoder), which gives the U shape.

  • Contracting path. Repeat two 3×33\times3 convolutions with ReLU, then 2×22\times2 max pooling; each pooling halves the size and the next convolution doubles the channels (64 up to 1024 in the paper).
  • Expanding path. Repeat an up-convolution that doubles the size and halves the channels (implementations often use a transposed convolution with k=s=2k=s=2, which has no overlap), a concatenation with the encoder map of the same size, and two 3×33\times3 convolutions.
  • Output. A 1×11\times1 convolution maps each feature vector to the CC class scores.

The concatenation is the skip connection: the decoder gets what from the up-sampled map below (meaning, but blurred) and where from the encoder map (exact edges, little meaning), and the convolutions that follow learn to combine them.

U-Net concatenates where FCN adds scores: the next convolution learns how to mix both, at the price of more input channels. A residual connection (P4.20) is different: it adds a block’s input to its own output inside a stage, while a U-Net skip carries a map across the network to the same resolution on the other side.

See it: the U-Net explorer

The widget draws the information flow of a small U-Net with padding 1 (sizes are kept) for a 3×32×323\times32\times32 input: three encoder levels and a bottleneck. It shows the tensor shape at every stage and lets you switch each skip off.

1/9 · Input image
Skips
skip 8²skip 16²skip 32²32²16²8²4²8²16²32²inoutpool ↘ (encoder)up-convolution ↗ (decoder)

Output of this stage: (3, 32, 32) (C, H, W) for one image

The input is a colour image, 3 channels of 32 by 32 pixels. The net will output one label per pixel.

True mask (object = blue, 295 of 1024 pixels)
The image has the full 32×32 detail

Idealised: a skip hands over the exact share of object pixels per cell; up-sampling is bilinear.

A U-Net on a 32 by 32 scene, stage by stage; the three Skip buttons switch a skip off. Left: the true mask. Right: what the decoder knows at this stage, and at the output the prediction and its IoU. Idealised, as the note says. Nothing is animated.

Try it.

  1. Step to stage 5, the bottleneck: the shape is (128,4,4)(128,4,4), and each of the 4×44\times4 cells summarises an 8×88\times8 patch of the input. Step on through the decoder: at each level the up-convolution and the skip are concatenated (for example (64,8,8)(64,8,8) and (64,8,8)(64,8,8) give (128,8,8)(128,8,8)) and two convolutions bring the channels back down. At the output the IoU with the true mask is 1.001.00.
  2. Press All skips off and go to stage 9. The decoder only has the 4×44\times4 summary, so the prediction is a blob: the IoU is 0.430.43 (129 of the 295 object pixels found, 8 wrongly marked, 166 missed). The thin line and the dot are gone, because a pooled cell that is mostly background rounds to background.
  3. Switch on only the 8×88\times8 skip: the IoU becomes 0.830.83. Add the 16×1616\times16 skip: 0.920.92. With the 32×3232\times32 skip off, 22 object pixels are still missed (the line and the dot, and the edge of the shapes). Switch it on and the IoU is 1.001.00.

A trained network is not this exact; the point is which information can reach the decoder.

Go deeper The original U-Net used valid convolutions

The paper’s convolutions were unpadded (valid, P5.2), so the decoder maps were smaller than the encoder maps and the encoder map was cropped before the concatenation. A 572×572572\times572 input gave a 388×388388\times388 output, so large images were processed in overlapping tiles. Most later implementations, including the one in the Code tab, use padding 1 and need no cropping.

The denoising network of the original latent diffusion models (P8.11) is also a U-Net.

Dilation instead of upsampling: DeepLab

The other answer is to lose less resolution. Replacing the strides of the last two stages of a ResNet by dilations (P5.4) keeps the receptive field and gives stride 8 instead of 32: a 28×2828\times28 map and not 7×77\times7 for a 224×224224\times224 image, with 16 times as many positions in the last stage (the one before has 4 times as many). The DeepLab family (Chen, Papandreou, Kokkinos, Murphy and Yuille) used atrous convolution (the dilated convolution, from the French à trous) from its first version (ICLR 2015). The journal version (IEEE TPAMI, 2018) added atrous spatial pyramid pooling (ASPP), dilated convolutions with several rates side by side, and the CRF post-processing of the early versions was dropped in DeepLabv3 (2017). torchvision’s fcn_resnet50 and deeplabv3_resnet50 use a dilated ResNet with stride 8 and a bilinear resize; fcn_resnet50 is not the FCN-8s of the paper.

Mask R-CNN: a mask for every box

Semantic segmentation cannot separate two touching cars. Mask R-CNN (He, Gkioxari, Dollár and Girshick, ICCV 2017) is Faster R-CNN (P5.12) with a third branch next to the class and box branches: for each region of interest (RoI), a small fully convolutional mask branch takes the 14×14×25614\times14\times256 RoI feature (the feature-pyramid version), applies four 3×33\times3 convolutions, a 2×22\times2 transposed convolution with stride 2 and a 1×11\times1 convolution, and outputs KK binary masks of size m×mm\times m, one per class, with m=28m=28 and K=80K=80 (COCO) in the paper’s figure.

  • A sigmoid per pixel and a loss on one class. The mask loss is the average binary cross-entropy over the pixels of the mask of the ground-truth class of the RoI only (for RoIs that match a ground-truth object). The classes do not compete inside the mask, and the class decision is left to the classification branch. At test time the mask of the predicted class is resized to the box and binarised at 0.5.
  • RoIAlign. RoI pooling (P5.12) rounds the RoI to whole feature cells. That is harmless for classification and bad for a mask that must match pixels.

Masks of two instances can overlap, and a mask is only as good as its box. In torchvision, maskrcnn_resnet50_fpn returns for each image a dictionary with boxes (N,4)(N,4), labels, scores and masks (N,1,H,W)(N,1,H,W): soft masks between 0 and 1, usually thresholded at 0.5.

RoIAlign: why rounding hurts

Take a feature map with stride 16 and an RoI that spans pixels 20 to 84 along xx, which is 1.251.25 to 5.255.25 in cell units. RoI pooling rounds to 1 and 5, which are pixels 16 and 80: both edges move by 4 pixels, a quarter of a cell. That hardly matters for a classifier and moves every boundary of a mask.

RoIAlign does not round. It divides the exact RoI into bins, places regularly spaced sample points in each bin (four per bin in the paper, whose results are not sensitive to this), reads the feature at each point by bilinear interpolation from the four nearest cell centres, and averages (or takes the maximum of) the samples. Example: a 4×44\times4 map with the value 10i+j10i+j in cell (i,j)(i,j), the RoI (0.7,0.7)(0.7,0.7) to (2.9,2.9)(2.9,2.9) in cell units and a 2×22\times2 output with one sample at each bin centre. At the point (1.25,1.25)(1.25,1.25) the nearest centres are cells (0,0)(0,0), (0,1)(0,1), (1,0)(1,0), (1,1)(1,1) with weights 0.06250.0625, 0.18750.1875, 0.18750.1875, 0.56250.5625 and values 00, 11, 1010, 1111, so the result is 8.258.25. All four points give

RoIAlign=(8.259.3519.2520.35),\text{RoIAlign}=\begin{pmatrix}8.25&9.35\\19.25&20.35\end{pmatrix},

the same numbers as torchvision.ops.roi_align with aligned=True.

Losses for imbalanced pixels

Most pixels are usually background, so plain per-pixel cross-entropy is dominated by the easy background. Three remedies are used.

  • Class weights. A larger weight for rare classes (weight= in nn.CrossEntropyLoss; P3.A10).
  • Focal loss. Down-weight well-classified pixels (RetinaNet’s loss, P5.12).
  • Dice loss. Compare overlap, not individual pixels.

The Dice score of a predicted mask AA and a true mask BB is

Dice=2 TP2 TP+FP+FN,\text{Dice}=\frac{2\,TP}{2\,TP+FP+FN},

with TPTP the pixels in both masks, FPFP the pixels only in the prediction and FNFN the pixels only in the truth (so TP=∣A∩B∣TP=\lvert A\cap B\rvert). It is the F1 score of P3.A9 on pixels, and Dice=2 IoU/(1+IoU)\text{Dice}=2\,\text{IoU}/(1+\text{IoU}) with the IoU of P5.11, so it is never smaller than the IoU.

To train with it, the predicted mask must be soft: use the probability pip_i of the class at pixel ii and the true value gig_i (0 or 1):

LDice=1−2∑ipi gi∑ipi+∑igi.L_{\text{Dice}}=1-\frac{2\sum_i p_i\,g_i}{\sum_i p_i+\sum_i g_i}.

The sums run over the whole image (per class), so the many background pixels do not swamp the loss. The V-Net paper (Milletari, Navab and Ahmadi, 3DV 2016) introduced this loss for medical volumes, with squares in the denominator. Implementations usually add a small constant to numerator and denominator so that an empty mask does not divide by zero, and Dice loss is often added to the cross-entropy and not used alone. The second code cell computes a soft Dice.

Metrics: IoU, mean IoU and pixel accuracy

Let nijn_{ij} be the number of pixels of true class ii that the network labelled jj (the confusion matrix of P3.A9, over pixels). Then:

pixel accuracy=∑inii∑i,jnij,IoUc=TPcTPc+FPc+FNc,\begin{aligned} \text{pixel accuracy}&=\frac{\sum_i n_{ii}}{\sum_{i,j}n_{ij}},\\[4pt] \text{IoU}_c&=\frac{TP_c}{TP_c+FP_c+FN_c}, \end{aligned}

with TPc=nccTP_c=n_{cc}, FPc=∑i≠cnicFP_c=\sum_{i\ne c}n_{ic} (the rest of column cc) and FNc=∑j≠cncjFN_c=\sum_{j\ne c}n_{cj} (the rest of row cc). The mean IoU (mIoU) averages IoUc\text{IoU}_c over the classes; it is the IoU of P5.11 on sets of pixels, and the counts are usually accumulated over the whole data set first. For instance segmentation the benchmark number is average precision (P5.11), with a match decided by the IoU of the masks, not the boxes.

Why pixel accuracy misleads. Take a 10×1010\times10 label map with a 6-pixel object (class 1) and a 4-pixel object (class 2). Predictor A labels everything background: pixel accuracy 0.900.90, IoUs 0.90.9, 00, 00, mean IoU 0.300.30. Predictor B finds 4 of the 6 and 2 of the 4 object pixels and adds 2 false pixels: pixel accuracy 0.940.94, barely above A’s, but mean IoU 0.6450.645. Pixel accuracy is dominated by the largest class; IoU counts each class’s false positives and misses. The code cell below computes both.

Three ways to see it

Intuition

The sketch and the tracing papers. The encoder squeezes the image into a small, meaningful summary (the bottleneck), like a rough sketch that says “a person on the left, a road below”. The decoder has to redraw the picture at full size from this sketch. Without help it can only draw blurry blobs. The skip connections are tracing papers saved on the way down, one per size, handed back on the way up: the decoder lays the sketch over the tracing paper of the same size and can follow the exact edges.

The stamp. A transposed convolution presses a rubber stamp (the kernel) once per input value, with ink proportional to the value, the stamps ss cells apart. Where stamps overlap, the ink adds; if the stamp size does not divide the step, some cells get two layers and some one. The pictures break in two places: a trained decoder learns to use the tracing paper and still makes mistakes, and a stamp cannot restore the values a convolution lost.

Math

Overlap. Along one axis the cell aa of the full grid is reached by the inputs ii with 0≤a−is≤k−10\le a-is\le k-1. For kk divisible by ss, every cell away from the border has k/sk/s such inputs. Otherwise the counts alternate between ⌊k/s⌋\lfloor k/s\rfloor and ⌈k/s⌉\lceil k/s\rceil.

Mask loss.

Lmask=1m2∑i,jℓij,ℓij=−gijlog⁡qij−(1−gij)log⁡(1−qij),\begin{aligned} L_{\text{mask}}&=\frac{1}{m^2}\sum_{i,j}\ell_{ij},\\[4pt] \ell_{ij}&=-g_{ij}\log q_{ij}\\ &\quad-(1-g_{ij})\log(1-q_{ij}), \end{aligned}

where ℓij\ell_{ij} is the binary cross-entropy at one pixel, qij=σ(zij)q_{ij}=\sigma(z_{ij}) with zijz_{ij} the logit of the ground-truth class’s mask at pixel (i,j)(i,j) of the m×mm\times m RoI mask, and gij∈{0,1}g_{ij}\in\{0,1\} its target. The identity Dice=2 IoU/(1+IoU)\text{Dice}=2\,\text{IoU}/(1+\text{IoU}) follows by substituting IoU=TP/(TP+FP+FN)\text{IoU}=TP/(TP+FP+FN).

Code

PyTorch, run locally with PyTorch 2.9.1. Tensor shapes are (N,C,H,W)(N,C,H,W) unless said otherwise.

import torch
import torch.nn as nn
import torch.nn.functional as F

# 1. Transposed convolution: the worked example
x = torch.tensor([[1., 2.], [3., 4.]]).reshape(1, 1, 2, 2)
K = torch.tensor([[1., 2., 0.], [0., 1., 2.], [2., 0., 1.]])
up = nn.ConvTranspose2d(1, 1, kernel_size=3, stride=2, bias=False)
up.weight.data = K.reshape(1, 1, 3, 3)    # (C_in, C_out, k, k)
print(up(x)[0, 0].int().numpy())

# the same numbers: gradient of a strided convolution
z = torch.zeros(1, 1, 5, 5, requires_grad=True)
F.conv2d(z, K.reshape(1, 1, 3, 3), stride=2).backward(x)
print(torch.equal(z.grad, up(x)))

# 2. Per-pixel loss: logits (N, C, H, W), target (N, H, W)
logits = torch.randn(4, 21, 64, 64)
target = torch.randint(0, 21, (4, 64, 64))
print('loss shape', F.cross_entropy(logits, target).shape)
print('labels', logits.argmax(dim=1).shape)

# 3. A small U-Net (padding 1, so sizes are kept)
def block(i, o):
    return nn.Sequential(nn.Conv2d(i, o, 3, padding=1), nn.ReLU(),
                         nn.Conv2d(o, o, 3, padding=1), nn.ReLU())

class UNet(nn.Module):
    def __init__(self, c_in=3, n_classes=2):
        super().__init__()
        self.enc = nn.ModuleList([block(c_in, 16), block(16, 32), block(32, 64)])
        self.neck = block(64, 128)
        self.up = nn.ModuleList([nn.ConvTranspose2d(c, c // 2, 2, stride=2)
                                 for c in (128, 64, 32)])
        self.dec = nn.ModuleList([block(128, 64), block(64, 32), block(32, 16)])
        self.head = nn.Conv2d(16, n_classes, 1)
        self.pool = nn.MaxPool2d(2)

    def forward(self, x):
        skips = []
        for e in self.enc:
            x = e(x)
            skips.append(x)                       # saved for the decoder
            x = self.pool(x)
        x = self.neck(x)
        for up, dec in zip(self.up, self.dec):
            x = up(x)                             # double size, halve channels
            x = torch.cat([skips.pop(), x], dim=1)  # concatenate on channels
            x = dec(x)
        return self.head(x)

net = UNet()
print(net(torch.zeros(1, 3, 32, 32)).shape)
print(sum(p.numel() for p in net.parameters()))

Output:

[[ 1  2  2  4  0]
 [ 0  1  2  2  4]
 [ 5  6  9  8  2]
 [ 0  3  6  4  8]
 [ 6  0 11  0  4]]
True
loss shape torch.Size([])
labels torch.Size([4, 64, 64])
torch.Size([1, 2, 32, 32])
482050

The first block is the matrix Y\mathbf{Y} of the lesson. The U-Net has 482,050 parameters; the same network without the skips (the decoder convolutions then read half as many channels) has 433,666.

Try it in Python

This cell runs in the browser with NumPy. It computes accuracy, IoU, mean IoU and Dice for the two predictors of the metrics section, and a soft Dice loss. (The transposed convolution is checked in the Code tab above.)

Pixel accuracy, IoU, mean IoU and Dice

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Common mistakes

Quiz

Check your understanding

  1. Why does a U-Net concatenate encoder maps into its decoder?

  2. A predicted object has 6 pixels, the true object has 6 pixels, and 4 pixels are shared by the two masks. What is the Dice score?

  3. In a 10×1010\times10 image with 90 background pixels and a 10-pixel object, a model labels every pixel background. What is its mean IoU over the two classes?

Exercises

  1. Compute the transposed convolution of (1234)\begin{pmatrix}1&2\\3&4\end{pmatrix} with the kernel (1234)\begin{pmatrix}1&2\\3&4\end{pmatrix}, s=2s=2, p=0p=0. What is the output size, and does the output have checkerboard overlap?
    Show answerThe size is (2−1)⋅2+2=4(2-1)\cdot2+2=4. Since k=sk=s the blocks do not overlap, so the output is the four blocks 1⋅K1\cdot\mathbf{K}, 2⋅K2\cdot\mathbf{K}, 3⋅K3\cdot\mathbf{K}, 4⋅K4\cdot\mathbf{K} side by side: rows [1,2,2,4][1,2,2,4], [3,4,6,8][3,4,6,8], [3,6,4,8][3,6,4,8], [9,12,12,16][9,12,12,16].
  2. In a U-Net level, the up-convolution produces 128 channels and the skip carries 128 channels. The next 3×33\times3 convolution has 128 output channels. How many weights (without biases) does it have, and how many would it have without the skip?
    Show answerWith the skip it reads 128+128=256128+128=256 channels: 3⋅3⋅256⋅128=294,9123\cdot3\cdot256\cdot128=294{,}912 weights. Without the skip it reads 128 channels: 3⋅3⋅128⋅128=147,4563\cdot3\cdot128\cdot128=147{,}456, half as many.
  3. The confusion matrix of three classes (rows true, columns predicted) is (5055103005015)\begin{pmatrix}50&5&5\\10&30&0\\5&0&15\end{pmatrix}. Compute the pixel accuracy and the mean IoU.
    Show answerPixel accuracy: (50+30+15)/120=0.792(50+30+15)/120=0.792. IoU of class 0: 50/(50+15+10)=0.66750/(50+15+10)=0.667 (its column holds 10+5=1510+5=15 false positives, its row 5+5=105+5=10 misses). Class 1: 30/(30+5+10)=0.66730/(30+5+10)=0.667. Class 2: 15/(15+5+5)=0.615/(15+5+5)=0.6. Mean IoU =0.644=0.644.

Next: P5.14 covers promptable segmentation, and P5.15 replaces the convolutional encoder with a Vision Transformer.

Key takeaways

  • Semantic segmentation gives each pixel a class, instance segmentation gives each object its own mask, and panoptic segmentation gives every pixel a class and, for countable things, an instance id.
  • A transposed convolution scatters each input value times the kernel into the output at (is,js)(is,js) and adds where blocks overlap. Along one axis the output size is (H−1)s−2p+d(k−1)+o+1(H-1)s-2p+d(k-1)+o+1. It is the gradient of a strided convolution with respect to its input, and restores the shape, not the values.
  • When kk is not divisible by ss the blocks overlap unevenly, which produces checkerboard artifacts. Resizing followed by a stride-1 convolution avoids them.
  • FCN turned classifiers into fully convolutional networks and added scores from earlier layers. U-Net mirrors the encoder with a decoder and concatenates the encoder map of the same size at every level, so the decoder regains the detail that pooling threw away.
  • Mask R-CNN is Faster R-CNN plus a mask branch per RoI, with RoIAlign instead of rounding the RoI to whole cells.
  • IoU is TP/(TP+FP+FN)TP/(TP+FP+FN) and Dice is 2TP/(2TP+FP+FN)2TP/(2TP+FP+FN). A model that labels everything background on an image that is 90%90\% background has pixel accuracy 0.900.90 and, for two classes, mean IoU 0.450.45.
Found a mistake? Tell us