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 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 (channels first, P5.1) and returns logits for classes: a vector of scores at each pixel. A softmax over the channel axis gives probabilities and the argmax over channels gives the label map . For a batch the shapes are , and .
The target is a map of integer class numbers , not one-hot. The loss is the cross-entropy of P1.E3 at every pixel, averaged:
with the softmax probability of class at pixel and 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, in and 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 and on its two nearest old values. For the map bilinear doubling gives a smooth ramp with rows , , and ; nearest-neighbour gives four flat 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 cells apart. It uses the same notation as P5.4: kernel size , stride , padding , dilation .
Take the input , the kernel , stride and no padding.
The value goes to the block at rows 0 to 2 and columns 0 to 2 as ; the value goes two columns to the right (columns 2 to 4) as ; goes two rows down as ; goes two rows down and two columns right as .
The four blocks cover a output. They overlap in row 2 and in column 2, and overlapping values add. The centre cell is reached by all four blocks: . The whole output is
As a formula (, ): , with kernel indices outside counting as 0. Nothing is flipped.
Why it is called transposed. A convolution is a matrix product (P5.2), and the transposed convolution multiplies by 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 map in as the upstream gradient of the stride-2 convolution of a map with this kernel, and the gradient that comes out is the matrix (the Code tab checks it with autograd).
The output size
Along one axis the output size is
the formula in the PyTorch nn.ConvTranspose2d documentation. is where the last block ends (blocks start apart and span an effective kernel of cells, P5.4), padding cuts rows and columns off each side (the opposite of a convolution), and is the output padding. For the example, .
Output padding. With , , 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 and 8 with : keeps more rows and columns at the bottom and right (zeros when , cells the padding would have cut off when ). PyTorch requires to be smaller than the stride or the dilation.
The settings , , and , , double the size. A result of 0 or less is an error, as in P5.4.
See it: the transposed-convolution widget
Try it.
- The widget opens on the example above: input , , . The output is and equals the matrix . Pick the input cell with the value 4 and see the dashed block cover rows 2 to 4 and columns 2 to 4.
- 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 is not divisible by .
- Set and with the input: the size is , 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 and 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 divisible by (, gives 2; 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 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.
- Convolutionalise the classifier. A fully connected layer on a 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 convolution with channels gives the scores (21 for PASCAL VOC: 20 classes and background).
- Upsample the scores. The upsampling layers that fuse the skips start as bilinear interpolation and are learned; the final upsampling to the image size is fixed to bilinear.
- 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 score layer on the stride-16 layer (
pool4) to the 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 convolutions with ReLU, then 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 , which has no overlap), a concatenation with the encoder map of the same size, and two convolutions.
- Output. A convolution maps each feature vector to the 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 input: three encoder levels and a bottleneck. It shows the tensor shape at every stage and lets you switch each skip off.
Try it.
- Step to stage 5, the bottleneck: the shape is , and each of the cells summarises an patch of the input. Step on through the decoder: at each level the up-convolution and the skip are concatenated (for example and give ) and two convolutions bring the channels back down. At the output the IoU with the true mask is .
- Press All skips off and go to stage 9. The decoder only has the summary, so the prediction is a blob: the IoU is (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.
- Switch on only the skip: the IoU becomes . Add the skip: . With the 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 .
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 input gave a 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 map and not for a 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 RoI feature (the feature-pyramid version), applies four convolutions, a transposed convolution with stride 2 and a convolution, and outputs binary masks of size , one per class, with and (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 , labels, scores and masks : 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 , which is to 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 map with the value in cell , the RoI to in cell units and a output with one sample at each bin centre. At the point the nearest centres are cells , , , with weights , , , and values , , , , so the result is . All four points give
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=innn.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 and a true mask is
with the pixels in both masks, the pixels only in the prediction and the pixels only in the truth (so ). It is the F1 score of P3.A9 on pixels, and 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 of the class at pixel and the true value (0 or 1):
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 be the number of pixels of true class that the network labelled (the confusion matrix of P3.A9, over pixels). Then:
with , (the rest of column ) and (the rest of row ). The mean IoU (mIoU) averages 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 label map with a 6-pixel object (class 1) and a 4-pixel object (class 2). Predictor A labels everything background: pixel accuracy , IoUs , , , mean IoU . Predictor B finds 4 of the 6 and 2 of the 4 object pixels and adds 2 false pixels: pixel accuracy , barely above A’s, but mean IoU . 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 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 of the full grid is reached by the inputs with . For divisible by , every cell away from the border has such inputs. Otherwise the counts alternate between and .
Mask loss.
where is the binary cross-entropy at one pixel, with the logit of the ground-truth class’s mask at pixel of the RoI mask, and its target. The identity follows by substituting .
Code
PyTorch, run locally with PyTorch 2.9.1. Tensor shapes are 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])
482050The first block is the matrix 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.)
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Common mistakes
Quiz
Check your understanding
Why does a U-Net concatenate encoder maps into its decoder?
Pooling discards the exact position of edges, so the narrow bottleneck cannot restore them; the encoder map of the same size still holds them. Concatenation adds no layer (it only stacks channels), and it adds weights, because the next convolution reads more channels. The decoder does not reuse the encoder weights, and the encoder maps are computed from the image, not from the labels.
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?
Dice is . The value is the IoU of the same masks (); Dice and IoU are different numbers for the same pair. The value forgets the factor 2 in the numerator. Equal sizes do not make the masks match: they share only 4 of 6 pixels.
In a 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?
The background has , (the object pixels labelled background) and , so its IoU is . The object has , so its IoU is 0, and the mean is . Pixel accuracy is , but mean IoU is a different quantity. The value counts classes instead of overlap, and the background pixels count in the IoU of the background class.
Exercises
- Compute the transposed convolution of with the kernel , , . What is the output size, and does the output have checkerboard overlap?
Show answer
The size is . Since the blocks do not overlap, so the output is the four blocks , , , side by side: rows , , , . - In a U-Net level, the up-convolution produces 128 channels and the skip carries 128 channels. The next convolution has 128 output channels. How many weights (without biases) does it have, and how many would it have without the skip?
Show answer
With the skip it reads channels: weights. Without the skip it reads 128 channels: , half as many. - The confusion matrix of three classes (rows true, columns predicted) is . Compute the pixel accuracy and the mean IoU.
Show answer
Pixel accuracy: . IoU of class 0: (its column holds false positives, its row misses). Class 1: . Class 2: . Mean IoU .
Next: P5.14 covers promptable segmentation, and P5.15 replaces the convolutional encoder with a Vision Transformer.