🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Improve focal loss for numerical stability (#1362)
Michał Tyszkiewiczb8f34116342b
diff --git a/kornia/losses/focal.py b/kornia/losses/focal.pyindex 78af5bf39..a4dd344d6 100644--- a/kornia/losses/focal.py+++ b/kornia/losses/focal.py@@ -1,3 +1,6 @@+import warnings+from typing import Optional+import torchimport torch.nn as nnimport torch.nn.functional as F@@ -14,7 +17,7 @@ def focal_loss(alpha: float,gamma: float = 2.0,reduction: str = 'none',- eps: float = 1e-8,+ eps: Optional[float] = None,) -> torch.Tensor:r"""Criterion that computes Focal loss.@@ -37,7 +40,7 @@ def focal_loss(will be applied, ``'mean'``: the sum of the output will be divided bythe number of elements in the output, ``'sum'``: the output will besummed.- eps: Scalar to enforce numerical stabiliy.+ eps: Deprecated: scalar to enforce numerical stabiliy. This is no longer used.Return:the computed loss.@@ -49,6 +52,14 @@ def focal_loss(>>> output = focal_loss(input, target, alpha=0.5, gamma=2.0, reduction='mean')>>> output.backward()"""+ if eps is not None and not torch.jit.is_scripting():+ warnings.warn(+ "`focal_loss` has been reworked for improved numerical stability "+ "and the `eps` argument is no longer necessary",+ DeprecationWarning,+ stacklevel=2,+ )+if not isinstance(input, torch.Tensor):raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")@@ -67,7 +78,8 @@ def focal_loss(raise ValueError(f"input and target must be in the same device. Got: {input.device} and {target.device}")# compute softmax over the classes axis- input_soft: torch.Tensor = F.softmax(input, dim=1) + eps+ input_soft: torch.Tensor = F.softmax(input, dim=1)+ log_input_soft: torch.Tensor = F.log_softmax(input, dim=1)# create the labels one hot tensortarget_one_hot: torch.Tensor = one_hot(target, num_classes=input.shape[1], device=input.device, dtype=input.dtype)@@ -75,8 +87,8 @@ def focal_loss(# compute the actual focal lossweight = torch.pow(-input_soft + 1.0, gamma)- focal = -alpha * weight * torch.log(input_soft)- loss_tmp = torch.sum(target_one_hot * focal, dim=1)+ focal = -alpha * weight * log_input_soft+ loss_tmp = torch.einsum('bc...,bc...->b...', (target_one_hot, focal))if reduction == 'none':loss = loss_tmp@@ -109,7 +121,8 @@ class FocalLoss(nn.Module):will be applied, ``'mean'``: the sum of the output will be divided bythe number of elements in the output, ``'sum'``: the output will besummed.- eps: Scalar to enforce numerical stabiliy.+ eps: Deprecated: scalar to enforce numerical stability. This is no longer+ used.Shape:- Input: :math:`(N, C, *)` where C = number of classes.@@ -126,12 +139,12 @@ class FocalLoss(nn.Module):>>> output.backward()"""- def __init__(self, alpha: float, gamma: float = 2.0, reduction: str = 'none', eps: float = 1e-8) -> None:+ def __init__(self, alpha: float, gamma: float = 2.0, reduction: str = 'none', eps: Optional[float] = None) -> None:super().__init__()self.alpha: float = alphaself.gamma: float = gammaself.reduction: str = reduction- self.eps: float = eps+ self.eps: Optional[float] = epsdef forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:return focal_loss(input, target, self.alpha, self.gamma, self.reduction, self.eps)@@ -143,7 +156,7 @@ def binary_focal_loss_with_logits(alpha: float = 0.25,gamma: float = 2.0,reduction: str = 'none',- eps: float = 1e-8,+ eps: Optional[float] = None,) -> torch.Tensor:r"""Function that computes Binary Focal loss.@@ -164,7 +177,7 @@ def binary_focal_loss_with_logits(will be applied, ``'mean'``: the sum of the output will be divided bythe number of elements in the output, ``'sum'``: the output will besummed.- eps: for numerically stability when dividing.+ eps: Deprecated: scalar for numerically stability when dividing. This is no longer used.Returns:the computed loss.@@ -174,9 +187,17 @@ def binary_focal_loss_with_logits(>>> 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)+ tensor(21.8725)"""+ if eps is not None and not torch.jit.is_scripting():+ warnings.warn(+ "`binary_focal_loss_with_logits` has been reworked for improved numerical stability "+ "and the `eps` argument is no longer necessary",+ DeprecationWarning,+ stacklevel=2,+ )+if not isinstance(input, torch.Tensor):raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")@@ -186,10 +207,11 @@ def binary_focal_loss_with_logits(if input.size(0) != target.size(0):raise ValueError(f'Expected input batch_size ({input.size(0)}) to match target batch_size ({target.size(0)}).')- probs = torch.sigmoid(input)- loss_tmp = -alpha * torch.pow((1.0 - probs + eps), gamma) * target * torch.log(probs + eps) - (+ probs_pos = torch.sigmoid(input)+ probs_neg = torch.sigmoid(-input)+ loss_tmp = -alpha * torch.pow(probs_neg, gamma) * target * F.logsigmoid(input) - (1 - alpha- ) * torch.pow(probs + eps, gamma) * (1.0 - target) * torch.log(1.0 - probs + eps)+ ) * torch.pow(probs_pos, gamma) * (1.0 - target) * F.logsigmoid(-input)if reduction == 'none':loss = loss_tmp@@ -224,15 +246,14 @@ class BinaryFocalLossWithLogits(nn.Module):summed.Shape:- - Input: :math:`(N, 1, *)`.- - Target: :math:`(N, 1, *)`.+ - Input: :math:`(N, *)`.+ - Target: :math:`(N, *)`.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)+ >>> input = torch.randn(1, 3, 5, requires_grad=True)+ >>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(2)>>> output = loss(input, target)>>> output.backward()"""@@ -242,7 +263,6 @@ class BinaryFocalLossWithLogits(nn.Module):self.alpha: float = alphaself.gamma: float = gammaself.reduction: str = reduction- self.eps: float = 1e-8def 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)+ return binary_focal_loss_with_logits(input, target, self.alpha, self.gamma, self.reduction)