Implement Per-Class IoU, Dice, Mean IoU and Mean Dice for Segmentation Masks
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Given integer label masks `y_true` and `y_pred` of identical shape (any number of dimensions), implement `segmentation_confusion_matrix`, `iou_per_class`, `dice_per_class`, `mean_iou` and `mean_dice`. Pixels whose true label equals `ignore_index` are dropped before counting (`ignore_index=None` disables this).
```python
def segmentation_confusion_matrix(y_true, y_pred, num_classes, ignore_index=255) -> np.ndarray: ...
def iou_per_class(y_true, y_pred, num_classes, ignore_index=255) -> np.ndarray: ...
def dice_per_class(y_true, y_pred, num_classes, ignore_index=255) -> np.ndarray: ...
def mean_iou(y_true, y_pred, num_classes, ignore_index=255) -> float: ...
def mean_dice(y_true, y_pred, num_classes, ignore_index=255) -> float: ...
```
Requirements:
- The confusion matrix is an `int64` array of shape `(num_classes, num_classes)`, with rows for the true class and columns for the predicted class.
- IoU is `TP / (TP + FP + FN)` and Dice is `2TP / (2TP + FP + FN)`, each returned as a float array of length `num_classes`.
- A class with a zero denominator gets `nan`. A class that is predicted but absent in the truth scores `0.0`.
- The means are Python floats that average only the non-`nan` classes, or `nan` if every class is `nan`.
- Raise `ValueError` on a shape mismatch, or on any kept label (true or predicted) outside `[0, num_classes)`.
Example:
```python
y_true = [[0, 0, 1], [1, 2, 255]]
y_pred = [[0, 1, 1], [1, 2, 255]]
segmentation_confusion_matrix(y_true, y_pred, num_classes=3)
# [[1, 1, 0], [0, 2, 0], [0, 0, 1]] (the 255 pixel is ignored)
iou_per_class(y_true, y_pred, num_classes=3) # [0.5, 0.6667, 1.0]
mean_iou(y_true, y_pred, num_classes=3) # 13/18, about 0.7222
dice_per_class(y_true, y_pred, num_classes=3) # [0.6667, 0.8, 1.0]
mean_dice(y_true, y_pred, num_classes=3) # 37/45, about 0.8222
# with num_classes=4, class 3 is nan and both means are unchanged
```
```hint Count everything once
Every metric here can be read off one confusion matrix. Think about how to count all (true, predicted) pixel pairs in a single vectorized step, without a Python loop over pixels or classes.
```
```hint Label pitfalls
Masks are often stored as `uint8`, and the void label 255 is outside the class range. Pay attention to the order of filtering, validation and any arithmetic you do on the labels.
```
### Constraints & Assumptions
- Masks are integer arrays or nested lists of identical shape with any number of dimensions, for example `(H, W)` or `(N, H, W)`.
- `num_classes` is a positive integer, and valid labels run from 0 to `num_classes - 1`.
- `ignore_index` applies to the true mask only.
### What a Strong Answer Covers
- Building the confusion matrix in one vectorized pass with the stated orientation (rows true, columns predicted).
- Deriving per-class TP, FP and FN from the matrix and applying the IoU and Dice formulas.
- The difference between an undefined class (`nan`) and a class that scores 0, and how each affects the means.
- The order of ignore filtering and label validation, and dtype pitfalls with `uint8` masks.
- Time and memory cost in terms of pixel count and class count.
### Follow-up Questions
- How would you compute mIoU over a whole dataset rather than per image?
- Why does Dice always score at least as high as IoU, and can you convert between them?
- How would you scale this to very large masks or many classes?
Overview: Implement pixel-level segmentation metrics in Python: a confusion matrix with an ignore label, per-class IoU and Dice, and mean IoU and mean Dice. Tests vectorized counting, the difference between undefined and zero-scoring classes, and careful label validation.