π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Allowing more than 3/4 dims for `total_variation` + adding `reduction` (#1815)
nitaifingerhut463e84953efd
diff --git a/kornia/losses/total_variation.py b/kornia/losses/total_variation.pyindex e6ccb1d5d..2d80b870d 100644--- a/kornia/losses/total_variation.py+++ b/kornia/losses/total_variation.py@@ -1,60 +1,76 @@-import torch-import torch.nn as nn+from kornia.core import Module, Tensor+from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_SHAPE-def total_variation(img: torch.Tensor) -> torch.Tensor:+def total_variation(img: Tensor, reduction: str = "sum") -> Tensor:r"""Function that computes Total Variation according to [1].Args:- img: the input image with shape :math:`(N, C, H, W)` or :math:`(C, H, W)`.+ img: the input image with shape :math:`(*, H, W)`.+ reduction : Specifies the reduction to apply to the output: ``'mean'`` | ``'sum'``.+ ``'mean'``: the sum of the output will be divided by the number of elements+ in the output, ``'sum'``: the output will be summed.Return:- a scalar with the computer loss.+ a tensor with shape :math:`(*,)`.Examples:- >>> total_variation(torch.ones(3, 4, 4))+ >>> total_variation(torch.ones(4, 4))tensor(0.)+ >>> total_variation(torch.ones(2, 5, 3, 4, 4)).shape+ torch.Size([2, 5, 3]).. note::See a working example `here <https://kornia-tutorials.readthedocs.io/en/latest/total_variation_denoising.html>`__.+ Total Variation is formulated with summation, however this is not resolution invariant.+ Thus, `reduction='mean'` was added as an optional reduction method.Reference:[1] https://en.wikipedia.org/wiki/Total_variation"""- if not isinstance(img, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(img)}")-- if len(img.shape) < 3 or len(img.shape) > 4:- raise ValueError(f"Expected input tensor to be of ndim 3 or 4, but got {len(img.shape)}.")+ KORNIA_CHECK_SHAPE(img, ["*", "H", "W"])+ KORNIA_CHECK(reduction in ("mean", "sum"), f"Expected reduction to be one of 'mean'/'sum', but got '{reduction}'.")pixel_dif1 = img[..., 1:, :] - img[..., :-1, :]pixel_dif2 = img[..., :, 1:] - img[..., :, :-1]- reduce_axes = (-3, -2, -1)- res1 = pixel_dif1.abs().sum(dim=reduce_axes)- res2 = pixel_dif2.abs().sum(dim=reduce_axes)+ res1 = pixel_dif1.abs()+ res2 = pixel_dif2.abs()++ reduce_axes = (-2, -1)+ if reduction == "mean":+ if img.is_floating_point():+ res1 = res1.to(img).mean(dim=reduce_axes)+ res2 = res2.to(img).mean(dim=reduce_axes)+ else:+ res1 = res1.float().mean(dim=reduce_axes)+ res2 = res2.float().mean(dim=reduce_axes)+ elif reduction == "sum":+ res1 = res1.sum(dim=reduce_axes)+ res2 = res2.sum(dim=reduce_axes)return res1 + res2-class TotalVariation(nn.Module):+class TotalVariation(Module):r"""Compute the Total Variation according to [1].Shape:- - Input: :math:`(N, C, H, W)` or :math:`(C, H, W)`.- - Output: :math:`(N,)` or scalar.+ - Input: :math:`(*, H, W)`.+ - Output: :math:`(*,)`.Examples:>>> tv = TotalVariation()>>> output = tv(torch.ones((2, 3, 4, 4), requires_grad=True))>>> output.data- tensor([0., 0.])+ tensor([[0., 0., 0.],+ [0., 0., 0.]])>>> output.sum().backward() # grad can be implicitly created only for scalar outputsReference:[1] https://en.wikipedia.org/wiki/Total_variation"""- def forward(self, img) -> torch.Tensor:+ def forward(self, img) -> Tensor:return total_variation(img)diff --git a/kornia/x/trainer.py b/kornia/x/trainer.pyindex 1ecf9ba2f..d76fe3183 100644--- a/kornia/x/trainer.py+++ b/kornia/x/trainer.py@@ -72,7 +72,7 @@ class Trainer:) -> None:# setup the acceleratorif Accelerator is None:- raise ModuleNotFoundError("accelerate library is not installed: pip install kornia[x]")+ raise ModuleNotFoundError('accelerate library is not installed: pip install "kornia[x]"')self.accelerator = Accelerator()# setup the data related objectsdiff --git a/test/losses/test_losses.py b/test/losses/test_losses.pyindex e9b08ab27..809f3d1f2 100644--- a/test/losses/test_losses.py+++ b/test/losses/test_losses.py@@ -425,7 +425,11 @@ class TestDivergenceLoss:class TestTotalVariation:# Total variation of constant vectors is 0@pytest.mark.parametrize(- 'input, expected', [(torch.ones(3, 4, 5), torch.zeros(())), (2 * torch.ones(2, 3, 4, 5), torch.zeros(2))]+ 'input, expected',+ [+ (torch.ones(3, 4, 5), torch.tensor([0.0, 0.0, 0.0])),+ (2 * torch.ones(2, 3, 4, 5), torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])),+ ],)def test_tv_on_constant(self, device, dtype, input, expected):actual = kornia.losses.total_variation(input.to(device, dtype))@@ -458,17 +462,17 @@ class TestTotalVariation:],]),- torch.tensor(33.001236),+ torch.tensor([12.6647, 7.9527, 12.3838]),),(torch.tensor([[[0.09094203, 0.32630223, 0.8066123], [0.10921168, 0.09534764, 0.48588026]]]),- torch.tensor(1.6900232),+ torch.tensor([1.6900]),),],)def test_tv_on_3d(self, device, dtype, input, expected):actual = kornia.losses.total_variation(input.to(device, dtype))- assert_close(actual, expected.to(device, dtype))+ assert_close(actual, expected.to(device, dtype), rtol=1e-3, atol=1e-3)# Total variation for 4D tensors@pytest.mark.parametrize(@@ -489,7 +493,7 @@ class TestTotalVariation:],]),- torch.tensor([5.0054283, 3.1870906]),+ torch.tensor([[1.5672, 1.2836, 2.1544], [1.4134, 0.8584, 0.9154]]),),(torch.tensor(@@ -499,19 +503,31 @@ class TestTotalVariation:[[[0.5078, 0.5703, 0.9110], [0.4765, 0.8401, 0.2754]]],]),- torch.tensor([1.9565653, 2.5786452, 2.2681699]),+ torch.tensor([[1.9566], [2.5787], [2.2682]]),),],)def test_tv_on_4d(self, device, dtype, input, expected):actual = kornia.losses.total_variation(input.to(device, dtype))- assert_close(actual, expected.to(device, dtype), rtol=1e-4, atol=1e-4)-- # Expect ValueError to be raised when tensors of ndim != 3 or 4 are passed- @pytest.mark.parametrize('input', [torch.rand(2, 3, 4, 5, 3), torch.rand(3, 1)])- def test_tv_on_invalid_dims(self, device, dtype, input):- with pytest.raises(ValueError):- kornia.losses.total_variation(input.to(device, dtype))+ assert_close(actual, expected.to(device, dtype), rtol=1e-3, atol=1e-3)++ @pytest.mark.parametrize('input', [torch.rand(3, 5, 5), torch.rand(4, 3, 5, 5), torch.rand(4, 2, 3, 5, 5)])+ def test_tv_shapes(self, device, dtype, input):+ input = input.to(device, dtype)+ actual_lesser_dims = []+ for slice in torch.unbind(input, dim=0):+ slice_tv = kornia.losses.total_variation(slice)+ actual_lesser_dims.append(slice_tv)+ actual_lesser_dims = torch.stack(actual_lesser_dims, dim=0)+ actual_higher_dims = kornia.losses.total_variation(input)+ assert_close(actual_lesser_dims, actual_higher_dims.to(device, dtype), rtol=1e-3, atol=1e-3)++ @pytest.mark.parametrize('reduction, expected', [('sum', torch.tensor(20)), ('mean', torch.tensor(1))])+ def test_tv_reduction(self, device, dtype, reduction, expected):+ input, _ = torch.meshgrid(torch.arange(5), torch.arange(5))+ input = input.to(device, dtype)+ actual = kornia.losses.total_variation(input, reduction=reduction)+ assert_close(actual, expected.to(device, dtype), rtol=1e-3, atol=1e-3)# Expect TypeError to be raised when non-torch tensors are passed@pytest.mark.parametrize('input', [1, [1, 2]])