Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fix confusion_matrix crash on an empty batch (#4845)

Mohammad Hijjawi7ddf731bd080
diff --git a/changelog.d/4845.fixed.md b/changelog.d/4845.fixed.md
new file mode 100644
index 000000000..587126bf2
--- /dev/null
+++ b/changelog.d/4845.fixed.md
@@ -0,0 +1 @@
+`confusion_matrix` and `mean_iou` return an empty `(0, K, K)` / `(0, K)` result for a zero-length batch instead of raising `RuntimeError` on `view(0, -1)`.
diff --git a/kornia/metrics/confusion_matrix.py b/kornia/metrics/confusion_matrix.py
index 5f0eed2b7..b94cb231d 100644
--- a/kornia/metrics/confusion_matrix.py
+++ b/kornia/metrics/confusion_matrix.py
@@ -64,6 +64,10 @@ def confusion_matrix(
raise ValueError(f"The number of classes must be an integer bigger than two. Got: {num_classes}")
batch_size: int = pred.shape[0]
+ # An empty batch used to fail on view(0, -1) because a zero-numel tensor
+ # cannot infer the trailing dimension. Return an empty (0, K, K) matrix.
+ if batch_size == 0:
+ return torch.zeros(0, num_classes, num_classes, device=pred.device, dtype=torch.float32)
# hack for bitcounting 2 arrays together
# NOTE: torch.bincount does not implement batched version
diff --git a/tests/metrics/test_confusion.py b/tests/metrics/test_confusion.py
index ad2bbb33a..bd167ee6c 100644
--- a/tests/metrics/test_confusion.py
+++ b/tests/metrics/test_confusion.py
@@ -139,6 +139,16 @@ class TestConfusionMatrix(BaseTester):
)
self.assert_close(conf_mat, conf_mat_real)
+ def test_empty_batch(self, device, dtype):
+ num_classes = 3
+ pred = torch.zeros(0, 4, 4, device=device, dtype=torch.long)
+ target = torch.zeros(0, 4, 4, device=device, dtype=torch.long)
+
+ conf_mat = kornia.metrics.confusion_matrix(pred, target, num_classes)
+ assert conf_mat.shape == (0, num_classes, num_classes)
+ assert conf_mat.dtype == torch.float32
+ assert conf_mat.device == pred.device
+
def test_exception_shape_mismatch(self, device, dtype):
pred = torch.zeros(1, 4, dtype=torch.long, device=device)
target = torch.zeros(1, 5, dtype=torch.long, device=device)
diff --git a/tests/metrics/test_mean_iou.py b/tests/metrics/test_mean_iou.py
index d350098b4..53f890cbc 100644
--- a/tests/metrics/test_mean_iou.py
+++ b/tests/metrics/test_mean_iou.py
@@ -99,6 +99,16 @@ class TestMeanIoU(BaseTester):
with pytest.raises(ValueError, match="bigger than two"):
kornia.metrics.mean_iou(pred, pred, num_classes=1)
+ def test_empty_batch(self, device, dtype):
+ num_classes = 3
+ pred = torch.zeros(0, 4, 4, device=device, dtype=torch.long)
+ target = torch.zeros(0, 4, 4, device=device, dtype=torch.long)
+
+ mean_iou = kornia.metrics.mean_iou(pred, target, num_classes)
+ assert mean_iou.shape == (0, num_classes)
+ assert mean_iou.dtype == torch.float32
+ assert mean_iou.device == pred.device
+
class TestMeanIoUBBox(BaseTester):
"""Tests for mean_iou_bbox with different box formats."""