π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[feat] Add Lovasz-Hinge/Softmax losses (#1682)
Christoph Reich8cdf7ae68e8d
diff --git a/docs/source/losses.rst b/docs/source/losses.rstindex d18fcd331..b9fa286aa 100644--- a/docs/source/losses.rst+++ b/docs/source/losses.rst@@ -11,6 +11,12 @@ Reconstruction.. autofunction:: total_variation.. autofunction:: inverse_depth_smoothness_loss+.. autoclass:: SSIMLoss+.. autoclass:: MS_SSIMLoss+.. autoclass:: TotalVariation+.. autoclass:: PSNRLoss+.. autoclass:: InverseDepthSmoothnessLoss+Semantic Segmentation---------------------@@ -18,6 +24,15 @@ Semantic Segmentation.. autofunction:: focal_loss.. autofunction:: dice_loss.. autofunction:: tversky_loss+.. autofunction:: lovasz_hinge_loss+.. autofunction:: lovasz_softmax_loss++.. autoclass:: BinaryFocalLossWithLogits+.. autoclass:: DiceLoss+.. autoclass:: TverskyLoss+.. autoclass:: FocalLoss+.. autoclass:: LovaszHingeLoss+.. autoclass:: LovaszSoftmaxLossDistributions-------------@@ -30,16 +45,3 @@ Morphology.. autoclass:: HausdorffERLoss.. autoclass:: HausdorffERLoss3D--Module---------.. autoclass:: DiceLoss-.. autoclass:: TverskyLoss-.. autoclass:: FocalLoss-.. autoclass:: SSIMLoss-.. autoclass:: MS_SSIMLoss-.. autoclass:: InverseDepthSmoothnessLoss-.. autoclass:: TotalVariation-.. autoclass:: PSNRLoss-.. autoclass:: BinaryFocalLossWithLogitsdiff --git a/kornia/losses/__init__.py b/kornia/losses/__init__.pyindex 6bab3521e..f21e0a72d 100644--- a/kornia/losses/__init__.py+++ b/kornia/losses/__init__.py@@ -3,6 +3,8 @@ from .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_lossfrom .hausdorff import HausdorffERLoss, HausdorffERLoss3D+from .lovasz_hinge import LovaszHingeLoss, lovasz_hinge_loss+from .lovasz_softmax import LovaszSoftmaxLoss, lovasz_softmax_lossfrom .ms_ssim import MS_SSIMLossfrom .psnr import PSNRLoss, psnr_lossfrom .ssim import SSIMLoss, ssim_loss@@ -31,4 +33,8 @@ __all__ = ["tversky_loss","TverskyLoss","MS_SSIMLoss",+ "LovaszHingeLoss",+ "lovasz_hinge_loss",+ "LovaszSoftmaxLoss",+ "lovasz_softmax_loss",]diff --git a/kornia/losses/lovasz_hinge.py b/kornia/losses/lovasz_hinge.pynew file mode 100644index 000000000..dc5f76878--- /dev/null+++ b/kornia/losses/lovasz_hinge.py@@ -0,0 +1,140 @@+import torch+import torch.nn as nn+from torch import Tensor++from kornia.testing import KORNIA_CHECK_SHAPE++# based on:+# https://github.com/bermanmaxim/LovaszSoftmax+++def lovasz_hinge_loss(pred: Tensor, target: Tensor) -> Tensor:+ r"""Criterion that computes a surrogate binary intersection-over-union (IoU) loss.++ According to [2], we compute the IoU as follows:++ .. math::++ \text{IoU}(x, class) = \frac{|X \cap Y|}{|X \cup Y|}++ [1] approximates this fomular with a surrogate, which is fully differentable.++ Where:+ - :math:`X` expects to be the scores of each class.+ - :math:`Y` expects to be the binary tensor with the class labels.++ the loss, is finally computed as:++ .. math::++ \text{loss}(x, class) = 1 - \text{IoU}(x, class)++ Reference:+ [1] http://proceedings.mlr.press/v37/yub15.pdf+ [2] https://arxiv.org/pdf/1705.08790.pdf++ . note::+ This loss function only supports binary labels. For multi-class labels please+ use the Lovasz-Softmax loss.++ Args:+ pred: logits tensor with shape :math:`(N, 1, H, W)`.+ labels: labels tensor with shape :math:`(N, H, W)` with binary values.++ Return:+ a scalar with the computed loss.++ Example:+ >>> N = 1 # num_classes+ >>> pred = torch.randn(1, N, 3, 5, requires_grad=True)+ >>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)+ >>> output = lovasz_hinge_loss(pred, target)+ >>> output.backward()+ """+ KORNIA_CHECK_SHAPE(pred, ["B", "1", "H", "W"])++ KORNIA_CHECK_SHAPE(target, ["B", "H", "W"])++ if not pred.shape[1] == 1:+ raise ValueError(f"Invalid pred shape, we expect Bx1xHxW. Got: {pred.shape}")++ if not pred.shape[-2:] == target.shape[-2:]:+ raise ValueError(f"pred and target shapes must be the same. Got: {pred.shape} and {target.shape}")++ if not pred.device == target.device:+ raise ValueError(f"pred and target must be in the same device. Got: {pred.device} and {target.device}")++ # flatten pred and target [B, -1] and to float+ pred_flatten: Tensor = pred.reshape(pred.shape[0], -1)+ target_flatten: Tensor = target.reshape(target.shape[0], -1)++ # get shapes+ B, N = pred_flatten.shape++ # compute actual loss+ signs = 2. * target_flatten - 1.+ errors = 1. - pred_flatten * signs+ errors_sorted, permutation = errors.sort(dim=1, descending=True)+ batch_index: Tensor = torch.arange(B, device=pred.device).reshape(-1, 1).repeat(1, N).reshape(-1)+ target_sorted: Tensor = target_flatten[batch_index, permutation.view(-1)]+ target_sorted = target_sorted.view(B, N)+ target_sorted_sum: Tensor = target_sorted.sum(1, keepdim=True)+ intersection: Tensor = target_sorted_sum - target_sorted.cumsum(1)+ union: Tensor = target_sorted_sum + (1. - target_sorted).cumsum(1)+ gradient: Tensor = 1. - intersection / union+ if N > 1:+ gradient[..., 1:] = gradient[..., 1:] - gradient[..., :-1]+ loss: Tensor = (errors_sorted.relu() * gradient).sum(1).mean()+ return loss+++class LovaszHingeLoss(nn.Module):+ r"""Criterion that computes a surrogate binary intersection-over-union (IoU) loss.++ According to [2], we compute the IoU as follows:++ .. math::++ \text{IoU}(x, class) = \frac{|X \cap Y|}{|X \cup Y|}++ [1] approximates this fomular with a surrogate, which is fully differentable.++ Where:+ - :math:`X` expects to be the scores of each class.+ - :math:`Y` expects to be the binary tensor with the class labels.++ the loss, is finally computed as:++ .. math::++ \text{loss}(x, class) = 1 - \text{IoU}(x, class)++ Reference:+ [1] http://proceedings.mlr.press/v37/yub15.pdf+ [2] https://arxiv.org/pdf/1705.08790.pdf++ . note::+ This loss function only supports binary labels. For multi-class labels please+ use the Lovasz-Softmax loss.++ Args:+ pred: logits tensor with shape :math:`(N, 1, H, W)`.+ labels: labels tensor with shape :math:`(N, H, W)` with binary values.++ Return:+ a scalar with the computed loss.++ Example:+ >>> N = 1 # num_classes+ >>> criterion = LovaszHingeLoss()+ >>> pred = torch.randn(1, N, 3, 5, requires_grad=True)+ >>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)+ >>> output = criterion(pred, target)+ >>> output.backward()+ """++ def __init__(self) -> None:+ super().__init__()++ def forward(self, pred: Tensor, target: Tensor) -> Tensor:+ return lovasz_hinge_loss(pred=pred, target=target)diff --git a/kornia/losses/lovasz_softmax.py b/kornia/losses/lovasz_softmax.pynew file mode 100644index 000000000..5a1b5ed85--- /dev/null+++ b/kornia/losses/lovasz_softmax.py@@ -0,0 +1,150 @@+from typing import List++import torch+import torch.nn as nn+from torch import Tensor++from kornia.testing import KORNIA_CHECK_SHAPE++# based on:+# https://github.com/bermanmaxim/LovaszSoftmax+++def lovasz_softmax_loss(pred: Tensor, target: Tensor) -> Tensor:+ r"""Criterion that computes a surrogate multi-class intersection-over-union (IoU) loss.++ According to [1], we compute the IoU as follows:++ .. math::++ \text{IoU}(x, class) = \frac{|X \cap Y|}{|X \cup Y|}++ [1] approximates this fomular with a surrogate, which is fully differentable.++ Where:+ - :math:`X` expects to be the scores of each class.+ - :math:`Y` expects to be the binary tensor with the class labels.++ the loss, is finally computed as:++ .. math::++ \text{loss}(x, class) = 1 - \text{IoU}(x, class)++ Reference:+ [1] https://arxiv.org/pdf/1705.08790.pdf++ . note::+ This loss function only supports multi-class (C > 1) labels. For binary+ labels please use the Lovasz-Hinge loss.++ Args:+ pred: logits tensor with shape :math:`(N, C, H, W)` where C = number of classes > 1.+ labels: labels tensor with shape :math:`(N, H, W)` where each value+ is :math:`0 β€ targets[i] β€ Cβ1`.++ Return:+ a scalar with the computed loss.++ Example:+ >>> N = 5 # num_classes+ >>> pred = torch.randn(1, N, 3, 5, requires_grad=True)+ >>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)+ >>> output = lovasz_softmax_loss(pred, target)+ >>> output.backward()+ """+ KORNIA_CHECK_SHAPE(pred, ["B", "N", "H", "W"])++ KORNIA_CHECK_SHAPE(target, ["B", "H", "W"])++ if not pred.shape[1] > 1:+ raise ValueError(f"Invalid pred shape, we expect BxNxHxW, with N > 1. Got: {pred.shape}")++ if not pred.shape[-2:] == target.shape[-2:]:+ raise ValueError(f"pred and target shapes must be the same. Got: {pred.shape} and {target.shape}")++ if not pred.device == target.device:+ raise ValueError(f"pred and target must be in the same device. Got: {pred.device} and {target.device}")++ # flatten pred [B, C, -1] and target [B, -1] and to float+ pred_flatten: Tensor = pred.reshape(pred.shape[0], pred.shape[1], -1)+ target_flatten: Tensor = target.reshape(target.shape[0], -1).float()++ # get shapes+ B, C, N = pred_flatten.shape++ # compute softmax over the classes axis+ pred_soft: Tensor = pred_flatten.softmax(1)++ # compute actual loss+ losses: List[Tensor] = []+ batch_index: Tensor = torch.arange(B, device=pred.device).reshape(-1, 1).repeat(1, N).reshape(-1)+ for c in range(C):+ foreground: Tensor = 1. * (target_flatten == c)+ class_pred: Tensor = pred_soft[:, c]+ errors = (class_pred - foreground).abs()+ errors_sorted, permutation = torch.sort(errors, dim=1, descending=True)+ target_sorted: Tensor = target_flatten[batch_index, permutation.view(-1)]+ target_sorted = target_sorted.view(B, N)+ target_sorted_sum: Tensor = target_sorted.sum(1, keepdim=True)+ intersection: Tensor = target_sorted_sum - target_sorted.cumsum(1)+ union: Tensor = target_sorted_sum + (1. - target_sorted).cumsum(1)+ gradient: Tensor = 1. - intersection / union+ if N > 1:+ gradient[..., 1:] = gradient[..., 1:] - gradient[..., :-1]+ loss: Tensor = (errors_sorted.relu() * gradient).sum(1).mean()+ losses.append(loss)+ final_loss: Tensor = torch.stack(losses, dim=0).mean()+ return final_loss+++class LovaszSoftmaxLoss(nn.Module):+ r"""Criterion that computes a surrogate multi-class intersection-over-union (IoU) loss.++ According to [1], we compute the IoU as follows:++ .. math::++ \text{IoU}(x, class) = \frac{|X \cap Y|}{|X \cup Y|}++ [1] approximates this fomular with a surrogate, which is fully differentable.++ Where:+ - :math:`X` expects to be the scores of each class.+ - :math:`Y` expects to be the binary tensor with the class labels.++ the loss, is finally computed as:++ .. math::++ \text{loss}(x, class) = 1 - \text{IoU}(x, class)++ Reference:+ [1] https://arxiv.org/pdf/1705.08790.pdf++ . note::+ This loss function only supports multi-class (C > 1) labels. For binary+ labels please use the Lovasz-Hinge loss.++ Args:+ pred: logits tensor with shape :math:`(N, C, H, W)` where C = number of classes > 1.+ labels: labels tensor with shape :math:`(N, H, W)` where each value+ is :math:`0 β€ targets[i] β€ Cβ1`.++ Return:+ a scalar with the computed loss.++ Example:+ >>> N = 5 # num_classes+ >>> criterion = LovaszSoftmaxLoss()+ >>> pred = torch.randn(1, N, 3, 5, requires_grad=True)+ >>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)+ >>> output = criterion(pred, target)+ >>> output.backward()+ """++ def __init__(self) -> None:+ super().__init__()++ def forward(self, pred: Tensor, target: Tensor) -> Tensor:+ return lovasz_softmax_loss(pred=pred, target=target)diff --git a/test/losses/test_losses.py b/test/losses/test_losses.pyindex 0f6093390..ed8879364 100644--- a/test/losses/test_losses.py+++ b/test/losses/test_losses.py@@ -22,28 +22,22 @@ class TestBinaryFocalLossWithLogits:logits = torch.rand(2, 3, 2, dtype=dtype, device=device)labels = torch.rand(2, 3, 2, dtype=dtype, device=device)- assert (- kornia.losses.binary_focal_loss_with_logits(logits, labels, alpha=0.5, gamma=2.0, reduction="sum").shape- == ()- )+ assert (kornia.losses.binary_focal_loss_with_logits(+ logits, labels, alpha=0.5, gamma=2.0, reduction="sum").shape == ())def test_smoke_mean(self, device, dtype):logits = torch.rand(2, 3, 2, dtype=dtype, device=device)labels = torch.rand(2, 3, 2, dtype=dtype, device=device)- assert (- kornia.losses.binary_focal_loss_with_logits(logits, labels, alpha=0.5, gamma=2.0, reduction="mean").shape- == ()- )+ assert (kornia.losses.binary_focal_loss_with_logits(+ logits, labels, alpha=0.5, gamma=2.0, reduction="mean").shape == ())def test_smoke_mean_flat(self, device, dtype):logits = torch.rand(2, 3, 2, dtype=dtype, device=device)labels = torch.rand(2, 3, 2, dtype=dtype, device=device)- assert (- kornia.losses.binary_focal_loss_with_logits(logits, labels, alpha=0.5, gamma=2.0, reduction="mean").shape- == ()- )+ assert (kornia.losses.binary_focal_loss_with_logits(+ logits, labels, alpha=0.5, gamma=2.0, reduction="mean").shape == ())def test_jit(self, device, dtype):logits = torch.rand(2, 3, 2, dtype=dtype, device=device)@@ -580,3 +574,130 @@ class TestPSNRLoss:input = utils.tensor_to_gradcheck_var(input) # to vartarget = utils.tensor_to_gradcheck_var(target) # to varassert gradcheck(kornia.losses.psnr_loss, (input, target, 1.0), raise_exception=True)+++class TestLovaszHingeLoss:++ def test_smoke(self, device, dtype):+ num_classes = 1+ logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)+ labels = torch.rand(2, 3, 2) * num_classes+ labels = labels.to(device).long()++ criterion = kornia.losses.LovaszHingeLoss()+ assert criterion(logits, labels) is not None++ def test_multi_class(self, device, dtype):+ num_classes = 5+ logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)+ labels = torch.rand(2, 3, 2) * num_classes+ labels = labels.to(device).long()++ criterion = kornia.losses.LovaszHingeLoss()+ with pytest.raises(Exception):+ criterion(logits, labels)++ def test_perfect_prediction(self, device, dtype):+ num_classes = 1+ prediction = torch.ones(2, num_classes, 1, 2, device=device, dtype=dtype)+ labels = torch.ones(2, 1, 2, device=device, dtype=torch.int64)++ criterion = kornia.losses.LovaszHingeLoss()+ loss = criterion(prediction, labels)+ assert_close(loss, torch.zeros_like(loss), rtol=1e-3, atol=1e-3)++ def test_gradcheck(self, device, dtype):+ num_classes = 1+ logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)+ labels = torch.rand(2, 3, 2) * num_classes+ labels = labels.to(device).long()++ logits = utils.tensor_to_gradcheck_var(logits) # to var+ assert gradcheck(kornia.losses.lovasz_hinge_loss, (logits, labels), raise_exception=True)++ def test_jit(self, device, dtype):+ num_classes = 1+ logits = torch.rand(2, num_classes, 1, 2, device=device, dtype=dtype)+ labels = torch.rand(2, 1, 2) * num_classes+ labels = labels.to(device).long()++ op = kornia.losses.lovasz_hinge_loss+ op_script = torch.jit.script(op)++ assert_close(op(logits, labels), op_script(logits, labels))++ def test_module(self, device, dtype):+ num_classes = 1+ logits = torch.rand(2, num_classes, 1, 2, device=device, dtype=dtype)+ labels = torch.rand(2, 1, 2) * num_classes+ labels = labels.to(device).long()++ op = kornia.losses.lovasz_hinge_loss+ op_module = kornia.losses.LovaszHingeLoss()++ assert_close(op(logits, labels), op_module(logits, labels))+++class TestLovaszSoftmaxLoss:+ def test_smoke(self, device, dtype):+ num_classes = 3+ logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)+ labels = torch.rand(2, 3, 2) * num_classes+ labels = labels.to(device).long()++ criterion = kornia.losses.LovaszSoftmaxLoss()+ assert criterion(logits, labels) is not None++ def test_binary(self, device, dtype):+ num_classes = 1+ logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)+ labels = torch.rand(2, 3, 2) * num_classes+ labels = labels.to(device).long()++ criterion = kornia.losses.LovaszSoftmaxLoss()+ with pytest.raises(Exception):+ criterion(logits, labels)++ def test_all_ones(self, device, dtype):+ num_classes = 2+ # make perfect prediction+ # note that softmax(prediction[:, 1]) == 1. softmax(prediction[:, 0]) == 0.+ prediction = torch.zeros(2, num_classes, 1, 2, device=device, dtype=dtype)+ prediction[:, 1] = 100.+ labels = torch.ones(2, 1, 2, device=device, dtype=torch.int64)++ criterion = kornia.losses.LovaszSoftmaxLoss()+ loss = criterion(prediction, labels)+ print(loss)+ assert_close(loss, torch.zeros_like(loss), rtol=1e-3, atol=1e-3)++ def test_gradcheck(self, device, dtype):+ num_classes = 4+ logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)+ labels = torch.rand(2, 3, 2) * num_classes+ labels = labels.to(device).long()++ logits = utils.tensor_to_gradcheck_var(logits) # to var+ assert gradcheck(kornia.losses.lovasz_softmax_loss, (logits, labels), raise_exception=True)++ def test_jit(self, device, dtype):+ num_classes = 6+ logits = torch.rand(2, num_classes, 1, 2, device=device, dtype=dtype)+ labels = torch.rand(2, 1, 2) * num_classes+ labels = labels.to(device).long()++ op = kornia.losses.lovasz_softmax_loss+ op_script = torch.jit.script(op)++ assert_close(op(logits, labels), op_script(logits, labels))++ def test_module(self, device, dtype):+ num_classes = 5+ logits = torch.rand(2, num_classes, 1, 2, device=device, dtype=dtype)+ labels = torch.rand(2, 1, 2) * num_classes+ labels = labels.to(device).long()++ op = kornia.losses.lovasz_softmax_loss+ op_module = kornia.losses.LovaszSoftmaxLoss()++ assert_close(op(logits, labels), op_module(logits, labels))