π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(metrics): validate the labels of confusion_matrix and mean_iou and form the cell index in int64 (#5565)
εΊζ’η0679cd53ae1d
diff --git a/changelog.d/5565.breaking.md b/changelog.d/5565.breaking.mdnew file mode 100644index 000000000..ef13be781--- /dev/null+++ b/changelog.d/5565.breaking.md@@ -0,0 +1,9 @@+`confusion_matrix` and `mean_iou` now require `pred` and `target` to be integer or `bool` tensors with values in+`[0, num_classes)`, and form the cell index in `int64` (#5549). Previously the labels were not checked: an+out-of-range prediction was counted silently in another cell (with 3 classes, a prediction of 3 for target 0 counted+as target 1 / prediction 0), and it now raises `BaseError` naming the offending range, as an out-of-range target+does instead of a raw torch error. A list now raises `TypeError` instead of `AttributeError`, and a float tensor+`BaseError` instead of a raw torch error. Small integer label maps now give the matrix of their `int64` copy. The+index used to wrap in the label dtype: `uint8` maps from 17 classes, so a perfect `uint8` prediction with 21 classes+reported an IoU of about 5e-7 for two classes that do not occur, and `int8` maps from 12 classes and `int16` maps+from 182, into another cell or a raw `bincount` error. The `num_classes` message now says "at least two".diff --git a/kornia/metrics/confusion_matrix.py b/kornia/metrics/confusion_matrix.pyindex a9f00f676..c5eca292b 100644--- a/kornia/metrics/confusion_matrix.py+++ b/kornia/metrics/confusion_matrix.py@@ -17,10 +17,30 @@import torch+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR+from kornia.core.utils import is_exporting+# Inspired by:# https://github.com/pytorch/tnt/blob/master/torchnet/meter/confusionmeter.py#L68-L73+def _check_labels(name: str, labels: torch.Tensor) -> None:+ KORNIA_CHECK_IS_TENSOR(labels, f"Input {name} must be a tensor of integer labels")+ # bool masks count as 0/1 labels, as they did before the check.+ KORNIA_CHECK(+ not (labels.dtype.is_floating_point or labels.dtype.is_complex),+ f"Input {name} must have an integer dtype. Got {labels.dtype}",+ )+++def _check_label_range(name: str, labels: torch.Tensor, num_classes: int) -> None:+ low, high = int(labels.min()), int(labels.max())+ KORNIA_CHECK(+ 0 <= low and high < num_classes,+ f"Input {name} must contain values in [0, {num_classes}). Got values in [{low}, {high}]",+ )++def confusion_matrix(pred: torch.Tensor, target: torch.Tensor, num_classes: int, normalized: bool = False) -> torch.Tensor:@@ -52,18 +72,15 @@ def confusion_matrix([0., 0., 0.]]])"""- if not torch.is_tensor(pred) and pred.dtype is not torch.int64:- raise TypeError(f"Input pred type is not a torch.Tensor with torch.int64 dtype. Got {type(pred)}")-- if not torch.is_tensor(target) and target.dtype is not torch.int64:- raise TypeError(f"Input target type is not a torch.Tensor with torch.int64 dtype. Got {type(target)}")+ _check_labels("pred", pred)+ _check_labels("target", target)if not pred.shape == target.shape:raise ValueError(f"Inputs pred and target must have the same shape. Got: {pred.shape} and {target.shape}")if not pred.device == target.device:raise ValueError(f"Inputs must be in the same device. Got: {pred.device} - {target.device}")if not isinstance(num_classes, int) or num_classes < 2:- raise ValueError(f"The number of classes must be an integer bigger than two. Got: {num_classes}")+ raise ValueError(f"The number of classes must be an integer of at least 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@@ -71,9 +88,15 @@ def confusion_matrix(if batch_size == 0:return torch.zeros(0, num_classes, num_classes, device=pred.device, dtype=torch.float32)+ # The range check reads the data, which graph capture cannot do; skip it under export.+ if not is_exporting() and pred.numel() > 0:+ _check_label_range("pred", pred, num_classes)+ _check_label_range("target", target, num_classes)+# hack for bitcounting 2 arrays together# NOTE: torch.bincount does not implement batched version- pre_bincount: torch.Tensor = pred + target * num_classes+ # The cell index is formed in int64: in the labels' own dtype it wraps, for uint8 from num_classes = 17.+ pre_bincount: torch.Tensor = pred.long() + target.long() * num_classespre_bincount_vec: torch.Tensor = pre_bincount.view(batch_size, -1)confusion_list = []diff --git a/kornia/metrics/mean_iou.py b/kornia/metrics/mean_iou.pyindex 79c44565a..d9c41b78c 100644--- a/kornia/metrics/mean_iou.py+++ b/kornia/metrics/mean_iou.py@@ -49,20 +49,7 @@ def mean_iou(pred: torch.Tensor, target: torch.Tensor, num_classes: int, eps: fltensor([[1., 1., 1.]])"""- if not torch.is_tensor(pred) and pred.dtype is not torch.int64:- raise TypeError(f"Input pred type is not a torch.Tensor with torch.int64 dtype. Got {type(pred)}")-- if not torch.is_tensor(target) and target.dtype is not torch.int64:- raise TypeError(f"Input target type is not a torch.Tensor with torch.int64 dtype. Got {type(target)}")- if not pred.shape == target.shape:- raise ValueError(f"Inputs pred and target must have the same shape. Got: {pred.shape} and {target.shape}")- if not pred.device == target.device:- raise ValueError(f"Inputs must be in the same device. Got: {pred.device} - {target.device}")-- if not isinstance(num_classes, int) or num_classes < 2:- raise ValueError(f"The number of classes must be an integer bigger than two. Got: {num_classes}")-- # we first compute the confusion matrix+ # we first compute the confusion matrix, which validates the labels and the class countconf_mat: torch.Tensor = confusion_matrix(pred, target, num_classes)# compute the actual intersection over uniondiff --git a/tests/metrics/test_confusion.py b/tests/metrics/test_confusion.pyindex 4b5397cc3..5835270ba 100644--- a/tests/metrics/test_confusion.py+++ b/tests/metrics/test_confusion.py@@ -19,6 +19,8 @@ import pytestimport torchimport kornia+from kornia.core._compat import torch_version_lt+from kornia.core.exceptions import BaseErrorfrom testing.base import BaseTester@@ -182,5 +184,63 @@ class TestConfusionMatrix(BaseTester):def test_exception_num_classes_too_small(self, device, dtype):pred = torch.zeros(1, 4, dtype=torch.long, device=device)- with pytest.raises(ValueError, match="bigger than two"):+ with pytest.raises(ValueError, match="at least two"):kornia.metrics.confusion_matrix(pred, pred, num_classes=1)++ def test_exception_not_integer_labels(self, device, dtype):+ # The two type checks were dead (#5549): a list reached `.dtype` and a float tensor reached `bincount`.+ labels = torch.tensor([[0, 1, 0]], device=device, dtype=torch.long)+ with pytest.raises(TypeError, match="pred must be a tensor"):+ kornia.metrics.confusion_matrix([[0, 1, 0]], labels, num_classes=3)+ with pytest.raises(BaseError, match="target must have an integer dtype"):+ kornia.metrics.confusion_matrix(labels, labels.to(dtype), num_classes=3)++ def test_exception_out_of_range(self, device, dtype):+ # An out-of-range prediction landed in another cell and an out-of-range target in a raw torch error (#5549).+ for pred, target, name, span in (+ ([0, 3, 2], [0, 1, 2], "pred", r"\[0, 3\]"),+ ([-1, 1, 2], [0, 1, 2], "pred", r"\[-1, 2\]"),+ ([0, 1, 2], [0, 3, 2], "target", r"\[0, 3\]"),+ ([0, 1, 2], [0, 255, 2], "target", r"\[0, 255\]"),+ ):+ message = rf"Input {name} must contain values in \[0, 3\)\. Got values in {span}"+ with pytest.raises(BaseError, match=message):+ kornia.metrics.confusion_matrix(+ torch.tensor([pred], device=device), torch.tensor([target], device=device), num_classes=3+ )++ @pytest.mark.parametrize("label_dtype, num_classes", [(torch.uint8, 21), (torch.int16, 182), (torch.int32, 21)])+ def test_small_integer_dtypes_match_int64(self, label_dtype, num_classes, device, dtype):+ # The cell index was formed in the label dtype and wrapped, for uint8 from num_classes = 17 (#5549).+ labels = torch.tensor([[[num_classes - 1, 0, 5], [5, num_classes - 1, 0]]], device=device, dtype=label_dtype)+ actual = kornia.metrics.confusion_matrix(labels, labels, num_classes)+ expected = kornia.metrics.confusion_matrix(labels.long(), labels.long(), num_classes)+ assert actual.dtype == torch.float32+ self.assert_close(actual, expected, rtol=0, atol=0)+ assert actual[0].nonzero().tolist() == [[0, 0], [5, 5], [num_classes - 1, num_classes - 1]]++ def test_bool_masks_count_as_binary_labels(self, device, dtype):+ pred = torch.tensor([[True, False, True, True]], device=device)+ target = torch.tensor([[True, False, False, True]], device=device)+ expected = torch.tensor([[[1, 1], [0, 2]]], device=device, dtype=torch.float32)+ self.assert_close(kornia.metrics.confusion_matrix(pred, target, num_classes=2), expected)++ def test_zero_pixel_samples_give_zero_matrices(self, device, dtype):+ # The range check reads the label minimum, which a sample without pixels does not have: it is skipped there.+ for shape in ((2, 0), (2, 3, 0)):+ labels = torch.zeros(shape, device=device, dtype=torch.long)+ expected = torch.zeros(2, 3, 3, device=device, dtype=torch.float32)+ self.assert_close(kornia.metrics.confusion_matrix(labels, labels, num_classes=3), expected, rtol=0, atol=0)++ @pytest.mark.skipif(torch_version_lt(2, 14, 0), reason="torch.export cannot capture the bincount before torch 2.14")+ def test_export_counts_like_eager(self, device, dtype):+ # The range check reads the data, which torch.export cannot capture, so it is skipped under export.+ class _ConfusionMatrix(torch.nn.Module):+ def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:+ return kornia.metrics.confusion_matrix(pred, target, num_classes=3)++ pred = torch.tensor([[0, 1, 2, 2], [1, 1, 0, 2]], device=device)+ target = torch.tensor([[0, 2, 2, 1], [1, 0, 0, 2]], device=device)+ exported = torch.export.export(_ConfusionMatrix(), (pred, target), strict=True).module()+ for p, t in ((pred, target), (target, pred.flip(-1))):+ self.assert_close(exported(p, t), kornia.metrics.confusion_matrix(p, t, num_classes=3), rtol=0, atol=0)diff --git a/tests/metrics/test_mean_iou.py b/tests/metrics/test_mean_iou.pyindex f2cbf0af3..ab30ca9b9 100644--- a/tests/metrics/test_mean_iou.py+++ b/tests/metrics/test_mean_iou.py@@ -19,6 +19,7 @@ import pytestimport torchimport kornia+from kornia.core.exceptions import BaseErrorfrom testing.base import BaseTester@@ -96,9 +97,24 @@ class TestMeanIoU(BaseTester):def test_exception_num_classes_too_small(self, device, dtype):pred = torch.zeros(1, 4, dtype=torch.long, device=device)- with pytest.raises(ValueError, match="bigger than two"):+ with pytest.raises(ValueError, match="at least two"):kornia.metrics.mean_iou(pred, pred, num_classes=1)+ def test_exception_out_of_range(self, device, dtype):+ # A prediction of num_classes was counted in another cell and gave an IoU for it (#5549).+ pred = torch.tensor([[0, 3]], device=device, dtype=torch.long)+ target = torch.tensor([[0, 0]], device=device, dtype=torch.long)+ with pytest.raises(BaseError, match=r"Input pred must contain values in \[0, 3\)"):+ kornia.metrics.mean_iou(pred, target, num_classes=3)++ def test_uint8_labels_match_int64(self, device, dtype):+ # The confusion matrix index wrapped in uint8 from num_classes = 17, so a perfect uint8 prediction reported+ # an IoU of about 5e-7 for two classes that do not occur (#5549).+ labels = torch.tensor([[[20, 0, 5], [5, 20, 0]]], device=device, dtype=torch.uint8)+ actual = kornia.metrics.mean_iou(labels, labels, num_classes=21)+ self.assert_close(actual, kornia.metrics.mean_iou(labels.long(), labels.long(), num_classes=21), rtol=0, atol=0)+ self.assert_close(actual, torch.ones(1, 21, device=device, dtype=torch.float32))+def test_empty_batch(self, device, dtype):num_classes = 3pred = torch.zeros(0, 4, 4, device=device, dtype=torch.long)