Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

improve documentation and renaming variable for confusion_matrix and mean_iou

edgarribac036f84c9004
diff --git a/test/test_metrics.py b/test/test_metrics.py
index 92466602b..2fda3d5d0 100644
--- a/test/test_metrics.py
+++ b/test/test_metrics.py
@@ -16,7 +16,7 @@ class TestMeanIoU:
predicted = torch.tensor(
[[1, 1, 1, 1, 0, 0, 0, 0]])
- mean_iou = tgm.metrics.mean_iou(actual, predicted, num_classes)
+ mean_iou = tgm.metrics.mean_iou(predicted, actual, 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)
@@ -28,7 +28,7 @@ class TestMeanIoU:
predicted = torch.tensor(
[[1, 1, 1, 1, 0, 0, 0, 1]])
- mean_iou = tgm.metrics.mean_iou(actual, predicted, num_classes)
+ mean_iou = tgm.metrics.mean_iou(predicted, actual, 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)
@@ -46,7 +46,7 @@ class TestMeanIoU:
[2, 2, 3, 3],
[2, 2, 3, 3]]])
- mean_iou = tgm.metrics.mean_iou(actual, predicted, num_classes)
+ mean_iou = tgm.metrics.mean_iou(predicted, actual, 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)
@@ -66,7 +66,7 @@ class TestMeanIoU:
[2, 2, 3, 3],
[2, 2, 3, 3]]])
- mean_iou = tgm.metrics.mean_iou(actual, predicted, num_classes)
+ mean_iou = tgm.metrics.mean_iou(predicted, actual, 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)
@@ -82,7 +82,7 @@ class TestConfusionMatrix:
predicted = torch.tensor(
[[1, 1, 1, 1, 0, 0, 0, 1]])
- conf_mat = tgm.metrics.confusion_matrix(actual, predicted, num_classes)
+ conf_mat = tgm.metrics.confusion_matrix(predicted, actual, num_classes)
assert conf_mat[..., 0, 0].item() == 3
assert conf_mat[..., 0, 1].item() == 1
assert conf_mat[..., 1, 0].item() == 0
@@ -95,16 +95,12 @@ class TestConfusionMatrix:
predicted = torch.tensor(
[[2, 1, 0, 0, 0, 0, 0, 1, 0, 2, 2, 1, 0, 0, 2, 2]])
- conf_mat = tgm.metrics.confusion_matrix(actual, predicted, num_classes)
- assert conf_mat[..., 0, 0].item() == 4
- assert conf_mat[..., 0, 1].item() == 1
- assert conf_mat[..., 0, 2].item() == 2
- assert conf_mat[..., 1, 0].item() == 3
- assert conf_mat[..., 1, 1].item() == 0
- assert conf_mat[..., 1, 2].item() == 2
- assert conf_mat[..., 2, 0].item() == 1
- assert conf_mat[..., 2, 1].item() == 2
- assert conf_mat[..., 2, 2].item() == 1
+ conf_mat = tgm.metrics.confusion_matrix(predicted, actual, num_classes)
+ conf_mat_real = torch.tensor(
+ [[[4, 1, 2],
+ [3, 0, 2],
+ [1, 2, 1]]])
+ assert torch.equal(conf_mat, conf_mat_real)
def test_four_classes_2d_perfect(self):
num_classes = 4
@@ -119,7 +115,7 @@ class TestConfusionMatrix:
[2, 2, 3, 3],
[2, 2, 3, 3]]])
- conf_mat = tgm.metrics.confusion_matrix(actual, predicted, num_classes)
+ conf_mat = tgm.metrics.confusion_matrix(predicted, actual, num_classes)
conf_mat_real = torch.tensor(
[[[4, 0, 0, 0],
[0, 4, 0, 0],
@@ -140,7 +136,7 @@ class TestConfusionMatrix:
[2, 2, 1, 3],
[2, 2, 3, 3]]])
- conf_mat = tgm.metrics.confusion_matrix(actual, predicted, num_classes)
+ conf_mat = tgm.metrics.confusion_matrix(predicted, actual, num_classes)
conf_mat_real = torch.tensor(
[[[3, 0, 0, 1],
[1, 3, 0, 0],
@@ -161,7 +157,7 @@ class TestConfusionMatrix:
[2, 2, 3, 3],
[2, 2, 3, 3]]])
- conf_mat = tgm.metrics.confusion_matrix(actual, predicted, num_classes)
+ conf_mat = tgm.metrics.confusion_matrix(predicted, actual, num_classes)
conf_mat_real = torch.tensor(
[[[0, 0, 0, 4],
[0, 4, 0, 0],
@@ -182,7 +178,7 @@ class TestConfusionMatrix:
[2, 2, 3, 3],
[2, 2, 3, 3]]])
- conf_mat = tgm.metrics.confusion_matrix(actual, predicted, num_classes)
+ conf_mat = tgm.metrics.confusion_matrix(predicted, actual, num_classes)
conf_mat_real = torch.tensor(
[[[0, 0, 4, 4],
[0, 0, 0, 0],
diff --git a/torchgeometry/metrics/confusion_matrix.py b/torchgeometry/metrics/confusion_matrix.py
index d89ccc952..195ecd61e 100644
--- a/torchgeometry/metrics/confusion_matrix.py
+++ b/torchgeometry/metrics/confusion_matrix.py
@@ -2,46 +2,53 @@ from typing import Optional
import torch
+# Inspired by:
+# https://github.com/pytorch/tnt/blob/master/torchnet/meter/confusionmeter.py#L68-L73 # noqa
def confusion_matrix(
- y_true: torch.Tensor,
- y_pred: torch.Tensor,
+ input: torch.Tensor,
+ target: torch.Tensor,
num_classes: int) -> torch.Tensor:
r"""Compute confusion matrix to evaluate the accuracy of a classification.
+ Computes the confusion matrix of K x K size where K is no of classes.
+
Args:
- y_true (torch.Tensor) : tensor with ground truth (correct) target
- values. The shape can be :math:`(N, *)`.
- y_pred (torch.Tensor) : tensor with estimated targets returned by a
- classifier. The shape can be :math:`(N, *)`.
- num_classes (int): total number of classes in y_true.
+ input (torch.Tensor) : tensor with estimated targets returned by a
+ classifier. The shape can be :math:`(B, *)` and must contain integer
+ values between 0 and K-1.
+ target (torch.Tensor) : tensor with ground truth (correct) target
+ values. The shape can be :math:`(B, *)` and must contain integer
+ 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.
Returns:
torch.Tensor: a tensor with the confusion matrix with shape
- :math:`(N, C, C)` where C is the number of classes.
+ :math:`(B, K, K)` where K is the number of classes.
"""
- if not torch.is_tensor(y_true):
- raise TypeError("Input y_true type is not a torch.Tensor. Got {}"
- .format(type(y_true)))
- if not torch.is_tensor(y_pred):
- raise TypeError("Input y_pred type is not a torch.Tensor. Got {}"
- .format(type(y_pred)))
- if not y_true.shape == y_pred.shape:
- raise ValueError("Inputs y_true and y_pred must have the same shape. "
- "Got: {}".format(y_true.shape, y_pred.shape))
- if not y_true.device == y_pred.device:
+ if not isinstance(input, torch.LongTensor):
+ raise TypeError("Input input type is not a torch.LongTensor. Got {}"
+ .format(type(input)))
+ if not isinstance(target, torch.LongTensor):
+ raise TypeError("Input target type is not a torch.LongTensor. Got {}"
+ .format(type(target)))
+ if not input.shape == target.shape:
+ raise ValueError("Inputs input and target must have the same shape. "
+ "Got: {}".format(input.shape, target.shape))
+ if not input.device == target.device:
raise ValueError("Inputs must be in the same device. "
- "Got: {} - {}".format(y_true.device, y_pred.device))
+ "Got: {} - {}".format(input.device, target.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))
- batch_size: int = y_true.shape[0]
- y_true_vec: torch.Tensor = y_true.view(batch_size, -1)
- y_pred_vec: torch.Tensor = y_pred.view(batch_size, -1)
+ batch_size: int = input.shape[0]
+ # hack for bitcounting 2 arrays together
# NOTE: torch.bincount does not implement batched version
- pre_bincount: torch.Tensor = y_true_vec * num_classes + y_pred_vec
+ pre_bincount: torch.Tensor = input + target * num_classes
+ pre_bincount_vec: torch.Tensor = pre_bincount.view(batch_size, -1)
confusion_vec: torch.Tensor = torch.stack([
- torch.bincount(pb) for pb in pre_bincount
+ torch.bincount(pb, minlength=num_classes**2) for pb in pre_bincount_vec
])
- return confusion_vec.view(batch_size, num_classes, num_classes) # BxNxN
+ return confusion_vec.view(batch_size, num_classes, num_classes) # BxKxK
diff --git a/torchgeometry/metrics/mean_iou.py b/torchgeometry/metrics/mean_iou.py
index 50e2875fe..4b5c8d268 100644
--- a/torchgeometry/metrics/mean_iou.py
+++ b/torchgeometry/metrics/mean_iou.py
@@ -4,40 +4,47 @@ from torchgeometry.metrics import confusion_matrix
def mean_iou(
- labels: torch.Tensor,
- predictions: torch.Tensor,
+ input: torch.Tensor,
+ target: torch.Tensor,
num_classes: int) -> torch.Tensor:
r"""Calculate mean Intersection-Over-Union (mIOU).
+ The function internally computes the confusion matrix.
+
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.
+ input (torch.Tensor) : tensor with estimated targets returned by a
+ classifier. The shape can be :math:`(B, *)` and must contain integer
+ values between 0 and K-1.
+ target (torch.Tensor) : tensor with ground truth (correct) target
+ values. The shape can be :math:`(B, *)` and must contain integer
+ 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.
+ labels: torch.Tensor,
+ predictions: torch.Tensor,
+ num_classes: int) -> torch.Tensor:
Returns:
- torch.Tensor: a tensor representing the mean intersection-over union.
+ torch.Tensor: a tensor representing the mean intersection-over union
+ with shape :math:`(B, C)` where C is the number of classes.
"""
- 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:
+ if not isinstance(input, torch.LongTensor):
+ raise TypeError("Input input type is not a torch.LongTensor. Got {}"
+ .format(type(input)))
+ if not isinstance(target, torch.LongTensor):
+ raise TypeError("Input target type is not a torch.LongTensor. Got {}"
+ .format(type(target)))
+ if not input.shape == target.shape:
+ raise ValueError("Inputs input and target must have the same shape. "
+ "Got: {}".format(input.shape, target.shape))
+ if not input.device == target.device:
raise ValueError("Inputs must be in the same device. "
- "Got: {} - {}".format(labels.device,
- predictions.device))
+ "Got: {} - {}".format(input.device, target.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)
+ conf_mat: torch.Tensor = confusion_matrix(input, target, num_classes)
# allocate output tensor
batch_size: int = conf_mat.shape[0]