Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

refactor dice loss and add gpu test

edgarriba53a0a4be9e70
diff --git a/kornia/losses/dice.py b/kornia/losses/dice.py
index 01bc7d015..9463dc8a2 100644
--- a/kornia/losses/dice.py
+++ b/kornia/losses/dice.py
@@ -10,6 +10,45 @@ from kornia.utils import one_hot
# based on:
# https://github.com/kevinzakka/pytorch-goodies/blob/master/losses.py
+def dice_loss(input: torch.Tensor, target: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
+ r"""Function that computes Sørensen-Dice Coefficient loss.
+
+ See :class:`~kornia.losses.DiceLoss` for details.
+ """
+ if not torch.is_tensor(input):
+ 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: {}"
+ .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 not input.device == target.device:
+ raise ValueError(
+ "input and target must be in the same device. Got: {}" .format(
+ input.device, target.device))
+
+ # compute softmax over the classes axis
+ input_soft: torch.Tensor = F.softmax(input, dim=1)
+
+ # create the labels one hot tensor
+ target_one_hot: torch.Tensor = one_hot(
+ target, num_classes=input.shape[1],
+ device=input.device, dtype=input.dtype)
+
+ # compute the actual dice score
+ dims = (1, 2, 3)
+ intersection = torch.sum(input_soft * target_one_hot, dims)
+ cardinality = torch.sum(input_soft + target_one_hot, dims)
+
+ dice_score = 2. * intersection / (cardinality + eps)
+ return torch.mean(1. - dice_score)
+
+
class DiceLoss(nn.Module):
r"""Criterion that computes Sørensen-Dice Coefficient loss.
@@ -53,45 +92,4 @@ class DiceLoss(nn.Module):
self,
input: torch.Tensor,
target: torch.Tensor) -> torch.Tensor:
- if not torch.is_tensor(input):
- 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: {}"
- .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 not input.device == target.device:
- raise ValueError(
- "input and target must be in the same device. Got: {}" .format(
- input.device, target.device))
- # compute softmax over the classes axis
- input_soft = F.softmax(input, dim=1)
-
- # create the labels one hot tensor
- target_one_hot = one_hot(target, num_classes=input.shape[1],
- device=input.device, dtype=input.dtype)
-
- # compute the actual dice score
- dims = (1, 2, 3)
- intersection = torch.sum(input_soft * target_one_hot, dims)
- cardinality = torch.sum(input_soft + target_one_hot, dims)
-
- dice_score = 2. * intersection / (cardinality + self.eps)
- return torch.mean(torch.tensor(1.) - dice_score)
-
-
-######################
-# functional interface
-######################
-
-
-def dice_loss(
- input: torch.Tensor,
- target: torch.Tensor) -> torch.Tensor:
- r"""Function that computes Sørensen-Dice Coefficient loss.
-
- See :class:`~kornia.losses.DiceLoss` for details.
- """
- return DiceLoss()(input, target)
+ return dice_loss(input, target)
diff --git a/test/test_losses.py b/test/test_losses.py
index 97cac9893..5db15a795 100644
--- a/test/test_losses.py
+++ b/test/test_losses.py
@@ -106,36 +106,36 @@ class TestTverskyLoss:
class TestDiceLoss:
- def test_smoke(self):
+ def test_smoke(self, device):
num_classes = 3
- logits = torch.rand(2, num_classes, 3, 2)
+ logits = torch.rand(2, num_classes, 3, 2).to(device)
labels = torch.rand(2, 3, 2) * num_classes
- labels = labels.long()
+ labels = labels.to(device).long()
criterion = kornia.losses.DiceLoss()
loss = criterion(logits, labels)
- def test_all_zeros(self):
+ def test_all_zeros(self, device):
num_classes = 3
- logits = torch.zeros(2, num_classes, 1, 2)
+ logits = torch.zeros(2, num_classes, 1, 2).to(device)
logits[:, 0] = 10.0
logits[:, 1] = 1.0
logits[:, 2] = 1.0
- labels = torch.zeros(2, 1, 2, dtype=torch.int64)
+ labels = torch.zeros(2, 1, 2, dtype=torch.int64).to(device)
criterion = kornia.losses.DiceLoss()
loss = criterion(logits, labels)
assert pytest.approx(loss.item(), 0.0)
# TODO: implement me
- def test_jit(self):
+ def test_jit(self, device):
pass
- def test_gradcheck(self):
+ def test_gradcheck(self, device):
num_classes = 3
- logits = torch.rand(2, num_classes, 3, 2)
+ logits = torch.rand(2, num_classes, 3, 2).to(device)
labels = torch.rand(2, 3, 2) * num_classes
- labels = labels.long()
+ labels = labels.to(device).long()
logits = utils.tensor_to_gradcheck_var(logits) # to var
assert gradcheck(