Mean Intersection over Union (mIoU)
Implement a metric to evaluate the performance of semantic segmentation models, focusing on mean Intersection over Union (mIoU). In semantic segmentation, the goal is to assign a class label to each pixel in an image, and mIoU is a key metric for assessing the accuracy of these assignments. The concept of IoU is based on the idea of comparing the overlap between predicted and actual masks for each class, calculated as , where , , and represent true positives, false positives, and false negatives for class , respectively.
To calculate IoU for each class, one must consider the intersection and union of predicted and actual masks, which can be represented as . The process involves:
- Creating binary masks for each class in both predicted and actual labels.
- Computing the intersection (logical AND) and union (logical OR) of these masks.
- Calculating IoU for each class using the intersection and union.
Here counts only the classes that appear in pred or target (union ). A class absent from both has an undefined IoU and is skipped, not scored as 0. If no class appears at all, return 0.0.
This technique is widely used in autonomous vehicles for scene understanding.
Example
pred = [[0, 1, 1], [0, 1, 2], [2, 2, 2]] target = [[0, 0, 1], [0, 1, 1], [2, 2, 2]] num_classes = 3
0.6389
predandtargetare label maps: each entry is the class index of one pixel, drawn fromnum_classesclasses ().- Class 0: predicted at 2 pixels, true at 3. Both predictions are right and one true pixel is missed (top middle), so .
- Class 1: predicted at 3, true at 3, but only 2 coincide. One false positive (top middle) and one false negative (middle right) give .
- Class 2: predicted at 4, true at 3; all 3 true pixels are hit plus one extra (middle right), so .
- , shown to 4 decimal places.
- Notice that each mislabelled pixel costs two classes at once: middle right (true 1, predicted 2) is a false negative for class 1 and a false positive for class 2; likewise top middle (true 0, predicted 1) hurts classes 0 and 1.
Constraints
- pred: Predicted segmentation map (H, W) with class indices
- target: Ground truth segmentation (H, W)
- num_classes: Total number of classes
- Return: mIoU score (0-1)