🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[Feat] Binary focal loss (#830)
xen0f0n47633e3efe1f
diff --git a/kornia/losses/__init__.py b/kornia/losses/__init__.pyindex 3a55dcdee..07633b7d3 100644--- a/kornia/losses/__init__.py+++ b/kornia/losses/__init__.py@@ -1,7 +1,7 @@from .ssim import SSIM, ssimfrom .dice import DiceLoss, dice_lossfrom .tversky import TverskyLoss, tversky_loss-from .focal import FocalLoss, focal_loss+from .focal import FocalLoss, focal_loss, BinaryFocalLossWithLogits, binary_focal_loss_with_logitsfrom .depth_smooth import (InverseDepthSmoothnessLoss, inverse_depth_smoothness_loss)diff --git a/kornia/losses/focal.py b/kornia/losses/focal.pyindex 977b18d96..889572e6d 100644--- a/kornia/losses/focal.py+++ b/kornia/losses/focal.py@@ -122,3 +122,117 @@ class FocalLoss(nn.Module):input: torch.Tensor,target: torch.Tensor) -> torch.Tensor:return focal_loss(input, target, self.alpha, self.gamma, self.reduction, self.eps)+++def binary_focal_loss_with_logits(+ inp: torch.Tensor,+ target: torch.Tensor,+ alpha: float = .25,+ gamma: float = 2.0,+ reduction: str = 'none',+ eps: float = 1e-8) -> torch.Tensor:+ r"""Function that computes Binary Focal loss.++ args:+ inp (torch.Tensor) : input data tensor+ target (torch.Tensor): the target tensor+ alpha (float): Weighting factor for the rare class :math:`\alpha \in [0, 1]`. Default: 0.25.+ gamma (float): Focusing parameter :math:`\gamma >= 0`. Default: 2.0.+ reduction (str, optional): Specifies the reduction to apply to the. Default: 'none'.+ eps (float): for numerically stability when dividing. Default: 1e-8.++ returns:+ torch.tensor: loss++ Examples:+ >>> num_classes = 1+ >>> kwargs = {"alpha": 0.25, "gamma": 2.0, "reduction": 'mean'}+ >>> logits = torch.tensor([[[[6.325]]],[[[5.26]]],[[[87.49]]]])+ >>> labels = torch.tensor([[[1.]],[[1.]],[[0.]]])+ >>> binary_focal_loss_with_logits(logits, labels, **kwargs)+ tensor(4.6052)+ """++ if not isinstance(inp, torch.Tensor):+ raise TypeError("Input type is not a torch.Tensor. Got {}"+ .format(type(inp)))++ if not len(inp.shape) >= 2:+ raise ValueError("Invalid input shape, we expect BxCx*. Got: {}"+ .format(inp.shape))++ if inp.size(0) != target.size(0):+ raise ValueError('Expected input batch_size ({}) to match target batch_size ({}).'+ .format(inp.size(0), target.size(0)))++ if not inp.device == target.device:+ raise ValueError(+ "input and target must be in the same device. Got: {} and {}".format(+ inp.device, target.device))++ probs = torch.sigmoid(inp)+ target = target.unsqueeze(dim=1)+ loss_tmp = -alpha * torch.pow((1. - probs), gamma) * target * torch.log(probs + eps) \+ - (1 - alpha) * torch.pow(probs, gamma) * (1. - target) * torch.log(1. - probs + eps)+ loss_tmp = loss_tmp.squeeze(dim=1)++ if reduction == 'none':+ loss = loss_tmp+ elif reduction == 'mean':+ loss = torch.mean(loss_tmp)+ elif reduction == 'sum':+ loss = torch.sum(loss_tmp)+ else:+ raise NotImplementedError("Invalid reduction mode: {}"+ .format(reduction))+ return loss+++class BinaryFocalLossWithLogits(nn.Module):+ r"""Criterion that computes Focal loss.++ According to :cite:`lin2017focal`, the Focal loss is computed as follows:++ .. math::++ \text{FL}(p_t) = -\alpha_t (1 - p_t)^{\gamma} \, \text{log}(p_t)++ where:+ - :math:`p_t` is the model's estimated probability for each class.+++ Arguments:+ alpha (float): Weighting factor for the rare class :math:`\alpha \in [0, 1]`.+ gamma (float): Focusing parameter :math:`\gamma >= 0`.+ reduction (str, optional): 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. Default: ‘none’.++ Shape:+ - Input: :math:`(N, 1, *)`+ - Target: :math:`(N, 1, *)`++ Examples:+ >>> N = 1 # num_classes+ >>> kwargs = {"alpha": 0.25, "gamma": 2.0, "reduction": 'mean'}+ >>> loss = BinaryFocalLossWithLogits(**kwargs)+ >>> input = torch.randn(1, N, 3, 5, requires_grad=True)+ >>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)+ >>> output = loss(input, target)+ >>> output.backward()+ """++ def __init__(self, alpha: float, gamma: float = 2.0,+ reduction: str = 'none') -> None:+ super(BinaryFocalLossWithLogits, self).__init__()+ self.alpha: float = alpha+ self.gamma: float = gamma+ self.reduction: str = reduction+ self.eps: float = 1e-8++ def forward(+ self,+ input: torch.Tensor,+ target: torch.Tensor) -> torch.Tensor:+ return binary_focal_loss_with_logits(input, target, self.alpha, self.gamma, self.reduction, self.eps)diff --git a/test/test_losses.py b/test/test_losses.pyindex 5890ee705..db3ff7687 100644--- a/test/test_losses.py+++ b/test/test_losses.py@@ -9,6 +9,85 @@ from torch.autograd import gradcheckfrom torch.testing import assert_allclose+class TestBinaryFocalLossWithLogits:+ def test_smoke_none(self, device, dtype):+ num_classes = 1+ logits = torch.rand(2, num_classes, 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="none"+ ).shape == (2, 3, 2)++ def test_smoke_sum(self, device, dtype):+ num_classes = 1+ logits = torch.rand(2, num_classes, 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 == ()+ )++ def test_smoke_mean(self, device, dtype):+ num_classes = 1+ logits = torch.rand(2, num_classes, 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 == ()+ )++ def test_smoke_mean_flat(self, device, dtype):+ num_classes = 1+ logits = torch.rand(2, num_classes, 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 == ()+ )++ def test_jit(self, device, dtype):+ num_classes = 1+ logits = torch.rand(2, num_classes, 3, 2, dtype=dtype, device=device)+ labels = torch.rand(2, 3, 2, dtype=dtype, device=device)++ op = kornia.losses.binary_focal_loss_with_logits+ op_script = torch.jit.script(op)+ actual = op_script(logits, labels, alpha=0.5, gamma=2.0, reduction="none")+ expected = op(logits, labels, alpha=0.5, gamma=2.0, reduction="none")+ assert_allclose(actual, expected)++ def test_gradcheck(self, device):+ num_classes = 1+ alpha, gamma = 0.5, 2.0 # for focal loss with logits+ logits = torch.rand(2, num_classes, 3, 2).to(device)+ labels = torch.rand(2, 1, 3, 2) * num_classes+ labels = labels.to(device).long()++ logits = utils.tensor_to_gradcheck_var(logits) # to var+ assert gradcheck(+ kornia.losses.binary_focal_loss_with_logits,+ (logits, labels, alpha, gamma),+ raise_exception=True,+ )++ def test_same_output(self, device, dtype):+ num_classes = 1+ logits = torch.rand(2, num_classes, 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'}++ assert kornia.losses.binary_focal_loss_with_logits(logits, labels, **kwargs) == \+ kornia.losses.BinaryFocalLossWithLogits(**kwargs)(logits, labels)++class TestFocalLoss:def test_smoke_none(self, device):num_classes = 3