Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

create metrics module and implement confusion_matrix

edgarribabef5f55be68b
diff --git a/docs/source/index.rst b/docs/source/index.rst
index 85e460210..e90c0ce86 100644
--- a/docs/source/index.rst
+++ b/docs/source/index.rst
@@ -23,6 +23,7 @@ TGM focuses on Image and tensor warping functions such as:
core
image
losses
+ metrics
contrib
utils
diff --git a/docs/source/metrics.rst b/docs/source/metrics.rst
new file mode 100644
index 000000000..5299b0107
--- /dev/null
+++ b/docs/source/metrics.rst
@@ -0,0 +1,6 @@
+torchgeometry.metrics
+=====================
+
+.. currentmodule:: torchgeometry.metrics
+
+.. autofunction:: confusion_matrix
diff --git a/test/test_metrics.py b/test/test_metrics.py
new file mode 100644
index 000000000..dd2273d7b
--- /dev/null
+++ b/test/test_metrics.py
@@ -0,0 +1,125 @@
+import pytest
+
+import torch
+import torchgeometry as tgm
+from torch.autograd import gradcheck
+
+import utils
+from common import device_type
+
+
+class TestConfusionMatrix:
+ 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]])
+
+ conf_mat = tgm.metrics.confusion_matrix(actual, predicted, num_classes)
+ assert conf_mat[..., 0, 0].item() == 3
+ assert conf_mat[..., 0, 1].item() == 1
+ assert conf_mat[..., 1, 0].item() == 0
+ assert conf_mat[..., 1, 1].item() == 4
+
+ def test_three_classes(self):
+ num_classes = 3
+ actual = torch.tensor(
+ [[2, 2, 0, 0, 1, 0, 0, 2, 1, 1, 0, 0, 1, 2, 1, 0]])
+ 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
+
+ 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]]])
+
+ conf_mat = tgm.metrics.confusion_matrix(actual, predicted, num_classes)
+ conf_mat_real = torch.tensor(
+ [[[4, 0, 0, 0],
+ [0, 4, 0, 0],
+ [0, 0, 4, 0],
+ [0, 0, 0, 4]]])
+ assert torch.equal(conf_mat, conf_mat_real)
+
+ def test_four_classes_2d_one_class_nonperfect(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, 3, 0, 1],
+ [2, 2, 1, 3],
+ [2, 2, 3, 3]]])
+
+ conf_mat = tgm.metrics.confusion_matrix(actual, predicted, num_classes)
+ conf_mat_real = torch.tensor(
+ [[[3, 0, 0, 1],
+ [1, 3, 0, 0],
+ [0, 0, 4, 0],
+ [0, 1, 0, 3]]])
+ assert torch.equal(conf_mat, conf_mat_real)
+
+ def test_four_classes_2d_one_class_missing(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(
+ [[[3, 3, 1, 1],
+ [3, 3, 1, 1],
+ [2, 2, 3, 3],
+ [2, 2, 3, 3]]])
+
+ conf_mat = tgm.metrics.confusion_matrix(actual, predicted, num_classes)
+ conf_mat_real = torch.tensor(
+ [[[0, 0, 0, 4],
+ [0, 4, 0, 0],
+ [0, 0, 4, 0],
+ [0, 0, 0, 4]]])
+ assert torch.equal(conf_mat, conf_mat_real)
+
+ 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]]])
+
+ conf_mat = tgm.metrics.confusion_matrix(actual, predicted, num_classes)
+ conf_mat_real = torch.tensor(
+ [[[0, 0, 4, 4],
+ [0, 0, 0, 0],
+ [0, 0, 4, 0],
+ [0, 0, 0, 4]]])
+ assert torch.equal(conf_mat, conf_mat_real)
diff --git a/torchgeometry/__init__.py b/torchgeometry/__init__.py
index dd6f0c08a..2910b1750 100644
--- a/torchgeometry/__init__.py
+++ b/torchgeometry/__init__.py
@@ -5,6 +5,7 @@ from torchgeometry import image
from torchgeometry import losses
from torchgeometry import contrib
from torchgeometry import utils
+from torchgeometry import metrics
# Exposes ``torchgeometry.core`` package to top level
from .core.homography_warper import HomographyWarper, homography_warp
diff --git a/torchgeometry/metrics/__init__.py b/torchgeometry/metrics/__init__.py
new file mode 100644
index 000000000..bef833dc4
--- /dev/null
+++ b/torchgeometry/metrics/__init__.py
@@ -0,0 +1 @@
+from .confusion_matrix import confusion_matrix
diff --git a/torchgeometry/metrics/confusion_matrix.py b/torchgeometry/metrics/confusion_matrix.py
new file mode 100644
index 000000000..d89ccc952
--- /dev/null
+++ b/torchgeometry/metrics/confusion_matrix.py
@@ -0,0 +1,47 @@
+from typing import Optional
+
+import torch
+
+
+def confusion_matrix(
+ y_true: torch.Tensor,
+ y_pred: torch.Tensor,
+ num_classes: int) -> torch.Tensor:
+ r"""Compute confusion matrix to evaluate the accuracy of a classification.
+
+ 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.
+
+ Returns:
+ torch.Tensor: a tensor with the confusion matrix with shape
+ :math:`(N, C, C)` where C 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:
+ raise ValueError("Inputs must be in the same device. "
+ "Got: {} - {}".format(y_true.device, y_pred.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)
+
+ # NOTE: torch.bincount does not implement batched version
+ pre_bincount: torch.Tensor = y_true_vec * num_classes + y_pred_vec
+ confusion_vec: torch.Tensor = torch.stack([
+ torch.bincount(pb) for pb in pre_bincount
+ ])
+ return confusion_vec.view(batch_size, num_classes, num_classes) # BxNxN