You are computing mean Intersection over Union (mIoU) over class labels for semantic segmentation masks.
1. Background Knowledge
In semantic segmentation , each pixel in an image is assigned a class label (e.g., background, road, car). A model outputs a predicted mask, and we compare it to the ground truth mask to evaluate how well it identified each class.
Intersection over Union (IoU) for a class c c c measures how well the predicted region for that class overlaps with the true region. It is defined as:
I o U c = ∣ prediction c ∩ ground_truth c ∣ ∣ prediction c ∪ ground_truth c ∣ IoU_c = \frac{| \text{prediction}_c \cap \text{ground\_truth}_c |}{| \text{prediction}_c \cup \text{ground\_truth}_c |} I o U c = ∣ prediction c ∪ ground_truth c ∣ ∣ prediction c ∩ ground_truth c ∣
This can be rewritten using TP, FP, FN counts for pixels of class c c c :
I o U c = T P c T P c + F P c + F N c IoU_c = \frac{TP_c}{TP_c + FP_c + FN_c} I o U c = T P c + F P c + F N c T P c
Mean IoU (mIoU) is the average IoU over all classes being evaluated:
m I o U = 1 C ′ ∑ c ∈ S I o U c mIoU = \frac{1}{C'} \sum_{c \in \mathcal{S}} IoU_c m I o U = C ′ 1 c ∈ S ∑ I o U c
where S \mathcal{S} S is the set of classes that actually appear in either prediction or ground truth (you skip classes where T P c = F P c = F N c = 0 TP_c = FP_c = FN_c = 0 T P c = F P c = F N c = 0 ).
2. Algorithm / General Approach
High-level pattern:
Loop over classes c ∈ { 0 , … , C − 1 } c \in \{0, \dots, C-1\} c ∈ { 0 , … , C − 1 } .
For each class, compute TP, FP, FN by comparing pred and gt pixel-wise.
If all of TP, FP, FN are zero , skip this class (it doesn’t appear at all).
Otherwise, compute:
I o U c = T P c T P c + F P c + F N c IoU_c = \frac{TP_c}{TP_c + FP_c + FN_c} I o U c = T P c + F P c + F N c T P c
Collect all valid I o U c IoU_c I o U c values and average them to get mIoU.
This is essentially building a per-class confusion summary (TP/FP/FN) from the full confusion matrix and then turning those into IoUs.
3. Step-by-Step Strategy
Assume pred and gt are same shape arrays of integer class labels (e.g., H x W or N x H x W).
Identify number of classes
Either given as C, or infer as max(pred.max(), gt.max()) + 1.
Optional: flatten arrays
For convenience, convert masks to 1D arrays:
pred_flat = pred.reshape(-1)
gt_flat = gt.reshape(-1)
Initialize accumulators
Arrays or dicts for TP, FP, FN per class:
TP = * C
FP = * C
FN = * C
PRO Continue the full explanation You're reading the free preview. Unlock the complete walkthrough, the code editor, test runner and reference solution with Premium.
Become a Premium Subscriber