Sub topic 18
Common pitfalls and practical checks
This chapter assumes you can read the label maps, mask stacks, and panoptic outputs from earlier chapters. It also assumes you know IoU, mask AP, and PQ, and can run PyTorch and NumPy code. Segmentation bugs rarely crash. They produce a model that trains, reports a plausible number, and is quietly wrong. The checks below catch the most common causes before you spend GPU hours on them.
Where errors enter the pipeline
Most failures fall into four stages: data, training, inference, and evaluation. The diagram shows the checks that belong to each one.
Data pitfalls
Invalid or shifted label values
A label map should contain only class IDs in the valid range plus the ignore value, commonly 255. Typical problems are an off-by-one shift between the dataset and the model (background is 0 in one and 1 in the other), a label stored as a float, and an RGB-coded PNG read as a single channel. Check every mask once, before training.
import numpy as np
def check_label_map(mask, num_classes, ignore_index=255):
problems = []
if mask.ndim != 2:
problems.append(f"expected 2-D mask, got shape {mask.shape}")
if not np.issubdtype(mask.dtype, np.integer):
problems.append(f"expected integer dtype, got {mask.dtype}")
for v in np.unique(mask):
if v != ignore_index and not (0 <= v < num_classes):
problems.append(f"unexpected label value {v}")
return problems
good = np.array([[0, 1], [2, 255]], dtype=np.uint8)
bad = np.array([[0, 1], [2, 21]], dtype=np.uint8)
print(check_label_map(good, num_classes=3)) # []
print(check_label_map(bad, num_classes=3)) # ['unexpected label value 21']Interpolating labels
Class IDs are categories, not quantities. Bilinear or bicubic resizing of a label map averages neighbouring IDs and creates classes that were never annotated. A boundary between class 0 and class 2 can produce class 1.
import numpy as np
row = np.array([0, 2])
print(np.interp(0.5, [0, 1], row)) # 1.0, a label that was never annotatedAlways resize masks with nearest-neighbour interpolation. Resize the image and its mask together, with the same random crop, flip, and scale in every augmentation. Resize logits or probabilities with bilinear interpolation instead, and take the argmax afterwards.
Panoptic ID encoding
Panoptic annotations are often stored as PNGs whose colour encodes the segment ID: id = R + 256 * G + 256 * 256 * B. Decoding in uint8 overflows silently.
import numpy as np
def decode_panoptic_png(rgb):
rgb = rgb.astype(np.int64) # cast first, or 256 * G overflows uint8
return rgb[..., 0] + 256 * rgb[..., 1] + 256 * 256 * rgb[..., 2]
rgb = np.array([[[1, 2, 0]]], dtype=np.uint8)
print(decode_panoptic_png(rgb)) # [[513]]Also avoid saving annotations as JPEG or resizing them with smoothing. Either one corrupts the IDs.
Ambiguous regions and crowds
Annotators mark blurry boundaries, occluded areas, and dense groups as "ignore" or "crowd". If you treat these as ordinary background, you punish the model for correct predictions. Keep the ignore value out of the loss and out of the evaluation. Handle crowd regions as your evaluation toolkit specifies, because the COCO tools match them differently from normal instances.
Training pitfalls
Ignore index and class imbalance
If 255 reaches the cross-entropy loss as a class index, you get an out-of-range error or, worse, a wrong target. In PyTorch, set ignore_index=255.
Imbalance is the other common problem. A class covering 1% of the pixels can be ignored completely while pixel accuracy stays above 95%. Options include class weights in cross-entropy, Dice loss (from the earlier chapter), or a sum of the two. Dice is sensitive on small foregrounds but noisier on tiny or empty masks, so the smoothing term eps matters. Cross-entropy alone gives smoother gradients, which is why many recipes combine the two.
Label conventions in detection-style models
Mask R-CNN in torchvision reserves label 0 for background. The labels you pass in training must start at 1. If your dataset uses 0 for the first real class, shift it.
Leakage and splits
Frames from the same video, or tiles from the same large image, put into both train and validation sets inflate scores. Split by scene, patient, or source image, not by individual crop.
Inference pitfalls
- Thresholds. The soft mask threshold (0.5 in the earlier Mask R-CNN example) and the confidence threshold change both the visual result and the metrics. Tune them on validation data and report the values you used.
- Mask resolution. Instance models predict a small mask per box, typically 28×28, then paste it into the box. Thin structures and sharp corners are lost at that step. Check the mask against the image at full resolution.
- Overlap in merged output. Instance masks can overlap each other and disagree with the semantic map. Panoptic output must not overlap, so apply a deterministic merge rule such as score order, and mark leftover thing pixels as void.
- Preprocessing mismatch. Use the same normalisation, channel order (RGB versus BGR), and input size as the pretrained weights expect.
Evaluation pitfalls
Per-image averages versus dataset-level IoU
The standard mIoU accumulates one confusion matrix over the entire dataset and computes IoU per class from it. Averaging per-image IoU values is a different number, and it is distorted by images where a class is absent or tiny.
import numpy as np
def confusion_matrix(pred, target, num_classes):
valid = (target >= 0) & (target < num_classes)
idx = num_classes * target[valid].astype(np.int64) + pred[valid].astype(np.int64)
return np.bincount(idx, minlength=num_classes ** 2).reshape(num_classes, num_classes)
def miou(cm):
tp = np.diag(cm).astype(np.float64)
union = cm.sum(axis=0) + cm.sum(axis=1) - np.diag(cm)
union = np.where(union == 0, np.nan, union)
return np.nanmean(tp / union)
pairs = [
(np.array([0, 0, 0, 0]), np.array([0, 0, 0, 0])), # class 1 absent
(np.array([0, 0, 0, 0]), np.array([1, 0, 0, 0])), # model misses the one class-1 pixel
]
per_image = np.mean([miou(confusion_matrix(p, t, 2)) for p, t in pairs])
total = sum(confusion_matrix(p, t, 2) for p, t in pairs)
print(per_image, miou(total)) # 0.6875 0.4375The per-image average rewards the empty image with a perfect score for class 0 and hides the miss. The dataset-level number shows it. Always say which one you report.
Missing classes
A class absent from both prediction and truth has an undefined IoU. Treating it as 0 punishes the model, and treating it as 1 flatters it. Use NaN and average only over classes that occur, as in the code above. Whichever convention you choose, state it.
Reading PQ correctly
PQ equals SQ times RQ. SQ is the mean IoU of matched segments and RQ is an F1-style recognition score. A low PQ with high SQ means the model finds too few segments, or too many false ones, rather than drawing them badly. Report PQ for things and stuff separately (PQ-Th and PQ-St), because a strong stuff score can mask weak instance separation. Mask AP and PQ also use different matching rules, so do not compare them directly.
Look at the output
Metrics hide systematic errors. Overlay predictions on 20 to 50 validation images, include the failures, and look at boundaries, small objects, and the ignore regions. A colour-mapped confusion matrix usually reveals which pair of classes is confused.
A practical checklist
- Count unique values in every mask and confirm they fit the label range.
- Overlay one mask on its image after each augmentation step.
- Confirm
ignore_indexin the loss and in the evaluator. - Resize masks with nearest-neighbour and logits with bilinear.
- Overfit a handful of images first. If the loss will not reach near zero, the bug is in the data or the labels.
- Report per-class IoU alongside mIoU, and the test resolution and thresholds.
Exercise
Your semantic model reports 96% pixel accuracy and a validation mIoU of 41%. A colleague suggests that the model is good because accuracy is high. Name the likely cause of the gap, and give two changes you would try.
Show answer
Class imbalance. Large classes such as road or sky dominate pixel accuracy, while rare classes have low IoU and pull the class-averaged mIoU down. Check per-class IoU to confirm. Two changes: add class weights or a Dice term to the cross-entropy loss, and confirm that the ignore index is excluded from both the loss and the metric. Oversampling images that contain the rare classes is another valid option.