Sub topic 7
Measuring overlap: IoU and mean IoU
Assume you know basic Python, NumPy, convolutional neural networks, and the difference between a prediction and a ground-truth label. This chapter uses label maps: one integer class ID per pixel.
Intersection over Union
Intersection over Union, or IoU, measures how much a predicted region overlaps the correct region. For one class:
\mathrm{IoU} = \frac{TP}{TP + FP + FN}Here, TP is the number of pixels correctly predicted as the class. FP is the number of pixels incorrectly predicted as the class. FN is the number of true class pixels that the model missed.
The denominator is the union of the predicted and true regions. IoU ranges from 0 to 1, where 1 means perfect overlap.
| Prediction and target | Meaning |
|---|---|
| True positive | Both maps assign this pixel to the class |
| False positive | Prediction assigns the class, but the target does not |
| False negative | Target assigns the class, but the prediction does not |
For a multiclass segmentation, calculate one IoU for each class. Then calculate mean IoU, or mIoU, by averaging the class IoUs. A class absent from both maps has no meaningful union, so it is usually excluded from the average.
import numpy as np
def confusion_matrix(pred, target, num_classes):
valid = (target >= 0) & (target < num_classes)
idx = num_classes * target[valid] + pred[valid]
counts = np.bincount(idx, minlength=num_classes**2)
return counts.reshape(num_classes, num_classes)
def per_class_iou(cm):
true_positive = np.diag(cm).astype(float)
union = cm.sum(axis=0) + cm.sum(axis=1) - true_positive
union = np.where(union == 0, np.nan, union)
return true_positive / 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)
ious = per_class_iou(cm)
print(cm)
print(ious)
print("mIoU:", np.nanmean(ious))The confusion matrix has ground-truth classes as rows and predicted classes as columns. Its diagonal contains true positives. For class c, the row sum counts all target pixels of c, and the column sum counts all predicted pixels of c.
Why mIoU can hide problems
A simple average gives every evaluated class equal weight. A rare class therefore affects mIoU as much as a common class. This is useful when every class matters equally, but it can hide poor performance on individual classes. Always report per-class IoU with mIoU.
Also decide whether the background is a class. Including a large, easy background region can raise the overall score even when small objects are poorly segmented.
Exercise
A class has 80 true positives, 20 false positives, and 40 false negatives. What are its IoU and its contribution to mIoU?
Show answer
IoU = 80 / (80 + 20 + 40) = 80 / 140 ≈ 0.571. Its contribution to mIoU is this value, provided the class is included in the evaluated classes.