Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

implement mIoU metric

edgarriba446cd210e526
diff --git a/docs/source/metrics.rst b/docs/source/metrics.rst
index 5299b0107..d6ce9f0a0 100644
--- a/docs/source/metrics.rst
+++ b/docs/source/metrics.rst
@@ -4,3 +4,4 @@ torchgeometry.metrics
.. currentmodule:: torchgeometry.metrics
.. autofunction:: confusion_matrix
+.. autofunction:: mean_iou
diff --git a/test/test_metrics.py b/test/test_metrics.py
index dd2273d7b..92466602b 100644
--- a/test/test_metrics.py
+++ b/test/test_metrics.py
@@ -8,6 +8,72 @@ import utils
from common import device_type
+class TestMeanIoU:
+ def test_two_classes_perfect(self):
+ num_classes = 2
+ actual = torch.tensor(
+ [[1, 1, 1, 1, 0, 0, 0, 0]])
+ predicted = torch.tensor(
+ [[1, 1, 1, 1, 0, 0, 0, 0]])
+
+ mean_iou = tgm.metrics.mean_iou(actual, predicted, num_classes)
+ assert mean_iou.shape == (1, num_classes)
+ assert pytest.approx(mean_iou[..., 0].item(), 1.00)
+ assert pytest.approx(mean_iou[..., 1].item(), 1.00)
+
+ def test_two_classes(self):
+ num_classes = 2
+ actual = torch.tensor(
+ [[1, 1, 1, 1, 0, 0, 0, 0]])
+ predicted = torch.tensor(
+ [[1, 1, 1, 1, 0, 0, 0, 1]])
+
+ mean_iou = tgm.metrics.mean_iou(actual, predicted, num_classes)
+ assert mean_iou.shape == (1, num_classes)
+ assert pytest.approx(mean_iou[..., 0].item(), 0.75)
+ assert pytest.approx(mean_iou[..., 1].item(), 0.80)
+
+ def test_four_classes_2d_perfect(self):
+ num_classes = 4
+ actual = torch.tensor(
+ [[[0, 0, 1, 1],
+ [0, 0, 1, 1],
+ [2, 2, 3, 3],
+ [2, 2, 3, 3]]])
+ predicted = torch.tensor(
+ [[[0, 0, 1, 1],
+ [0, 0, 1, 1],
+ [2, 2, 3, 3],
+ [2, 2, 3, 3]]])
+
+ mean_iou = tgm.metrics.mean_iou(actual, predicted, num_classes)
+ assert mean_iou.shape == (1, num_classes)
+ assert pytest.approx(mean_iou[..., 0].item(), 1.00)
+ assert pytest.approx(mean_iou[..., 1].item(), 1.00)
+ assert pytest.approx(mean_iou[..., 2].item(), 1.00)
+ assert pytest.approx(mean_iou[..., 3].item(), 1.00)
+
+ def test_four_classes_2d_one_class_no_predicted(self):
+ num_classes = 4
+ actual = torch.tensor(
+ [[[0, 0, 0, 0],
+ [0, 0, 0, 0],
+ [2, 2, 3, 3],
+ [2, 2, 3, 3]]])
+ predicted = torch.tensor(
+ [[[3, 3, 2, 2],
+ [3, 3, 2, 2],
+ [2, 2, 3, 3],
+ [2, 2, 3, 3]]])
+
+ mean_iou = tgm.metrics.mean_iou(actual, predicted, num_classes)
+ assert mean_iou.shape == (1, num_classes)
+ assert pytest.approx(mean_iou[..., 0].item(), 0.00)
+ assert pytest.approx(mean_iou[..., 1].item(), 0.00)
+ assert pytest.approx(mean_iou[..., 2].item(), 0.50)
+ assert pytest.approx(mean_iou[..., 3].item(), 0.50)
+
+
class TestConfusionMatrix:
def test_two_classes(self):
num_classes = 2
diff --git a/torchgeometry/metrics/__init__.py b/torchgeometry/metrics/__init__.py
index bef833dc4..c4bbe4727 100644
--- a/torchgeometry/metrics/__init__.py
+++ b/torchgeometry/metrics/__init__.py
@@ -1 +1,2 @@
from .confusion_matrix import confusion_matrix
+from .mean_iou import mean_iou
diff --git a/torchgeometry/metrics/mean_iou.py b/torchgeometry/metrics/mean_iou.py
new file mode 100644
index 000000000..50e2875fe
--- /dev/null
+++ b/torchgeometry/metrics/mean_iou.py
@@ -0,0 +1,55 @@
+import torch
+
+from torchgeometry.metrics import confusion_matrix
+
+
+def mean_iou(
+ labels: torch.Tensor,
+ predictions: torch.Tensor,
+ num_classes: int) -> torch.Tensor:
+ r"""Calculate mean Intersection-Over-Union (mIOU).
+
+ Args:
+ labels (torch.Tensor) : tensor with ground truth (correct) target
+ values. The shape can be :math:`(N, *)`.
+ predictions (torch.Tensor) : tensor with estimated targets returned by
+ a classifier. The shape can be :math:`(N, *)`.
+ num_classes (int): total possible number of classes in labels.
+
+ Returns:
+ torch.Tensor: a tensor representing the mean intersection-over union.
+ """
+ if not torch.is_tensor(labels):
+ raise TypeError("Input labels type is not a torch.Tensor. Got {}"
+ .format(type(labels)))
+ if not torch.is_tensor(predictions):
+ raise TypeError("Input predictions type is not a torch.Tensor. Got {}"
+ .format(type(predictions)))
+ if not labels.shape == predictions.shape:
+ raise ValueError("Inputs labels and predictions must have the same "
+ "shape. Got: {}".format(labels.shape,
+ predictions.shape))
+ if not labels.device == predictions.device:
+ raise ValueError("Inputs must be in the same device. "
+ "Got: {} - {}".format(labels.device,
+ predictions.device))
+ if not isinstance(num_classes, int) or num_classes < 2:
+ raise ValueError("The number of classes must be an intenger bigger "
+ "than two. Got: {}".format(num_classes))
+ # we first compute the confusion matrix
+ conf_mat: torch.Tensor = confusion_matrix(labels, predictions, num_classes)
+
+ # allocate output tensor
+ batch_size: int = conf_mat.shape[0]
+ ious: torch.Tensor = torch.zeros(
+ batch_size, num_classes, device=conf_mat.device)
+
+ # TODO: is it possible to vectorize this ?
+ # iterate over classes
+ for class_id in range(num_classes):
+ tp: torch.Tensor = conf_mat[..., class_id, class_id].float()
+ total = torch.sum(conf_mat[..., class_id, :], dim=-1, keepdim=True) + \
+ torch.sum(conf_mat[..., :, class_id], dim=-1, keepdim=True)
+ iou_val: torch.Tensor = tp / (total.float() - tp + 1e-6)
+ ious[..., class_id:class_id + 1] += iou_val
+ return ious