Sub topic 7
Measuring overlap: IoU and mean IoU
This chapter assumes you can read NumPy code and know what a label map is (an integer class ID for every pixel). It also assumes you know what a confusion matrix is in classification. Here you learn to score a segmentation by how well predicted regions overlap ground-truth regions.
Why pixel accuracy is not enough
Pixel accuracy is the fraction of pixels whose predicted class equals the true class. It is easy to compute and easy to fool. Suppose 96% of an image is road and 4% is a pedestrian. A model that predicts "road" everywhere scores 96% accuracy and finds no pedestrians at all.
Intersection over Union (IoU), also called the Jaccard index, fixes this. It compares the predicted region and the true region of one class:
IoU = |P ∩ G| / |P ∪ G|
Here P is the set of pixels predicted as the class and G is the set of pixels that truly belong to it. IoU is 1 for a perfect match and 0 for no overlap. Because the union includes both missed pixels and extra pixels, a model cannot score well by ignoring a small class.
IoU for one binary mask
For a single mask, such as one instance or one class, IoU is a direct set computation on boolean arrays.
import numpy as np
def mask_iou(a, b):
# a, b: boolean arrays of the same shape
inter = np.logical_and(a, b).sum()
union = np.logical_or(a, b).sum()
if union == 0:
return np.nan # both masks empty: IoU is undefined
return inter / union
a = np.zeros((4, 4), dtype=bool); a[:2, :] = True # 8 pixels
b = np.zeros((4, 4), dtype=bool); b[1:3, :] = True # 8 pixels, 4 shared
print(mask_iou(a, b)) # 4 / 12 = 0.333...Returning nan for two empty masks is a choice. Returning 1 or 0 would silently change averages, so keep it explicit and skip such cases when averaging.
IoU from true positives, false positives and false negatives
For one class, every pixel falls into one of three groups:
- True positives (TP): predicted as the class and truly the class.
- False positives (FP): predicted as the class but truly something else.
- False negatives (FN): truly the class but predicted as something else.
The union is TP + FP + FN, so:
IoU = TP / (TP + FP + FN)
For a full label map, a confusion matrix holds these counts for all classes at once. With rows as ground truth and columns as predictions, class c has TP at the diagonal cell, FN as the rest of its row, and FP as the rest of its column.
Computing mean IoU
Mean IoU (mIoU) is the average of per-class IoU values. Averaging per class gives a rare class the same weight as a common one, which is why mIoU is the standard semantic segmentation score.
The code below builds the confusion matrix with one bincount call. Each pixel pair (truth, prediction) is encoded as a single index num_classes * truth + prediction, so counting indices fills the matrix.
import numpy as np
def confusion_matrix(pred, target, num_classes):
# pred and target are integer label maps of the same shape.
# Pixels whose target is outside [0, num_classes) (e.g. 255 = ignore) are skipped.
valid = (target >= 0) & (target < num_classes)
idx = num_classes * target[valid].astype(np.int64) + pred[valid].astype(np.int64)
counts = np.bincount(idx, minlength=num_classes ** 2)
return counts.reshape(num_classes, num_classes) # rows: ground truth, cols: prediction
def per_class_iou(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) # class absent from both prediction and truth
return tp / union
pred = np.array([[0, 0, 1], [1, 1, 2]])
target = np.array([[0, 1, 1], [1, 2, 2]])
cm = confusion_matrix(pred, target, num_classes=3)
iou = per_class_iou(cm)
print(iou, np.nanmean(iou)) # [0.5 0.5 0.5] 0.5Two details matter here. The union is the column sum plus the row sum minus the diagonal, because the diagonal would otherwise be counted twice. And the nan for an absent class, combined with np.nanmean, keeps classes that never appear from dragging the average down.
Accuracy versus mIoU on imbalanced data
The next example repeats the road-and-pedestrian problem. It uses the functions above, so run it after the previous block.
import numpy as np
target = np.zeros((10, 10), dtype=np.int64)
target[:2, :2] = 1 # 4 pixels of class 1, 96 pixels of class 0
pred = np.zeros((10, 10), dtype=np.int64) # model predicts class 0 everywhere
cm = confusion_matrix(pred, target, num_classes=2)
pixel_acc = np.diag(cm).sum() / cm.sum()
iou = per_class_iou(cm)
print(pixel_acc) # 0.96
print(iou, np.nanmean(iou)) # [0.96 0. ] 0.48Pixel accuracy reports 0.96. The class-1 IoU is 0, and mIoU is 0.48, which reflects that the model found nothing of interest.
Dataset-level versus per-image averaging
There are two ways to aggregate over many images, and they give different numbers.
| Method | How it works | Effect |
|---|---|---|
| Dataset-level | Sum confusion matrices over all images, then compute IoU once | Large objects dominate; this is the usual benchmark protocol |
| Per-image | Compute IoU per image, then average | Every image counts equally; a tiny object in one image can swing the score |
Accumulate the confusion matrix with cm_total += confusion_matrix(...) inside your evaluation loop, and compute IoU only at the end. Averaging per-image mIoU values is a common mistake, and it is not comparable to published results.
Relation to Dice and to instance matching
The Dice coefficient is 2·TP / (2·TP + FP + FN). It relates to IoU by Dice = 2·IoU / (1 + IoU). The two always rank a single prediction the same way, but Dice is larger, and averages of the two across images do not map onto each other exactly. Always say which one you report.
IoU is also the matching rule for instances. Mask AP and panoptic quality, covered in later chapters, count a predicted mask as a match for a ground-truth mask only when their IoU passes a threshold. In panoptic quality that threshold is 0.5, which guarantees each ground-truth segment matches at most one prediction.
Common errors
- Passing label maps with different integer types or shapes, which gives wrong indices or a crash in
bincount. - Forgetting the ignore label. Counting 255 pixels as a class corrupts the matrix. The code above filters them using the target, so keep ignore labels in the target.
- Evaluating after resizing the prediction with bilinear interpolation of class IDs. Resize logits or use nearest-neighbor on labels, and evaluate at the original ground-truth resolution.
- Averaging over classes that never occur in the test set and counting them as 0.
- Swapping the axes of the matrix. Rows are truth and columns are predictions in this chapter, so row sums are FN-side and column sums are FP-side.
Exercise
A model is evaluated on 3 classes and produces this confusion matrix (rows = ground truth, columns = prediction): [[50, 10, 0], [5, 30, 5], [0, 10, 40]]. Compute the IoU of class 1 and the pixel accuracy.
Show answer
For class 1, TP = 30. The row sum is 5 + 30 + 5 = 40, so FN = 10. The column sum is 10 + 30 + 10 = 50, so FP = 20. IoU = 30 / (30 + 20 + 10) = 0.5. Pixel accuracy = (50 + 30 + 40) / 150 = 0.8.