π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Add Common Regression Losses (#2109)
Christoph Reich55ef09d1eb84
diff --git a/kornia/losses/__init__.py b/kornia/losses/__init__.pyindex e773bac0f..ac9b309fe 100644--- a/kornia/losses/__init__.py+++ b/kornia/losses/__init__.py@@ -1,7 +1,10 @@+from .cauchy import CauchyLoss, cauchy_loss+from .charbonnier import CharbonnierLoss, charbonnier_lossfrom .depth_smooth import InverseDepthSmoothnessLoss, inverse_depth_smoothness_lossfrom .dice import DiceLoss, dice_lossfrom .divergence import js_div_loss_2d, kl_div_loss_2dfrom .focal import BinaryFocalLossWithLogits, FocalLoss, binary_focal_loss_with_logits, focal_loss+from .geman_mcclure import GemanMcclureLoss, geman_mcclure_lossfrom .hausdorff import HausdorffERLoss, HausdorffERLoss3Dfrom .lovasz_hinge import LovaszHingeLoss, lovasz_hinge_lossfrom .lovasz_softmax import LovaszSoftmaxLoss, lovasz_softmax_loss@@ -11,6 +14,7 @@ from .ssim import SSIMLoss, ssim_lossfrom .ssim3d import SSIM3DLoss, ssim3d_lossfrom .total_variation import TotalVariation, total_variationfrom .tversky import TverskyLoss, tversky_loss+from .welsch import WelschLoss, welsch_loss__all__ = ["inverse_depth_smoothness_loss",@@ -40,4 +44,12 @@ __all__ = ["lovasz_hinge_loss","LovaszSoftmaxLoss","lovasz_softmax_loss",+ "WelschLoss",+ "welsch_loss",+ "CauchyLoss",+ "cauchy_loss",+ "GemanMcclureLoss",+ "geman_mcclure_loss",+ "CharbonnierLoss",+ "charbonnier_loss",]diff --git a/kornia/losses/cauchy.py b/kornia/losses/cauchy.pynew file mode 100644index 000000000..dea2a90a8--- /dev/null+++ b/kornia/losses/cauchy.py@@ -0,0 +1,106 @@+from torch import Tensor++from kornia.core import Module+from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_DEVICE, KORNIA_CHECK_SAME_SHAPE+++def cauchy_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Tensor:+ r"""Criterion that computes the Cauchy [2] (aka. Lorentzian) loss.++ According to [1], we compute the Cauchy loss as follows:++ .. math::++ \text{WL}(x, y) = log(\frac{1}{2} (x - y)^{2} + 1)++ Where:+ - :math:`x` expects to be the prediction.+ - :math:`z` expects to be the target to be regressed to.++ Reference:+ [1] https://arxiv.org/pdf/1701.03077.pdf+ [2] https://files.is.tue.mpg.de/black/papers/cviu.63.1.1996.pdf++ Args:+ img1: the predicted tensor with shape :math:`(*)`.+ img2: the target tensor with the same shape as img1.+ reduction: Specifies the reduction to apply to the+ output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction+ will be applied (default), ``'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 computed loss.++ Example:+ >>> img1 = torch.randn(2, 3, 32, 32, requires_grad=True)+ >>> img2 = torch.randn(2, 3, 32, 32)+ >>> output = cauchy_loss(img1, img2, reduction="mean")+ >>> output.backward()+ """+ KORNIA_CHECK_IS_TENSOR(img1)++ KORNIA_CHECK_IS_TENSOR(img2)++ KORNIA_CHECK_SAME_SHAPE(img1, img2)++ KORNIA_CHECK_SAME_DEVICE(img1, img2)++ KORNIA_CHECK(reduction in ("mean", "sum", "none"), f"Given type of reduction is not supported. Got: {reduction}")++ # compute loss+ loss = (0.5 * (img1 - img2) ** 2 + 1.0).log()++ # perform reduction+ if reduction == "mean":+ loss = loss.mean()+ elif reduction == "sum":+ loss = loss.sum()+ elif reduction == "none":+ pass+ return loss+++class CauchyLoss(Module):+ r"""Criterion that computes the Cauchy [2] (aka. Lorentzian) loss.++ According to [1], we compute the Cauchy loss as follows:++ .. math::++ \text{WL}(x, y) = log(\frac{1}{2} (x - y)^{2} + 1)++ Where:+ - :math:`x` expects to be the prediction.+ - :math:`z` expects to be the target to be regressed to.++ Reference:+ [1] https://arxiv.org/pdf/1701.03077.pdf+ [2] https://files.is.tue.mpg.de/black/papers/cviu.63.1.1996.pdf++ Args:+ reduction: Specifies the reduction to apply to the+ output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction+ will be applied (default), ``'mean'``: the sum of the output will be divided+ by the number of elements in the output, ``'sum'``: the output will be+ summed.++ Shape:+ - img1: the predicted tensor with shape :math:`(*)`.+ - img2: the target tensor with the same shape as img1.++ Example:+ >>> criterion = CauchyLoss(reduction="mean")+ >>> img1 = torch.randn(2, 3, 32, 2107, requires_grad=True)+ >>> img2 = torch.randn(2, 3, 32, 2107)+ >>> output = criterion(img1, img2)+ >>> output.backward()+ """++ def __init__(self, reduction: str = "none") -> None:+ super().__init__()+ self.reduction = reduction++ def forward(self, img1: Tensor, img2: Tensor) -> Tensor:+ return cauchy_loss(img1=img1, img2=img2, reduction=self.reduction)diff --git a/kornia/losses/charbonnier.py b/kornia/losses/charbonnier.pynew file mode 100644index 000000000..22015b728--- /dev/null+++ b/kornia/losses/charbonnier.py@@ -0,0 +1,118 @@+from torch import Tensor++from kornia.core import Module+from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_DEVICE, KORNIA_CHECK_SAME_SHAPE+++def charbonnier_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Tensor:+ r"""Criterion that computes the Charbonnier [2] (aka. L1-L2 [3]) loss.++ According to [1], we compute the Charbonnier loss as follows:++ .. math::++ \text{WL}(x, y) = \sqrt{(x - y)^{2} + 1} - 1++ Where:+ - :math:`x` expects to be the prediction.+ - :math:`z` expects to be the target to be regressed to.++ Reference:+ [1] https://arxiv.org/pdf/1701.03077.pdf+ [2] https://ieeexplore.ieee.org/document/413553+ [3] https://hal.inria.fr/inria-00074015/document+ [4] https://arxiv.org/pdf/1712.05927.pdf++ . note::+ This implementation follows the formulation by Barron [1]. Other works utilize+ a slightly different implementation (see [4]).++ Args:+ img1: the predicted tensor with shape :math:`(*)`.+ img2: the target tensor with the same shape as img1.+ reduction: Specifies the reduction to apply to the+ output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction+ will be applied (default), ``'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 computed loss.++ Example:+ >>> img1 = torch.randn(2, 3, 32, 32, requires_grad=True)+ >>> img2 = torch.randn(2, 3, 32, 32)+ >>> output = charbonnier_loss(img1, img2, reduction="sum")+ >>> output.backward()+ """+ KORNIA_CHECK_IS_TENSOR(img1)++ KORNIA_CHECK_IS_TENSOR(img2)++ KORNIA_CHECK_SAME_SHAPE(img1, img2)++ KORNIA_CHECK_SAME_DEVICE(img1, img2)++ KORNIA_CHECK(reduction in ("mean", "sum", "none"), f"Given type of reduction is not supported. Got: {reduction}")++ # compute loss+ loss = ((img1 - img2) ** 2 + 1.0).sqrt() - 1.0++ # perform reduction+ if reduction == "mean":+ loss = loss.mean()+ elif reduction == "sum":+ loss = loss.sum()+ elif reduction == "none":+ pass+ return loss+++class CharbonnierLoss(Module):+ r"""Criterion that computes the Charbonnier [2] (aka. L1-L2 [3]) loss.++ According to [1], we compute the Charbonnier loss as follows:++ .. math::++ \text{WL}(x, y) = \sqrt{(x - y)^{2} + 1} - 1++ Where:+ - :math:`x` expects to be the prediction.+ - :math:`z` expects to be the target to be regressed to.++ Reference:+ [1] https://arxiv.org/pdf/1701.03077.pdf+ [2] https://ieeexplore.ieee.org/document/413553+ [3] https://hal.inria.fr/inria-00074015/document+ [4] https://arxiv.org/pdf/1712.05927.pdf++ . note::+ This implementation follows the formulation by Barron [1]. Other works utilize+ a slightly different implementation (see [4]).++ Args:+ reduction: Specifies the reduction to apply to the+ output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction+ will be applied (default), ``'mean'``: the sum of the output will be divided+ by the number of elements in the output, ``'sum'``: the output will be+ summed.++ Shape:+ - img1: the predicted tensor with shape :math:`(*)`.+ - img2: the target tensor with the same shape as img1.++ Example:+ >>> criterion = CharbonnierLoss(reduction="mean")+ >>> img1 = torch.randn(2, 3, 32, 2107, requires_grad=True)+ >>> img2 = torch.randn(2, 3, 32, 2107)+ >>> output = criterion(img1, img2)+ >>> output.backward()+ """++ def __init__(self, reduction: str = "none") -> None:+ super().__init__()+ self.reduction = reduction++ def forward(self, img1: Tensor, img2: Tensor) -> Tensor:+ return charbonnier_loss(img1=img1, img2=img2, reduction=self.reduction)diff --git a/kornia/losses/geman_mcclure.py b/kornia/losses/geman_mcclure.pynew file mode 100644index 000000000..bc52cec81--- /dev/null+++ b/kornia/losses/geman_mcclure.py@@ -0,0 +1,106 @@+from torch import Tensor++from kornia.core import Module+from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_DEVICE, KORNIA_CHECK_SAME_SHAPE+++def geman_mcclure_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Tensor:+ r"""Criterion that computes the Geman-McClure loss [2].++ According to [1], we compute the Geman-McClure loss as follows:++ .. math::++ \text{WL}(x, y) = \frac{2 (x - y)^{2}}{(x - y)^{2} + 4}++ Where:+ - :math:`x` expects to be the prediction.+ - :math:`z` expects to be the target to be regressed to.++ Reference:+ [1] https://arxiv.org/pdf/1701.03077.pdf+ [2] Bayesian image analysis: An application to single photon emission tomography, Geman and McClure, 1985++ Args:+ img1: the predicted tensor with shape :math:`(*)`.+ img2: the target tensor with the same shape as img1.+ reduction: Specifies the reduction to apply to the+ output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction+ will be applied (default), ``'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 computed loss.++ Example:+ >>> img1 = torch.randn(2, 3, 32, 32, requires_grad=True)+ >>> img2 = torch.randn(2, 3, 32, 32)+ >>> output = geman_mcclure_loss(img1, img2, reduction="mean")+ >>> output.backward()+ """+ KORNIA_CHECK_IS_TENSOR(img1)++ KORNIA_CHECK_IS_TENSOR(img2)++ KORNIA_CHECK_SAME_SHAPE(img1, img2)++ KORNIA_CHECK_SAME_DEVICE(img1, img2)++ KORNIA_CHECK(reduction in ("mean", "sum", "none"), f"Given type of reduction is not supported. Got: {reduction}")++ # compute loss+ loss = 2.0 * (img1 - img2) ** 2 / ((img1 - img2) ** 2 + 4.0)++ # perform reduction+ if reduction == "mean":+ loss = loss.mean()+ elif reduction == "sum":+ loss = loss.sum()+ elif reduction == "none":+ pass+ return loss+++class GemanMcclureLoss(Module):+ r"""Criterion that computes the Geman-McClure loss [2].++ According to [1], we compute the Geman-McClure loss as follows:++ .. math::++ \text{WL}(x, y) = \frac{2 (x - y)^{2}}{(x - y)^{2} + 4}++ Where:+ - :math:`x` expects to be the prediction.+ - :math:`z` expects to be the target to be regressed to.++ Reference:+ [1] https://arxiv.org/pdf/1701.03077.pdf+ [2] Bayesian image analysis: An application to single photon emission tomography, Geman and McClure, 1985++ Args:+ reduction: Specifies the reduction to apply to the+ output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction+ will be applied (default), ``'mean'``: the sum of the output will be divided+ by the number of elements in the output, ``'sum'``: the output will be+ summed.++ Shape:+ - img1: the predicted tensor with shape :math:`(*)`.+ - img2: the target tensor with the same shape as img1.++ Example:+ >>> criterion = GemanMcclureLoss(reduction="mean")+ >>> img1 = torch.randn(2, 3, 32, 2107, requires_grad=True)+ >>> img2 = torch.randn(2, 3, 32, 2107)+ >>> output = criterion(img1, img2)+ >>> output.backward()+ """++ def __init__(self, reduction: str = "none") -> None:+ super().__init__()+ self.reduction = reduction++ def forward(self, img1: Tensor, img2: Tensor) -> Tensor:+ return geman_mcclure_loss(img1=img1, img2=img2, reduction=self.reduction)diff --git a/kornia/losses/welsch.py b/kornia/losses/welsch.pynew file mode 100644index 000000000..c22b2670b--- /dev/null+++ b/kornia/losses/welsch.py@@ -0,0 +1,108 @@+from torch import Tensor++from kornia.core import Module+from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_DEVICE, KORNIA_CHECK_SAME_SHAPE+++def welsch_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Tensor:+ r"""Criterion that computes the Welsch [2] (aka. Leclerc [3]) loss.++ According to [1], we compute the Welsch loss as follows:++ .. math::++ \text{WL}(x, y) = 1 - exp(-\frac{1}{2} (x - y)^{2})++ Where:+ - :math:`x` expects to be the prediction.+ - :math:`z` expects to be the target to be regressed to.++ Reference:+ [1] https://arxiv.org/pdf/1701.03077.pdf+ [2] https://www.tandfonline.com/doi/abs/10.1080/03610917808812083+ [3] https://link.springer.com/article/10.1007/BF00054839++ Args:+ img1: the predicted tensor with shape :math:`(*)`.+ img2: the target tensor with the same shape as img1.+ reduction: Specifies the reduction to apply to the+ output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction+ will be applied (default), ``'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 computed loss.++ Example:+ >>> img1 = torch.randn(2, 3, 32, 32, requires_grad=True)+ >>> img2 = torch.randn(2, 3, 32, 32)+ >>> output = welsch_loss(img1, img2, reduction="mean")+ >>> output.backward()+ """+ KORNIA_CHECK_IS_TENSOR(img1)++ KORNIA_CHECK_IS_TENSOR(img2)++ KORNIA_CHECK_SAME_SHAPE(img1, img2)++ KORNIA_CHECK_SAME_DEVICE(img1, img2)++ KORNIA_CHECK(reduction in ("mean", "sum", "none"), f"Given type of reduction is not supported. Got: {reduction}")++ # compute loss+ loss = 1.0 - (-0.5 * (img1 - img2) ** 2).exp()++ # perform reduction+ if reduction == "mean":+ loss = loss.mean()+ elif reduction == "sum":+ loss = loss.sum()+ elif reduction == "none":+ pass+ return loss+++class WelschLoss(Module):+ r"""Criterion that computes the Welsch [2] (aka. Leclerc [3]) loss.++ According to [1], we compute the Welsch loss as follows:++ .. math::++ \text{WL}(x, y) = 1 - exp(-\frac{1}{2} (x - y)^{2})++ Where:+ - :math:`x` expects to be the prediction.+ - :math:`z` expects to be the target to be regressed to.++ Reference:+ [1] https://arxiv.org/pdf/1701.03077.pdf+ [2] https://www.tandfonline.com/doi/abs/10.1080/03610917808812083+ [3] https://link.springer.com/article/10.1007/BF00054839++ Args:+ reduction: Specifies the reduction to apply to the+ output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction+ will be applied (default), ``'mean'``: the sum of the output will be divided+ by the number of elements in the output, ``'sum'``: the output will be+ summed.++ Shape:+ - img1: the predicted tensor with shape :math:`(*)`.+ - img2: the target tensor with the same shape as img1.++ Example:+ >>> criterion = WelschLoss(reduction="mean")+ >>> img1 = torch.randn(2, 3, 32, 1904, requires_grad=True)+ >>> img2 = torch.randn(2, 3, 32, 1904)+ >>> output = criterion(img1, img2)+ >>> output.backward()+ """++ def __init__(self, reduction: str = "none") -> None:+ super().__init__()+ self.reduction = reduction++ def forward(self, img1: Tensor, img2: Tensor) -> Tensor:+ return welsch_loss(img1=img1, img2=img2, reduction=self.reduction)diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.pyindex 348bbc6a8..4449285b7 100644--- a/kornia/testing/__init__.py+++ b/kornia/testing/__init__.py@@ -27,7 +27,6 @@ __all__ = ["KORNIA_CHECK_SAME_DEVICES","KORNIA_CHECK_IS_COLOR","KORNIA_CHECK_IS_GRAY",- "KORNIA_CHECK_IS_COLR_OR_GRAY","KORNIA_CHECK_DM_DESC","KORNIA_CHECK_LAF",]@@ -457,6 +456,26 @@ def KORNIA_CHECK_SAME_DEVICES(tensors: List[Tensor], msg: Optional[str] = None):raise Exception(f"Not same device for tensors. Got: {[x.device for x in tensors]}.\n{msg}")+def KORNIA_CHECK_SAME_SHAPE(x: Tensor, y: Tensor) -> None:+ """Check whether two tensor have the same shape.++ Args:+ x: first tensor to evaluate.+ y: sencod tensor to evaluate.+ msg: message to show in the exception.++ Raises:+ TypeException: if the two tensors have not the same shape.++ Example:+ >>> x1 = torch.rand(2, 3, 3)+ >>> x2 = torch.rand(2, 3, 3)+ >>> KORNIA_CHECK_SAME_SHAPE(x1, x2)+ """+ if x.shape != y.shape:+ raise TypeError(f"Not same shape for tensors. Got: {x.shape} and {y.shape}")++def KORNIA_CHECK_IS_COLOR(x: Tensor, msg: Optional[str] = None):"""Check whether an image tensor is a color images.diff --git a/test/losses/test_losses.py b/test/losses/test_losses.pyindex 42346c2e1..a9ff01c69 100644--- a/test/losses/test_losses.py+++ b/test/losses/test_losses.py@@ -93,7 +93,7 @@ class TestBinaryFocalLossWithLogits:logits = torch.rand(2, 3, 2, dtype=dtype, device=device)labels = torch.rand(2, 3, 2, dtype=dtype, device=device)- kwargs = {"alpha": 0.25, "gamma": 2.0, "reduction": 'mean'}+ kwargs = {"alpha": 0.25, "gamma": 2.0, "reduction": "mean"}assert kornia.losses.binary_focal_loss_with_logits(logits, labels, **kwargs@@ -336,7 +336,7 @@ class TestDepthSmoothnessLoss:class TestDivergenceLoss:@pytest.mark.parametrize(- 'input,target,expected',+ "input,target,expected",[(torch.full((1, 1, 2, 4), 0.125), torch.full((1, 1, 2, 4), 0.125), 0.0),(torch.full((1, 7, 2, 4), 0.125), torch.full((1, 7, 2, 4), 0.125), 0.0),@@ -350,7 +350,7 @@ class TestDivergenceLoss:assert_close(actual, expected)@pytest.mark.parametrize(- 'input,target,expected',+ "input,target,expected",[(torch.full((1, 1, 2, 4), 0.125), torch.full((1, 1, 2, 4), 0.125), 0.0),(torch.full((1, 7, 2, 4), 0.125), torch.full((1, 7, 2, 4), 0.125), 0.0),@@ -364,7 +364,7 @@ class TestDivergenceLoss:assert_close(actual, expected)@pytest.mark.parametrize(- 'input,target,expected',+ "input,target,expected",[(torch.full((1, 1, 2, 4), 0.125), torch.full((1, 1, 2, 4), 0.125), torch.full((1, 1), 0.0)),(torch.full((1, 7, 2, 4), 0.125), torch.full((1, 7, 2, 4), 0.125), torch.full((1, 7), 0.0)),@@ -373,11 +373,11 @@ class TestDivergenceLoss:],)def test_kl_div_loss_2d_without_reduction(self, device, dtype, input, target, expected):- actual = kornia.losses.kl_div_loss_2d(input.to(device, dtype), target.to(device, dtype), reduction='none')+ actual = kornia.losses.kl_div_loss_2d(input.to(device, dtype), target.to(device, dtype), reduction="none")assert_close(actual, expected.to(device, dtype))@pytest.mark.parametrize(- 'input,target,expected',+ "input,target,expected",[(torch.full((1, 1, 2, 4), 0.125), torch.full((1, 1, 2, 4), 0.125), 0.0),(torch.full((1, 7, 2, 4), 0.125), torch.full((1, 7, 2, 4), 0.125), 0.0),@@ -393,7 +393,7 @@ class TestDivergenceLoss:assert_close(actual, expected)@pytest.mark.parametrize(- 'input,target,expected',+ "input,target,expected",[(torch.full((1, 1, 2, 4), 0.125), torch.full((1, 1, 2, 4), 0.125), 0.0),(torch.full((1, 7, 2, 4), 0.125), torch.full((1, 7, 2, 4), 0.125), 0.0),@@ -446,7 +446,7 @@ class TestDivergenceLoss:class TestTotalVariation:# Total variation of constant vectors is 0@pytest.mark.parametrize(- 'input, expected',+ "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]])),@@ -458,7 +458,7 @@ class TestTotalVariation:# Total variation for 3D tensors@pytest.mark.parametrize(- 'input, expected',+ "input, expected",[(torch.tensor(@@ -497,7 +497,7 @@ class TestTotalVariation:# Total variation for 4D tensors@pytest.mark.parametrize(- 'input, expected',+ "input, expected",[(torch.tensor(@@ -532,7 +532,7 @@ class TestTotalVariation:actual = 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)])+ @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 = []@@ -543,15 +543,15 @@ class TestTotalVariation: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))])+ @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)], 'ij')+ input, _ = torch_meshgrid([torch.arange(5), torch.arange(5)], "ij")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]])+ @pytest.mark.parametrize("input", [1, [1, 2]])def test_tv_on_invalid_types(self, device, dtype, input):with pytest.raises(TypeError):kornia.losses.total_variation(input)@@ -762,3 +762,227 @@ class TestLovaszSoftmaxLoss:op_module = kornia.losses.LovaszSoftmaxLoss()assert_close(op(logits, labels), op_module(logits, labels))+++class TestWelschLoss:+ def test_smoke(self, device, dtype):+ img1 = torch.rand(2, 3, 2, device=device, dtype=dtype)+ img2 = torch.rand(2, 3, 2)+ img2 = img2.to(device).long()++ criterion = kornia.losses.WelschLoss()+ assert criterion(img1, img2) is not None++ def test_gradcheck(self, device, dtype):+ img1 = torch.rand(2, 3, 64, 12, device=device, dtype=dtype)+ img2 = torch.rand(2, 3, 64, 12)+ img2 = img2.to(device).long()++ img1 = utils.tensor_to_gradcheck_var(img1) # to var+ assert gradcheck(kornia.losses.welsch_loss, (img1, img2), raise_exception=True, fast_mode=True)++ def test_jit(self, device, dtype):+ img1 = torch.rand(2, 3, 64, 1904, device=device, dtype=dtype)+ img2 = torch.rand(2, 3, 64, 1904)+ img2 = img2.to(device).long()++ op = kornia.losses.welsch_loss+ op_script = torch.jit.script(op)++ assert_close(op(img1, img2), op_script(img1, img2))++ def test_module(self, device, dtype):+ img1 = torch.rand(2, 3, 32, 1904, device=device, dtype=dtype)+ img2 = torch.rand(2, 3, 32, 1904)+ img2 = img2.to(device).long()++ op = kornia.losses.welsch_loss+ op_module = kornia.losses.WelschLoss()++ assert_close(op(img1, img2), op_module(img1, img2))++ def test_perfect_prediction(self, device, dtype):+ img1 = torch.ones(100, device=device, dtype=dtype)+ img2 = torch.ones(100, device=device, dtype=torch.int64)++ criterion = kornia.losses.WelschLoss()+ loss = criterion(img1, img2)+ assert_close(loss, torch.zeros_like(loss), rtol=1e-3, atol=1e-3)++ def test_shape(self, device, dtype):+ criterion = kornia.losses.WelschLoss()+ with pytest.raises(Exception):+ criterion(torch.rand(2, 3, 3, 2), torch.rand(2, 3, 3))++ def test_reduction(self, device, dtype):+ criterion = kornia.losses.WelschLoss(reduction="test")+ with pytest.raises(Exception):+ criterion(torch.rand(3, 3), torch.rand(3, 3))+++class TestCauchyLoss:+ def test_smoke(self, device, dtype):+ img1 = torch.rand(2, 3, 2, device=device, dtype=dtype)+ img2 = torch.rand(2, 3, 2)+ img2 = img2.to(device).long()++ criterion = kornia.losses.CauchyLoss()+ assert criterion(img1, img2) is not None++ def test_gradcheck(self, device, dtype):+ img1 = torch.rand(2, 3, 64, 12, device=device, dtype=dtype)+ img2 = torch.rand(2, 3, 64, 12)+ img2 = img2.to(device).long()++ img1 = utils.tensor_to_gradcheck_var(img1) # to var+ assert gradcheck(kornia.losses.cauchy_loss, (img1, img2), raise_exception=True, fast_mode=True)++ def test_jit(self, device, dtype):+ img1 = torch.rand(2, 3, 64, 1904, device=device, dtype=dtype)+ img2 = torch.rand(2, 3, 64, 1904)+ img2 = img2.to(device).long()++ op = kornia.losses.cauchy_loss+ op_script = torch.jit.script(op)++ assert_close(op(img1, img2), op_script(img1, img2))++ def test_module(self, device, dtype):+ img1 = torch.rand(2, 3, 32, 1904, device=device, dtype=dtype)+ img2 = torch.rand(2, 3, 32, 1904)+ img2 = img2.to(device).long()++ op = kornia.losses.cauchy_loss+ op_module = kornia.losses.CauchyLoss()++ assert_close(op(img1, img2), op_module(img1, img2))++ def test_perfect_prediction(self, device, dtype):+ img1 = torch.ones(100, device=device, dtype=dtype)+ img2 = torch.ones(100, device=device, dtype=torch.int64)++ criterion = kornia.losses.CauchyLoss()+ loss = criterion(img1, img2)+ assert_close(loss, torch.zeros_like(loss), rtol=1e-3, atol=1e-3)++ def test_shape(self, device, dtype):+ criterion = kornia.losses.CauchyLoss()+ with pytest.raises(Exception):+ criterion(torch.rand(2, 3, 3, 2), torch.rand(2, 3, 3))++ def test_reduction(self, device, dtype):+ criterion = kornia.losses.CauchyLoss(reduction="test")+ with pytest.raises(Exception):+ criterion(torch.rand(2, 2), torch.rand(2, 2))+++class TestGemanMcclureLossLoss:+ def test_smoke(self, device, dtype):+ img1 = torch.rand(2, 3, 2, device=device, dtype=dtype)+ img2 = torch.rand(2, 3, 2)+ img2 = img2.to(device).long()++ criterion = kornia.losses.GemanMcclureLoss()+ assert criterion(img1, img2) is not None++ def test_gradcheck(self, device, dtype):+ img1 = torch.rand(2, 3, 64, 12, device=device, dtype=dtype)+ img2 = torch.rand(2, 3, 64, 12)+ img2 = img2.to(device).long()++ img1 = utils.tensor_to_gradcheck_var(img1) # to var+ assert gradcheck(kornia.losses.geman_mcclure_loss, (img1, img2), raise_exception=True, fast_mode=True)++ def test_jit(self, device, dtype):+ img1 = torch.rand(2, 3, 64, 1904, device=device, dtype=dtype)+ img2 = torch.rand(2, 3, 64, 1904)+ img2 = img2.to(device).long()++ op = kornia.losses.geman_mcclure_loss+ op_script = torch.jit.script(op)++ assert_close(op(img1, img2), op_script(img1, img2))++ def test_module(self, device, dtype):+ img1 = torch.rand(2, 3, 32, 1904, device=device, dtype=dtype)+ img2 = torch.rand(2, 3, 32, 1904)+ img2 = img2.to(device).long()++ op = kornia.losses.geman_mcclure_loss+ op_module = kornia.losses.GemanMcclureLoss()++ assert_close(op(img1, img2), op_module(img1, img2))++ def test_perfect_prediction(self, device, dtype):+ img1 = torch.ones(100, device=device, dtype=dtype)+ img2 = torch.ones(100, device=device, dtype=torch.int64)++ criterion = kornia.losses.GemanMcclureLoss()+ loss = criterion(img1, img2)+ assert_close(loss, torch.zeros_like(loss), rtol=1e-3, atol=1e-3)++ def test_shape(self, device, dtype):+ criterion = kornia.losses.GemanMcclureLoss()+ with pytest.raises(Exception):+ criterion(torch.rand(2, 3, 3, 2), torch.rand(2, 3, 3))++ def test_reduction(self, device, dtype):+ criterion = kornia.losses.GemanMcclureLoss(reduction="test")+ with pytest.raises(Exception):+ criterion(torch.rand(4, 4), torch.rand(4, 4))+++class TestCharbonnierLoss:+ def test_smoke(self, device, dtype):+ img1 = torch.rand(2, 3, 2, device=device, dtype=dtype)+ img2 = torch.rand(2, 3, 2)+ img2 = img2.to(device).long()++ criterion = kornia.losses.CharbonnierLoss()+ assert criterion(img1, img2) is not None++ def test_gradcheck(self, device, dtype):+ img1 = torch.rand(2, 3, 64, 12, device=device, dtype=dtype)+ img2 = torch.rand(2, 3, 64, 12)+ img2 = img2.to(device).long()++ img1 = utils.tensor_to_gradcheck_var(img1) # to var+ assert gradcheck(kornia.losses.charbonnier_loss, (img1, img2), raise_exception=True, fast_mode=True)++ def test_jit(self, device, dtype):+ img1 = torch.rand(2, 3, 64, 1904, device=device, dtype=dtype)+ img2 = torch.rand(2, 3, 64, 1904)+ img2 = img2.to(device).long()++ op = kornia.losses.charbonnier_loss+ op_script = torch.jit.script(op)++ assert_close(op(img1, img2), op_script(img1, img2))++ def test_module(self, device, dtype):+ img1 = torch.rand(2, 3, 32, 1904, device=device, dtype=dtype)+ img2 = torch.rand(2, 3, 32, 1904)+ img2 = img2.to(device).long()++ op = kornia.losses.charbonnier_loss+ op_module = kornia.losses.CharbonnierLoss()++ assert_close(op(img1, img2), op_module(img1, img2))++ def test_perfect_prediction(self, device, dtype):+ img1 = torch.ones(100, device=device, dtype=dtype)+ img2 = torch.ones(100, device=device, dtype=torch.int64)++ criterion = kornia.losses.CharbonnierLoss()+ loss = criterion(img1, img2)+ assert_close(loss, torch.zeros_like(loss), rtol=1e-3, atol=1e-3)++ def test_shape(self, device, dtype):+ criterion = kornia.losses.CharbonnierLoss()+ with pytest.raises(Exception):+ criterion(torch.rand(2, 3, 3, 2), torch.rand(2, 3, 3))++ def test_reduction(self, device, dtype):+ criterion = kornia.losses.CharbonnierLoss(reduction="test")+ with pytest.raises(Exception):+ criterion(torch.rand(4, 4), torch.rand(4, 4))