Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Feat/dice loss averaging (#2264)

ViriAldi08d24c32ad6c
diff --git a/kornia/losses/dice.py b/kornia/losses/dice.py
index 11a5a8335..c494c9ee3 100644
--- a/kornia/losses/dice.py
+++ b/kornia/losses/dice.py
@@ -2,15 +2,17 @@ from __future__ import annotations
import torch
import torch.nn as nn
-import torch.nn.functional as F
+from kornia.core import Tensor
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR
from kornia.utils.one_hot import one_hot
# based on:
# https://github.com/kevinzakka/pytorch-goodies/blob/master/losses.py
+# https://github.com/Lightning-AI/metrics/blob/v0.11.3/src/torchmetrics/functional/classification/dice.py#L66-L207
-def dice_loss(input: torch.Tensor, target: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
+def dice_loss(input: Tensor, target: Tensor, average: str = "micro", eps: float = 1e-8) -> Tensor:
r"""Criterion that computes Sørensen-Dice Coefficient loss.
According to [1], we compute the Sørensen-Dice Coefficient as follows:
@@ -36,10 +38,14 @@ def dice_loss(input: torch.Tensor, target: torch.Tensor, eps: float = 1e-8) -> t
input: logits tensor with shape :math:`(N, C, H, W)` where C = number of classes.
labels: labels tensor with shape :math:`(N, H, W)` where each value
is :math:`0 ≤ targets[i] ≤ C−1`.
+ average:
+ Reduction applied in multi-class scenario:
+ - ``'micro'`` [default]: Calculate the loss across all classes.
+ - ``'macro'``: Calculate the loss for each class separately and average the metrics across classes.
eps: Scalar to enforce numerical stabiliy.
Return:
- the computed loss.
+ One-element tensor of the computed loss.
Example:
>>> N = 5 # num_classes
@@ -48,8 +54,7 @@ def dice_loss(input: torch.Tensor, target: torch.Tensor, eps: float = 1e-8) -> t
>>> output = dice_loss(input, target)
>>> output.backward()
"""
- if not isinstance(input, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
+ KORNIA_CHECK_IS_TENSOR(input)
if not len(input.shape) == 4:
raise ValueError(f"Invalid input shape, we expect BxNxHxW. Got: {input.shape}")
@@ -60,20 +65,31 @@ def dice_loss(input: torch.Tensor, target: torch.Tensor, eps: float = 1e-8) -> t
if not input.device == target.device:
raise ValueError(f"input and target must be in the same device. Got: {input.device} and {target.device}")
+ possible_average = {"micro", "macro"}
+ KORNIA_CHECK(average in possible_average, f"The `average` has to be one of {possible_average}. Got: {average}")
+
# compute softmax over the classes axis
- input_soft: torch.Tensor = F.softmax(input, dim=1)
+ input_soft: Tensor = input.softmax(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)
+ target_one_hot: Tensor = one_hot(target, num_classes=input.shape[1], device=input.device, dtype=input.dtype)
+
+ # set dimensions for the appropriate averaging
+ dims: tuple[int, ...] = (2, 3)
+ if average == "micro":
+ dims = (1,) + dims
# 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.0 * intersection / (cardinality + eps)
+ dice_loss = -dice_score + 1.0
+
+ # reduce the loss across samples (and classes in case of `macro` averaging)
+ dice_loss = torch.mean(dice_loss)
- return torch.mean(-dice_score + 1.0)
+ return dice_loss
class DiceLoss(nn.Module):
@@ -99,6 +115,10 @@ class DiceLoss(nn.Module):
[1] https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient
Args:
+ average:
+ Reduction applied in multi-class scenario:
+ - ``'micro'`` [default]: Calculate the loss across all classes.
+ - ``'macro'``: Calculate the loss for each class separately and average the metrics across classes.
eps: Scalar to enforce numerical stabiliy.
Shape:
@@ -115,9 +135,10 @@ class DiceLoss(nn.Module):
>>> output.backward()
"""
- def __init__(self, eps: float = 1e-8) -> None:
+ def __init__(self, average: str = "micro", eps: float = 1e-8) -> None:
super().__init__()
- self.eps: float = eps
+ self.average = average
+ self.eps = eps
- def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
- return dice_loss(input, target, self.eps)
+ def forward(self, input: Tensor, target: Tensor) -> Tensor:
+ return dice_loss(input, target, self.average, self.eps)
diff --git a/test/losses/test_losses.py b/test/losses/test_losses.py
index 458924ba2..ef71f9990 100644
--- a/test/losses/test_losses.py
+++ b/test/losses/test_losses.py
@@ -264,6 +264,59 @@ class TestDiceLoss:
loss = criterion(logits, labels)
assert_close(loss, torch.zeros_like(loss), rtol=1e-3, atol=1e-3)
+ def test_averaging_micro(self, device, dtype):
+ num_classes = 2
+ eps = 1e-8
+
+ logits = torch.zeros(1, num_classes, 4, 1, device=device, dtype=dtype)
+ logits[:, 0, 0:3] = 10.0
+ logits[:, 0, 3:4] = 1.0
+ logits[:, 1, 0:3] = 1.0
+ logits[:, 1, 3:4] = 10.0
+
+ labels = torch.zeros(2, 4, 1, device=device, dtype=torch.int64)
+
+ exp_1_0 = torch.exp(torch.tensor([1.0], device=device, dtype=dtype))
+ exp_10_0 = torch.exp(torch.tensor([10.0], device=device, dtype=dtype))
+
+ expected_intersection = (3.0 * exp_10_0 + 1.0 * exp_1_0) / (exp_1_0 + exp_10_0)
+ expected_cardinality = 8.0 # for micro averaging cardinality is equal 2 * H * W
+ expected_loss = 1.0 - 2.0 * expected_intersection / (expected_cardinality + eps)
+ expected_loss = expected_loss.squeeze()
+
+ criterion = kornia.losses.DiceLoss(average="micro", eps=eps)
+ loss = criterion(logits, labels)
+ assert_close(loss, expected_loss, rtol=1e-3, atol=1e-3)
+
+ def test_averaging_macro(self, device, dtype):
+ num_classes = 2
+ eps = 1e-8
+
+ logits = torch.zeros(1, num_classes, 4, 1, device=device, dtype=dtype)
+ logits[:, 0, 0:3] = 10.0
+ logits[:, 0, 3:4] = 1.0
+ logits[:, 1, 0:3] = 1.0
+ logits[:, 1, 3:4] = 10.0
+
+ labels = torch.zeros(2, 4, 1, device=device, dtype=torch.int64)
+
+ exp_1_0 = torch.exp(torch.tensor([1.0], device=device, dtype=dtype))
+ exp_10_0 = torch.exp(torch.tensor([10.0], device=device, dtype=dtype))
+
+ expected_intersection_1 = (3.0 * exp_10_0 + exp_1_0) / (exp_1_0 + exp_10_0)
+ expected_intersection_2 = 0.0 # all labels are 0 so the intersection for the second class is empty
+ expected_cardinality_1 = 4.0 + (3.0 * exp_10_0 + 1.0 * exp_1_0) / (exp_1_0 + exp_10_0)
+ expected_cardinality_2 = 0.0 + (1.0 * exp_10_0 + 3.0 * exp_1_0) / (exp_1_0 + exp_10_0)
+
+ expected_loss_1 = 1.0 - 2.0 * expected_intersection_1 / (expected_cardinality_1 + eps)
+ expected_loss_2 = 1.0 - 2.0 * expected_intersection_2 / (expected_cardinality_2 + eps)
+ expected_loss = (expected_loss_1 + expected_loss_2) / 2.0
+ expected_loss = expected_loss.squeeze()
+
+ criterion = kornia.losses.DiceLoss(average="macro", eps=eps)
+ loss = criterion(logits, labels)
+ assert_close(loss, expected_loss, rtol=1e-3, atol=1e-3)
+
def test_gradcheck(self, device, dtype):
num_classes = 3
logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)