🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Focal loss flat (#393)
Dmytro Mishkin74f0be18e227
diff --git a/kornia/losses/focal.py b/kornia/losses/focal.pyindex 67bd6f05c..b3e613572 100644--- a/kornia/losses/focal.py+++ b/kornia/losses/focal.py@@ -25,13 +25,19 @@ def focal_loss(raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))- if not len(input.shape) == 4:- raise ValueError("Invalid input shape, we expect BxNxHxW. Got: {}"+ if not len(input.shape) >= 2:+ raise ValueError("Invalid input shape, we expect BxCx*. Got: {}".format(input.shape))- if not input.shape[-2:] == target.shape[-2:]:- raise ValueError("input and target shapes must be the same. Got: {}"- .format(input.shape, input.shape))+ if input.size(0) != target.size(0):+ raise ValueError('Expected input batch_size ({}) to match target batch_size ({}).'+ .format(input.size(0), target.size(0)))++ n = input.size(0)+ out_size = (n,) + input.size()[2:]+ if target.size()[1:] != input.size()[2:]:+ raise ValueError('Expected target size {}, got {}'.format(+ out_size, target.size()))if not input.device == target.device:raise ValueError(@@ -86,8 +92,8 @@ class FocalLoss(nn.Module):in the output, ‘sum’: the output will be summed. Default: ‘none’.Shape:- - Input: :math:`(N, C, H, W)` where C = number of classes.- - Target: :math:`(N, H, W)` where each value is+ - Input: :math:`(N, C, *)` where C = number of classes.+ - Target: :math:`(N, *)` where each value is:math:`0 ≤ targets[i] ≤ C−1`.Examples:diff --git a/kornia/utils/one_hot.py b/kornia/utils/one_hot.pyindex c2ba6acf5..2531166eb 100644--- a/kornia/utils/one_hot.py+++ b/kornia/utils/one_hot.py@@ -8,11 +8,11 @@ def one_hot(labels: torch.Tensor,device: Optional[torch.device] = None,dtype: Optional[torch.dtype] = None,eps: Optional[float] = 1e-6) -> torch.Tensor:- r"""Converts an integer label 2D tensor to a one-hot 3D tensor.+ r"""Converts an integer label x-D tensor to a one-hot (x+1)-D tensor.Args:- labels (torch.Tensor) : tensor with labels of shape :math:`(N, H, W)`,- where N is batch siz. Each value is an integer+ labels (torch.Tensor) : tensor with labels of shape :math:`(N, *)`,+ where N is batch size. Each value is an integerrepresenting correct classification.num_classes (int): number of classes in labels.device (Optional[torch.device]): the desired device of returned tensor.@@ -23,7 +23,7 @@ def one_hot(labels: torch.Tensor,tensor. Default: if None, infers data type from values.Returns:- torch.Tensor: the labels in one hot tensor.+ torch.Tensor: the labels in one hot tensor of shape :math:`(N, C, *)`,Examples::>>> labels = torch.LongTensor([[[0, 1], [2, 0]]])@@ -38,9 +38,6 @@ def one_hot(labels: torch.Tensor,if not torch.is_tensor(labels):raise TypeError("Input labels type is not a torch.Tensor. Got {}".format(type(labels)))- if not len(labels.shape) == 3:- raise ValueError("Invalid depth shape, we expect BxHxW. Got: {}"- .format(labels.shape))if not labels.dtype == torch.int64:raise ValueError("labels must be of the same dtype torch.int64. Got: {}" .format(@@ -48,7 +45,7 @@ def one_hot(labels: torch.Tensor,if num_classes < 1:raise ValueError("The number of classes must be bigger than one."" Got: {}".format(num_classes))- batch_size, height, width = labels.shape- one_hot = torch.zeros(batch_size, num_classes, height, width,+ shape = labels.shape+ one_hot = torch.zeros(shape[0], num_classes, *shape[1:],device=device, dtype=dtype)return one_hot.scatter_(1, labels.unsqueeze(1), 1.0) + epsdiff --git a/test/test_losses.py b/test/test_losses.pyindex ef44d58f6..ca98cbbbc 100644--- a/test/test_losses.py+++ b/test/test_losses.py@@ -45,6 +45,17 @@ class TestFocalLoss:).shape == ())+ def test_smoke_mean_flat(self, device):+ num_classes = 3+ logits = torch.rand(2, num_classes).to(device)+ labels = torch.rand(2) * num_classes+ labels = labels.to(device).long()+ assert (+ kornia.losses.focal_loss(+ logits, labels, alpha=0.5, gamma=2.0, reduction="mean"+ ).shape == ()+ )+# TODO: implement medef test_jit(self, device):pass