Sub topic 4
Semantic segmentation: one class per pixel
This chapter assumes you know basic Python and NumPy, how a convolutional network classifies a whole image, and how a loss function drives gradient-based training. Mask formats, IoU, and the encoder-decoder design each get their own chapter. Here the focus is the task: what a semantic segmentation model outputs, how it is trained, and where it goes wrong.
The task in one sentence
Semantic segmentation assigns exactly one class label to every pixel. The input is an image of shape (3, H, W). The output is a label map of shape (H, W) with an integer class ID at each position. Classes are things like road, sky, person, or tumor.
The model knows what each pixel belongs to. It does not know which object a pixel belongs to. If two people stand side by side, every pixel of both is labeled person, and the output has no boundary between them. Separating the two people is the job of instance segmentation, covered in a later chapter.
Typical uses are cases where category coverage matters more than counting objects:
- Driving scenes: which pixels are drivable road, sidewalk, or vegetation.
- Medical imaging: which pixels are tissue of a given type.
- Satellite imagery: land cover such as water, forest, or buildings.
- Photo editing: separating the sky or the background from the subject.
From image to label map
A semantic segmentation network does not output class IDs directly. It outputs one score per class per pixel, called logits. Then two steps turn scores into labels.
- The network produces logits of shape
(B, C, h, w), whereBis the batch size andCis the number of classes. - Taking the
argmaxover the class dimension gives an integer label per pixel. Softmax before the argmax is optional. It does not change which class wins, but you need it if you want per-pixel probabilities.
The logits often come out at a lower resolution than the input, for example one quarter of it. That is why the diagram has an upsampling step. Bilinear interpolation of the logits, not of the final labels, is the usual choice. Interpolating integer labels would blend IDs such as 3 and 7 into meaningless values.
Training as per-pixel classification
Semantic segmentation is image classification repeated at every pixel. The standard loss is cross-entropy computed per pixel and averaged over pixels. The target is a label map of integer class IDs, the same shape as the output.
The following example is complete and runs as shown. It fakes a low-resolution network output, upsamples it, computes the loss with an ignore label, and measures pixel accuracy over valid pixels only.
import torch
import torch.nn.functional as F
num_classes = 3
IGNORE = 255 # label for pixels that should not count
torch.manual_seed(0)
logits = torch.randn(1, num_classes, 4, 4) # network output at 1/4 resolution
target = torch.randint(0, num_classes, (1, 16, 16)) # full-resolution labels
target[0, :2, :] = IGNORE # pretend the top rows are unlabeled
# Upsample the logits (not the labels) to the label resolution.
logits_up = F.interpolate(logits, size=target.shape[-2:], mode="bilinear", align_corners=False)
loss = F.cross_entropy(logits_up, target, ignore_index=IGNORE)
pred = logits_up.argmax(dim=1) # (1, 16, 16) label map
valid = target != IGNORE
pixel_acc = (pred[valid] == target[valid]).float().mean()
print(f"loss={loss.item():.3f} pixel_acc={pixel_acc.item():.3f} pred_shape={tuple(pred.shape)}")Three details matter here:
F.cross_entropyexpects logits shaped(B, C, H, W)and targets shaped(B, H, W)asint64. Passing one-hot targets, or a target with a channel dimension, is a frequent shape error.ignore_indexexcludes pixels from both the loss and its gradient. Datasets use it for unlabeled regions, object borders, or pixels outside a crop.- The metric must skip the same pixels. Counting ignored pixels as errors or as correct predictions skews the number.
Class imbalance
Per-pixel cross-entropy treats every pixel equally, so large classes dominate. In a street scene, road and sky may cover half the pixels, while poles and traffic signs cover a fraction of a percent. A model can reach high pixel accuracy by getting the large regions right and ignoring the small classes.
Common remedies are:
- Class weights in cross-entropy, often inversely related to class frequency. Extreme weights can make training noisy.
- Online hard example mining, which averages the loss over only the hardest pixels.
- An overlap-based loss such as Dice, which scores the match between predicted and true regions directly. The losses chapter covers it in detail.
- Crops or sampling that show rare classes more often.
Evaluating: why pixel accuracy is not enough
Pixel accuracy is the fraction of valid pixels labeled correctly. It is easy to compute and easy to inflate. If 90% of the image is background, predicting background everywhere scores 90%. Semantic segmentation is therefore reported with mean IoU, which averages overlap per class so small classes count as much as large ones. The next chapters define IoU and mean IoU. For now, treat pixel accuracy as a sanity check and not as the headline result.
What the output cannot express
A label map has one label per pixel, which makes it compact and easy to work with. It also limits what you can ask of it.
| Question | Answerable from a semantic map? |
|---|---|
| Which pixels are road? | Yes |
| Is there any person in the image? | Yes |
| How many people are there? | Not reliably. Touching people merge into one region. |
| Which pixels belong to the left person? | No |
| Which pixels are sky, and which are unlabeled? | Only if the dataset has an explicit void or ignore class |
Connected-component labeling on a class region can approximate instances, but it fails whenever objects touch or overlap. This is the motivation for the instance and panoptic tasks that follow.
Common errors
- Interpolating labels. Resize masks with nearest-neighbor interpolation, and resize logits with bilinear. Bilinear on a label map creates invalid class IDs at borders.
- Mismatched augmentation. Any geometric transform, such as flips, crops, or scales, must be applied identically to the image and the mask. Color jitter applies to the image only.
- Wrong ignore handling. A label such as 255 in
targetwithnum_classes=3and noignore_indexmakescross_entropyfail with an out-of-range error on CPU, or a device-side assert on GPU. - Dtype of the target. Masks loaded as
uint8must be converted toint64before the loss. - Evaluating at the wrong resolution. Compute metrics against the original full-resolution ground truth, not a downsized copy. Otherwise thin structures disappear from the evaluation.
- Mismatched class order. Pretrained checkpoints have a fixed class list. Using a different dataset's ID mapping silently produces wrong labels.
Practical checks before moving on
- Print
target.unique()for a few batches. The values should be a subset of0..C-1plus your ignore ID. - Overfit a single image. A correct pipeline drives the loss near zero within a few hundred steps.
- Visualize the argmax map over the image. Checking alignment by eye catches flipped or transposed masks quickly.
Exercise
A segmentation model outputs logits of shape (2, 5, 64, 64), and the ground-truth masks have shape (2, 256, 256) with values 0 to 4 plus 255 for unlabeled pixels. Describe how to compute the training loss and the predicted label map at the mask resolution.
Show answer
Upsample the logits with bilinear interpolation to (2, 5, 256, 256), then call cross-entropy with the (2, 256, 256) int64 target and ignore_index=255. The predicted label map is the argmax over dimension 1 of the upsampled logits, giving shape (2, 256, 256). Metrics should skip pixels where the target equals 255.
Exercise
An image contains three cars parked bumper to bumper. A semantic segmentation model labels all car pixels correctly. Why can you still not read the number of cars from its output?
Show answer
The output stores only a class per pixel, so all three cars share the label "car" and form one connected region with no boundaries between them. Counting or separating the cars needs instance-level output.