Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

vectorize mean_iou

edgarriba908ae00551bc
diff --git a/test/test_metrics.py b/test/test_metrics.py
index 9eb7587c2..bea753b60 100644
--- a/test/test_metrics.py
+++ b/test/test_metrics.py
@@ -2,7 +2,6 @@ import pytest
import torch
import torchgeometry as tgm
-from torch.autograd import gradcheck
import utils
from common import device_type
@@ -72,7 +71,7 @@ class TestMeanIoU:
assert mean_iou.shape == (batch_size, num_classes)
assert utils.check_equal_torch(mean_iou, mean_iou_real)
- def test_four_classes_2d_one_class_no_predicted(self):
+ def test_four_classes_one_missing(self):
batch_size = 1
num_classes = 4
actual = torch.tensor(
@@ -88,7 +87,7 @@ class TestMeanIoU:
mean_iou = tgm.metrics.mean_iou(predicted, actual, num_classes)
mean_iou_real = torch.tensor(
- [[0.0, 0.0, 0.5, 0.5]], dtype=torch.float32)
+ [[0.0, 1.0, 0.5, 0.5]], dtype=torch.float32)
assert mean_iou.shape == (batch_size, num_classes)
assert utils.check_equal_torch(mean_iou, mean_iou_real)
@@ -135,6 +134,21 @@ class TestConfusionMatrix:
[1, 2, 1]]], dtype=torch.float32)
assert utils.check_equal_torch(conf_mat, conf_mat_real)
+ def test_four_classes_one_missing(self):
+ num_classes = 4
+ actual = torch.tensor(
+ [[3, 3, 1, 1, 2, 1, 1, 3, 2, 2, 1, 1, 2, 3, 2, 1]])
+ predicted = torch.tensor(
+ [[3, 2, 1, 1, 1, 1, 1, 2, 1, 3, 3, 2, 1, 1, 3, 3]])
+
+ conf_mat = tgm.metrics.confusion_matrix(predicted, actual, num_classes)
+ conf_mat_real = torch.tensor(
+ [[[0, 0, 0, 0],
+ [0, 4, 1, 2],
+ [0, 3, 0, 2],
+ [0, 1, 2, 1]]], dtype=torch.float32)
+ assert utils.check_equal_torch(conf_mat, conf_mat_real)
+
def test_three_classes_normalized(self):
num_classes = 3
normalized = True
diff --git a/torchgeometry/metrics/confusion_matrix.py b/torchgeometry/metrics/confusion_matrix.py
index f77e73bd3..27f881701 100644
--- a/torchgeometry/metrics/confusion_matrix.py
+++ b/torchgeometry/metrics/confusion_matrix.py
@@ -10,7 +10,7 @@ def confusion_matrix(
input: torch.Tensor,
target: torch.Tensor,
num_classes: int,
- normalized: Optional[float] = False) -> torch.Tensor:
+ normalized: Optional[bool] = False) -> torch.Tensor:
r"""Compute confusion matrix to evaluate the accuracy of a classification.
Args:
@@ -22,7 +22,7 @@ def confusion_matrix(
values between 0 and K-1, whete targets are assumed to be provided as
one-hot vectors.
num_classes (int): total possible number of classes in target.
- normalized: (Optional[float]): wether to return the confusion matrix
+ normalized: (Optional[bool]): wether to return the confusion matrix
normalized. Default: False.
Returns:
diff --git a/torchgeometry/metrics/mean_iou.py b/torchgeometry/metrics/mean_iou.py
index 5be42166a..cdde691a7 100644
--- a/torchgeometry/metrics/mean_iou.py
+++ b/torchgeometry/metrics/mean_iou.py
@@ -1,12 +1,14 @@
-import torch
+from typing import Optional
+import torch
from torchgeometry.metrics import confusion_matrix
def mean_iou(
input: torch.Tensor,
target: torch.Tensor,
- num_classes: int) -> torch.Tensor:
+ num_classes: int,
+ eps: Optional[float] = 1e-6) -> torch.Tensor:
r"""Calculate mean Intersection-Over-Union (mIOU).
The function internally computes the confusion matrix.
@@ -43,18 +45,13 @@ def mean_iou(
# we first compute the confusion matrix
conf_mat: torch.Tensor = confusion_matrix(input, target, 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[..., None, class_id, class_id]
- total: torch.Tensor = \
- 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
+ # compute the actual intersection over union
+ sum_over_row = torch.sum(conf_mat, dim=1)
+ sum_over_col = torch.sum(conf_mat, dim=2)
+ conf_mat_diag = torch.diagonal(conf_mat, dim1=-2, dim2=-1)
+ denominator = sum_over_row + sum_over_col - conf_mat_diag
+
+ # NOTE: we add epsilon so that samples that are neither in the
+ # prediction or ground truth are taken into account.
+ ious = (conf_mat_diag + eps) / (denominator + eps)
return ious