π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[feat] Add Average Endpoint Error to Metrics (#2500)
Christoph Reich9c8765aa25c5
diff --git a/docs/source/metrics.rst b/docs/source/metrics.rstindex cf188f8cc..32ee117c4 100644--- a/docs/source/metrics.rst+++ b/docs/source/metrics.rst@@ -31,6 +31,12 @@ Image Quality.. autoclass:: SSIM.. autoclass:: SSIM3D+Optical Flow+-------------++.. autofunction:: aepe+.. autoclass:: AEPE+Monitoring----------diff --git a/kornia/metrics/__init__.py b/kornia/metrics/__init__.pyindex 6682889b5..41c5ebe4f 100644--- a/kornia/metrics/__init__.py+++ b/kornia/metrics/__init__.py@@ -1,6 +1,7 @@from .accuracy import accuracyfrom .average_meter import AverageMeterfrom .confusion_matrix import confusion_matrix+from .endpoint_error import AEPE, aepefrom .mean_average_precision import mean_average_precisionfrom .mean_iou import mean_iou, mean_iou_bboxfrom .psnr import psnr@@ -11,6 +12,8 @@ __all__ = ["accuracy","AverageMeter","confusion_matrix",+ "aepe",+ "AEPE","mean_iou","mean_iou_bbox","mean_average_precision",diff --git a/kornia/metrics/endpoint_error.py b/kornia/metrics/endpoint_error.pynew file mode 100644index 000000000..e393c70eb--- /dev/null+++ b/kornia/metrics/endpoint_error.py@@ -0,0 +1,91 @@+import torch+from torch import Tensor, nn++from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE+++def aepe(input: torch.Tensor, target: torch.Tensor, reduction: str = "mean") -> torch.Tensor:+ r"""Create a function that calculates the average endpoint error (AEPE) between 2 flow maps.++ AEPE is the endpoint error between two 2D vectors (e.g., optical flow).+ Given a h x w x 2 optical flow map, the AEPE is:++ .. math::++ \text{AEPE}=\frac{1}{hw}\sum_{i=1, j=1}^{h, w}\sqrt{(I_{i,j,1}-T_{i,j,1})^{2}+(I_{i,j,2}-T_{i,j,2})^{2}}++ Args:+ input: the input flow map with shape :math:`(*, 2)`.+ target: the target flow map with shape :math:`(*, 2)`.+ reduction : Specifies the reduction to apply to the+ output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,+ ``'mean'``: the sum of the output will be divided by the number of elements+ in the output, ``'sum'``: the output will be summed.++ Return:+ the computed AEPE as a scalar.++ Examples:+ >>> ones = torch.ones(4, 4, 2)+ >>> aepe(ones, 1.2 * ones)+ tensor(0.2828)++ Reference:+ https://link.springer.com/content/pdf/10.1007/s11263-010-0390-2.pdf+ """+ KORNIA_CHECK_IS_TENSOR(input)+ KORNIA_CHECK_IS_TENSOR(target)+ KORNIA_CHECK_SHAPE(input, ["*", "2"])+ KORNIA_CHECK_SHAPE(target, ["*", "2"])+ KORNIA_CHECK(+ input.shape == target.shape, f"input and target shapes must be the same. Got: {input.shape} and {target.shape}"+ )++ epe: Tensor = ((input[..., 0] - target[..., 0]) ** 2 + (input[..., 1] - target[..., 1]) ** 2).sqrt()++ if reduction == "mean":+ epe = epe.mean()+ elif reduction == "sum":+ epe = epe.sum()+ elif reduction == "none":+ pass+ else:+ raise NotImplementedError('Invalid reduction option.')++ return epe+++class AEPE(nn.Module):+ r"""Computes the average endpoint error (AEPE) between 2 flow maps.++ EPE is the endpoint error between two 2D vectors (e.g., optical flow).+ Given a h x w x 2 optical flow map, the AEPE is:++ .. math::++ \text{AEPE}=\frac{1}{hw}\sum_{i=1, j=1}^{h, w}\sqrt{(I_{i,j,1}-T_{i,j,1})^{2}+(I_{i,j,2}-T_{i,j,2})^{2}}++ Args:+ reduction : Specifies the reduction to apply to the+ output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,+ ``'mean'``: the sum of the output will be divided by the number of elements+ in the output, ``'sum'``: the output will be summed.++ Shape:+ - input: :math:`(*, 2)`.+ - target :math:`(*, 2)`.+ - output: :math:`(1)`.++ Examples:+ >>> input1 = torch.rand(1, 4, 5, 2)+ >>> input2 = torch.rand(1, 4, 5, 2)+ >>> epe = AEPE(reduction="mean")+ >>> epe = epe(input1, input2)+ """++ def __init__(self, reduction: str = 'mean') -> None:+ super().__init__()+ self.reduction: str = reduction++ def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:+ return aepe(input, target, self.reduction)diff --git a/test/test_metrics.py b/test/test_metrics.pyindex 7a9742e69..89a050004 100644--- a/test/test_metrics.py+++ b/test/test_metrics.py@@ -196,6 +196,55 @@ class TestPsnr:assert_close(actual, expected)+class TestAepe:+ def test_metric_mean_reduction(self, device, dtype):+ sample = torch.ones(4, 4, 2, device=device, dtype=dtype)+ expected = torch.tensor(0.565685424, device=device, dtype=dtype)+ actual = kornia.metrics.aepe(sample, 1.4 * sample, reduction="mean")+ assert_close(actual, expected)++ def test_metric_sum_reduction(self, device, dtype):+ sample = torch.ones(4, 4, 2, device=device, dtype=dtype)+ expected = torch.tensor(1.4142, device=device, dtype=dtype) * 4**2+ actual = kornia.metrics.aepe(sample, 2.0 * sample, reduction="sum")+ assert_close(actual, expected)++ def test_metric_no_reduction(self, device, dtype):+ sample = torch.ones(4, 4, 2, device=device, dtype=dtype)+ expected = torch.zeros(4, 4, device=device, dtype=dtype) + 1.4142+ actual = kornia.metrics.aepe(sample, 2.0 * sample, reduction="none")+ assert_close(actual, expected)++ def test_perfect_fit(self, device, dtype):+ sample = torch.ones(4, 4, 2, device=device, dtype=dtype)+ expected = torch.zeros(4, 4, device=device, dtype=dtype)+ actual = kornia.metrics.aepe(sample, sample, reduction="none")+ assert_close(actual, expected)++ def test_exception(self, device, dtype):+ with pytest.raises(TypeError) as errinfo:+ criterion = kornia.metrics.AEPE()+ criterion(None, torch.ones(4, 4, 2, device=device, dtype=dtype))+ assert "Not a Tensor type. Got" in str(errinfo)++ with pytest.raises(NotImplementedError) as errinfo:+ sample = torch.ones(4, 4, 2, device=device, dtype=dtype)+ _ = kornia.metrics.aepe(sample, 2.0 * sample, reduction="foo")+ assert "Invalid reduction option." in str(errinfo)++ with pytest.raises(Exception) as errinfo:+ sample = torch.ones(4, 4, 2, device=device, dtype=dtype)+ _ = kornia.metrics.aepe(sample, 2.0 * sample[..., 0], reduction="mean")+ assert "shape must be [['*', '2']]. Got" in str(errinfo)++ def test_smoke(self, device, dtype):+ input = torch.rand(3, 3, 2, device=device, dtype=dtype)+ target = torch.rand(3, 3, 2, device=device, dtype=dtype)++ criterion = kornia.metrics.AEPE()+ assert criterion(input, target) is not None++class TestMeanAveragePrecision:def test_smoke(self, device, dtype):boxes = torch.tensor([[100, 50, 150, 100.0]], device=device, dtype=dtype)