Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Add ignore_index to dice, focal and tversky loss (#3034)

Tillmann Falck9aa8c7f69c25
diff --git a/kornia/losses/_utils.py b/kornia/losses/_utils.py
new file mode 100644
index 000000000..2e78df19e
--- /dev/null
+++ b/kornia/losses/_utils.py
@@ -0,0 +1,23 @@
+from __future__ import annotations
+
+from typing import Optional
+
+import torch
+
+
+def mask_ignore_pixels(
+ target: torch.Tensor, ignore_index: Optional[int]
+) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
+ if ignore_index is None:
+ return target, None
+
+ target_mask = target != ignore_index
+
+ if target_mask.all():
+ return target, None
+
+ # map invalid pixels to a valid class (0)
+ # they need to be manually excluded from the loss computation after
+ target = target.where(target_mask, target.new_zeros(1))
+
+ return target, target_mask
diff --git a/kornia/losses/dice.py b/kornia/losses/dice.py
index 0dcbcc2b0..63f49612e 100644
--- a/kornia/losses/dice.py
+++ b/kornia/losses/dice.py
@@ -7,6 +7,7 @@ from torch import nn
from kornia.core import Tensor
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR
+from kornia.losses._utils import mask_ignore_pixels
from kornia.utils.one_hot import one_hot
# based on:
@@ -15,7 +16,12 @@ from kornia.utils.one_hot import one_hot
def dice_loss(
- pred: Tensor, target: Tensor, average: str = "micro", eps: float = 1e-8, weight: Optional[Tensor] = None
+ pred: Tensor,
+ target: Tensor,
+ average: str = "micro",
+ eps: float = 1e-8,
+ weight: Optional[Tensor] = None,
+ ignore_index: Optional[int] = -100,
) -> Tensor:
r"""Criterion that computes Sørensen-Dice Coefficient loss.
@@ -48,6 +54,7 @@ def dice_loss(
- ``'macro'``: Calculate the loss for each class separately and average the metrics across classes.
eps: Scalar to enforce numerical stabiliy.
weight: weights for classes with shape :math:`(num\_of\_classes,)`.
+ ignore_index: labels with this value are ignored in the loss computation.
Return:
One-element tensor of the computed loss.
@@ -76,9 +83,17 @@ def dice_loss(
# compute softmax over the classes axis
pred_soft: Tensor = pred.softmax(dim=1)
+ target, target_mask = mask_ignore_pixels(target, ignore_index)
+
# create the labels one hot tensor
target_one_hot: Tensor = one_hot(target, num_classes=pred.shape[1], device=pred.device, dtype=pred.dtype)
+ # mask ignore pixels
+ if target_mask is not None:
+ target_mask.unsqueeze_(1)
+ target_one_hot = target_one_hot * target_mask
+ pred_soft = pred_soft * target_mask
+
# compute the actual dice score
if weight is not None:
KORNIA_CHECK_IS_TENSOR(weight, "weight must be Tensor or None.")
@@ -147,6 +162,7 @@ class DiceLoss(nn.Module):
- ``'macro'``: Calculate the loss for each class separately and average the metrics across classes.
eps: Scalar to enforce numerical stabiliy.
weight: weights for classes with shape :math:`(num\_of\_classes,)`.
+ ignore_index: labels with this value are ignored in the loss computation.
Shape:
- Pred: :math:`(N, C, H, W)` where C = number of classes.
@@ -162,11 +178,18 @@ class DiceLoss(nn.Module):
>>> output.backward()
"""
- def __init__(self, average: str = "micro", eps: float = 1e-8, weight: Optional[Tensor] = None) -> None:
+ def __init__(
+ self,
+ average: str = "micro",
+ eps: float = 1e-8,
+ weight: Optional[Tensor] = None,
+ ignore_index: Optional[int] = -100,
+ ) -> None:
super().__init__()
self.average = average
self.eps = eps
self.weight = weight
+ self.ignore_index = ignore_index
def forward(self, pred: Tensor, target: Tensor) -> Tensor:
- return dice_loss(pred, target, self.average, self.eps, self.weight)
+ return dice_loss(pred, target, self.average, self.eps, self.weight, self.ignore_index)
diff --git a/kornia/losses/focal.py b/kornia/losses/focal.py
index 1a5813dd6..d73f02b55 100644
--- a/kornia/losses/focal.py
+++ b/kornia/losses/focal.py
@@ -7,6 +7,7 @@ from torch import nn
from kornia.core import Tensor, tensor
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+from kornia.losses._utils import mask_ignore_pixels
from kornia.utils.one_hot import one_hot
# based on:
@@ -20,6 +21,7 @@ def focal_loss(
gamma: float = 2.0,
reduction: str = "none",
weight: Optional[Tensor] = None,
+ ignore_index: Optional[int] = -100,
) -> Tensor:
r"""Criterion that computes Focal loss.
@@ -44,6 +46,7 @@ def focal_loss(
the number of elements in the output, ``'sum'``: the output will be
summed.
weight: weights for classes with shape :math:`(num\_of\_classes,)`.
+ ignore_index: labels with this value are ignored in the loss computation.
Return:
the computed loss.
@@ -68,9 +71,16 @@ def focal_loss(
f"pred and target must be in the same device. Got: {pred.device} and {target.device}",
)
+ target, target_mask = mask_ignore_pixels(target, ignore_index)
+
# create the labels one hot tensor
target_one_hot: Tensor = one_hot(target, num_classes=pred.shape[1], device=pred.device, dtype=pred.dtype)
+ # mask ignore pixels
+ if target_mask is not None:
+ target_mask.unsqueeze_(1)
+ target_one_hot = target_one_hot * target_mask
+
# compute softmax over the classes axis
log_pred_soft: Tensor = pred.log_softmax(1)
@@ -130,6 +140,7 @@ class FocalLoss(nn.Module):
the number of elements in the output, ``'sum'``: the output will be
summed.
weight: weights for classes with shape :math:`(num\_of\_classes,)`.
+ ignore_index: labels with this value are ignored in the loss computation.
Shape:
- Pred: :math:`(N, C, *)` where C = number of classes.
@@ -147,16 +158,22 @@ class FocalLoss(nn.Module):
"""
def __init__(
- self, alpha: Optional[float], gamma: float = 2.0, reduction: str = "none", weight: Optional[Tensor] = None
+ self,
+ alpha: Optional[float],
+ gamma: float = 2.0,
+ reduction: str = "none",
+ weight: Optional[Tensor] = None,
+ ignore_index: Optional[int] = -100,
) -> None:
super().__init__()
self.alpha: Optional[float] = alpha
self.gamma: float = gamma
self.reduction: str = reduction
self.weight: Optional[Tensor] = weight
+ self.ignore_index: Optional[int] = ignore_index
def forward(self, pred: Tensor, target: Tensor) -> Tensor:
- return focal_loss(pred, target, self.alpha, self.gamma, self.reduction, self.weight)
+ return focal_loss(pred, target, self.alpha, self.gamma, self.reduction, self.weight, self.ignore_index)
def binary_focal_loss_with_logits(
@@ -167,6 +184,7 @@ def binary_focal_loss_with_logits(
reduction: str = "none",
pos_weight: Optional[Tensor] = None,
weight: Optional[Tensor] = None,
+ ignore_index: Optional[int] = -100,
) -> Tensor:
r"""Criterion that computes Binary Focal loss.
@@ -193,6 +211,7 @@ def binary_focal_loss_with_logits(
pos_weight: a weight of positive examples with shape :math:`(num\_of\_classes,)`.
It is possible to trade off recall and precision by adding weights to positive examples.
weight: weights for classes with shape :math:`(num\_of\_classes,)`.
+ ignore_index: labels with this value are ignored in the loss computation.
Returns:
the computed loss.
@@ -216,6 +235,13 @@ def binary_focal_loss_with_logits(
log_probs_pos: Tensor = nn.functional.logsigmoid(pred)
log_probs_neg: Tensor = nn.functional.logsigmoid(-pred)
+ target, target_mask = mask_ignore_pixels(target, ignore_index)
+
+ if target_mask is not None:
+ # mask ignore pixels
+ log_probs_neg = log_probs_neg * target_mask
+ log_probs_pos = log_probs_pos * target_mask
+
pos_term: Tensor = -log_probs_neg.exp().pow(gamma) * target * log_probs_pos
neg_term: Tensor = -log_probs_pos.exp().pow(gamma) * (1.0 - target) * log_probs_neg
if alpha is not None:
@@ -287,6 +313,7 @@ class BinaryFocalLossWithLogits(nn.Module):
pos_weight: a weight of positive examples with shape :math:`(num\_of\_classes,)`.
It is possible to trade off recall and precision by adding weights to positive examples.
weight: weights for classes with shape :math:`(num\_of\_classes,)`.
+ ignore_index: labels with this value are ignored in the loss computation.
Shape:
- Pred: :math:`(N, C, *)` where C = number of classes.
@@ -310,6 +337,7 @@ class BinaryFocalLossWithLogits(nn.Module):
reduction: str = "none",
pos_weight: Optional[Tensor] = None,
weight: Optional[Tensor] = None,
+ ignore_index: Optional[int] = -100,
) -> None:
super().__init__()
self.alpha: Optional[float] = alpha
@@ -317,8 +345,9 @@ class BinaryFocalLossWithLogits(nn.Module):
self.reduction: str = reduction
self.pos_weight: Optional[Tensor] = pos_weight
self.weight: Optional[Tensor] = weight
+ self.ignore_index: Optional[int] = ignore_index
def forward(self, pred: Tensor, target: Tensor) -> Tensor:
return binary_focal_loss_with_logits(
- pred, target, self.alpha, self.gamma, self.reduction, self.pos_weight, self.weight
+ pred, target, self.alpha, self.gamma, self.reduction, self.pos_weight, self.weight, self.ignore_index
)
diff --git a/kornia/losses/tversky.py b/kornia/losses/tversky.py
index cfbbf56a8..8782c9ffd 100644
--- a/kornia/losses/tversky.py
+++ b/kornia/losses/tversky.py
@@ -1,9 +1,12 @@
from __future__ import annotations
+from typing import Optional
+
import torch
import torch.nn.functional as F
from torch import nn
+from kornia.losses._utils import mask_ignore_pixels
from kornia.utils.one_hot import one_hot
# based on:
@@ -11,7 +14,12 @@ from kornia.utils.one_hot import one_hot
def tversky_loss(
- pred: torch.Tensor, target: torch.Tensor, alpha: float, beta: float, eps: float = 1e-8
+ pred: torch.Tensor,
+ target: torch.Tensor,
+ alpha: float,
+ beta: float,
+ eps: float = 1e-8,
+ ignore_index: Optional[int] = -100,
) -> torch.Tensor:
r"""Criterion that computes Tversky Coefficient loss.
@@ -40,6 +48,7 @@ def tversky_loss(
alpha: the first coefficient in the denominator.
beta: the second coefficient in the denominator.
eps: scalar for numerical stability.
+ ignore_index: labels with this value are ignored in the loss computation.
Return:
the computed loss.
@@ -66,9 +75,17 @@ def tversky_loss(
# compute softmax over the classes axis
pred_soft: torch.Tensor = F.softmax(pred, dim=1)
+ target, target_mask = mask_ignore_pixels(target, ignore_index)
+
# create the labels one hot tensor
target_one_hot: torch.Tensor = one_hot(target, num_classes=pred.shape[1], device=pred.device, dtype=pred.dtype)
+ # mask ignore pixels
+ if target_mask is not None:
+ target_mask.unsqueeze_(1)
+ target_one_hot = target_one_hot * target_mask
+ pred_soft = pred_soft * target_mask
+
# compute the actual dice score
dims = (1, 2, 3)
intersection = torch.sum(pred_soft * target_one_hot, dims)
@@ -107,6 +124,7 @@ class TverskyLoss(nn.Module):
alpha: the first coefficient in the denominator.
beta: the second coefficient in the denominator.
eps: scalar for numerical stability.
+ ignore_index: labels with this value are ignored in the loss computation.
Shape:
- Pred: :math:`(N, C, H, W)` where C = number of classes.
@@ -122,11 +140,12 @@ class TverskyLoss(nn.Module):
>>> output.backward()
"""
- def __init__(self, alpha: float, beta: float, eps: float = 1e-8) -> None:
+ def __init__(self, alpha: float, beta: float, eps: float = 1e-8, ignore_index: Optional[int] = -100) -> None:
super().__init__()
self.alpha: float = alpha
self.beta: float = beta
self.eps: float = eps
+ self.ignore_index: Optional[int] = ignore_index
def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
- return tversky_loss(pred, target, self.alpha, self.beta, self.eps)
+ return tversky_loss(pred, target, self.alpha, self.beta, self.eps, self.ignore_index)
diff --git a/tests/losses/test_dice.py b/tests/losses/test_dice.py
index 5434c6954..43fdad979 100644
--- a/tests/losses/test_dice.py
+++ b/tests/losses/test_dice.py
@@ -16,7 +16,8 @@ class TestDiceLoss(BaseTester):
criterion = kornia.losses.DiceLoss()
assert criterion(logits, labels) is not None
- def test_all_zeros(self, device, dtype):
+ @pytest.mark.parametrize("ignore_index", [-100, None])
+ def test_all_zeros(self, device, dtype, ignore_index):
num_classes = 3
logits = torch.zeros(2, num_classes, 1, 2, device=device, dtype=dtype)
logits[:, 0] = 10.0
@@ -24,7 +25,7 @@ class TestDiceLoss(BaseTester):
logits[:, 2] = 1.0
labels = torch.zeros(2, 1, 2, device=device, dtype=torch.int64)
- criterion = kornia.losses.DiceLoss()
+ criterion = kornia.losses.DiceLoss(ignore_index=ignore_index)
loss = criterion(logits, labels)
self.assert_close(loss, torch.zeros_like(loss), rtol=1e-3, atol=1e-3)
@@ -160,10 +161,28 @@ class TestDiceLoss(BaseTester):
loss = criterion(logits, labels)
self.assert_close(loss, expected_loss, rtol=1e-3, atol=1e-3)
+ @pytest.mark.parametrize("ignore_index", [-100, 255])
+ def test_ignore_index(self, device, dtype, ignore_index):
+ num_classes = 2
+ eps = 1e-8
+
+ logits = torch.zeros(2, num_classes, 1, 4, device=device, dtype=dtype)
+ logits[:, 0, :, 0] = 100.0
+ logits[:, 1, :, 1:] = 100.0
+ labels = torch.zeros(2, 1, 4, device=device, dtype=torch.int64)
+
+ labels[..., 2:] = ignore_index
+ expected_loss = torch.tensor([1.0 / 2.0], device=device, dtype=dtype).squeeze()
+ criterion = kornia.losses.DiceLoss(average="micro", eps=eps, ignore_index=ignore_index)
+ loss = criterion(logits, labels)
+ self.assert_close(loss, expected_loss, rtol=1e-3, atol=1e-3)
+
def test_gradcheck(self, device):
num_classes = 3
logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=torch.float64)
labels = torch.randint(0, num_classes, (2, 3, 2), device=device)
+ ignore = torch.rand(2, 3, 2, device=device) > 0.8
+ labels[ignore] = -100
self.gradcheck(kornia.losses.dice_loss, (logits, labels), dtypes=[torch.float64, torch.int64])
def test_dynamo(self, device, dtype, torch_optimizer):
diff --git a/tests/losses/test_focal_loss.py b/tests/losses/test_focal_loss.py
index fe737e7dd..10deb88c3 100644
--- a/tests/losses/test_focal_loss.py
+++ b/tests/losses/test_focal_loss.py
@@ -9,12 +9,13 @@ from testing.base import BaseTester
class TestBinaryFocalLossWithLogits(BaseTester):
@pytest.mark.parametrize("reduction", ["none", "mean", "sum"])
- def test_value_same_as_torch_bce_loss(self, device, dtype, reduction):
+ @pytest.mark.parametrize("ignore_index", [-100, None])
+ def test_value_same_as_torch_bce_loss(self, device, dtype, reduction, ignore_index):
logits = torch.rand(2, 3, 2, dtype=dtype, device=device)
labels = torch.rand(2, 3, 2, dtype=dtype, device=device)
focal_equivalent_bce_loss = kornia.losses.binary_focal_loss_with_logits(
- logits, labels, alpha=None, gamma=0, reduction=reduction
+ logits, labels, alpha=None, gamma=0, reduction=reduction, ignore_index=ignore_index
)
torch_bce_loss = F.binary_cross_entropy_with_logits(logits, labels, reduction=reduction)
self.assert_close(focal_equivalent_bce_loss, torch_bce_loss)
@@ -63,6 +64,20 @@ class TestBinaryFocalLossWithLogits(BaseTester):
).shape
assert actual_shape == expected_shape
+ @pytest.mark.parametrize("reduction,expected_shape", [("none", (2, 3, 2)), ("mean", ()), ("sum", ())])
+ @pytest.mark.parametrize("ignore_index", [-100, 255])
+ def test_shape_ignore_index(self, device, dtype, reduction, expected_shape, ignore_index):
+ logits = torch.rand(2, 3, 2, dtype=dtype, device=device)
+ labels = torch.rand(2, 3, 2, dtype=dtype, device=device)
+
+ ignore = torch.rand(2, 3, 2, device=device) > 0.6
+ labels[ignore] = ignore_index
+
+ actual_shape = kornia.losses.binary_focal_loss_with_logits(
+ logits, labels, alpha=0.8, gamma=0.5, reduction=reduction, ignore_index=ignore_index
+ ).shape
+ assert actual_shape == expected_shape
+
def test_dynamo(self, device, dtype, torch_optimizer):
logits = torch.rand(2, 3, 2, dtype=dtype, device=device)
labels = torch.rand(2, 3, 2, dtype=dtype, device=device)
@@ -83,6 +98,16 @@ class TestBinaryFocalLossWithLogits(BaseTester):
op = kornia.losses.binary_focal_loss_with_logits
self.gradcheck(op, (logits, labels, *args))
+ def test_gradcheck_ignore_index(self, device):
+ logits = torch.rand(2, 3, 2, device=device, dtype=torch.float64)
+ labels = torch.rand(2, 3, 2, device=device, dtype=torch.float64)
+ ignore = torch.rand(2, 3, 2, device=device) > 0.8
+ labels[ignore] = -100
+
+ args = (0.25, 2.0)
+ op = kornia.losses.binary_focal_loss_with_logits
+ self.gradcheck(op, (logits, labels, *args), requires_grad=[True, False, False, False])
+
def test_module(self, device, dtype):
logits = torch.rand(2, 3, 2, dtype=dtype, device=device)
labels = torch.rand(2, 3, 2, dtype=dtype, device=device)
@@ -137,6 +162,44 @@ class TestFocalLoss(BaseTester):
).shape
assert actual_shape == expected_shape
+ @pytest.mark.parametrize("reduction,expected_shape", [("none", (2, 3, 3, 2)), ("mean", ()), ("sum", ())])
+ @pytest.mark.parametrize("ignore_index", [-100, 255])
+ def test_shape_ignore_index(self, device, dtype, reduction, expected_shape, ignore_index):
+ num_classes = 3
+ logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)
+ labels = torch.randint(num_classes, (2, 3, 2), device=device)
+
+ ignore = torch.rand(2, 3, 2, device=device) > 0.6
+ labels[ignore] = ignore_index
+
+ actual_shape = kornia.losses.focal_loss(
+ logits, labels, alpha=0.8, gamma=0.5, reduction=reduction, ignore_index=ignore_index
+ ).shape
+ assert actual_shape == expected_shape
+
+ @pytest.mark.parametrize("ignore_index", [-100, 255])
+ def test_value_ignore_index(self, device, dtype, ignore_index):
+ num_classes = 3
+ logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)
+ labels = torch.randint(num_classes, (2, 3, 2), device=device)
+
+ ignore = torch.rand(2, 3, 2, device=device) > 0.6
+ labels[ignore] = ignore_index
+
+ labels_extra_class = labels.clone()
+ labels_extra_class[ignore] = num_classes
+ logits_extra_class = torch.cat([logits, logits.new_full((2, 1, 3, 2), float("-inf"))], dim=1)
+
+ expected_values = kornia.losses.focal_loss(
+ logits_extra_class, labels_extra_class, alpha=0.8, gamma=0.5, reduction="none"
+ )[:, :-1, ...]
+
+ actual_values = kornia.losses.focal_loss(
+ logits, labels, alpha=0.8, gamma=0.5, reduction="none", ignore_index=ignore_index
+ )
+
+ self.assert_close(actual_values, expected_values)
+
def test_dynamo(self, device, dtype, torch_optimizer):
num_classes = 3
logits = torch.rand(2, num_classes, device=device, dtype=dtype)
@@ -154,6 +217,8 @@ class TestFocalLoss(BaseTester):
num_classes = 3
logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=torch.float64)
labels = torch.randint(num_classes, (2, 3, 2), device=device).long()
+ ignore = torch.rand(2, 3, 2, device=device) > 0.8
+ labels[ignore] = -100
self.gradcheck(
kornia.losses.focal_loss, (logits, labels, 0.25, 2.0), dtypes=[torch.float64, torch.int64, None, None]
diff --git a/tests/losses/test_tversky.py b/tests/losses/test_tversky.py
index 5cdc8b75a..274ad558e 100644
--- a/tests/losses/test_tversky.py
+++ b/tests/losses/test_tversky.py
@@ -35,7 +35,8 @@ class TestTverskyLoss(BaseTester):
criterion(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1, 1, device="meta"))
assert "pred and target must be in the same device. Got:" in str(errinfo)
- def test_all_zeros(self, device, dtype):
+ @pytest.mark.parametrize("ignore_index", [-100, None])
+ def test_all_zeros(self, device, dtype, ignore_index):
num_classes = 3
logits = torch.zeros(2, num_classes, 1, 2, device=device, dtype=dtype)
logits[:, 0] = 10.0
@@ -43,15 +44,32 @@ class TestTverskyLoss(BaseTester):
logits[:, 2] = 1.0
labels = torch.zeros(2, 1, 2, device=device, dtype=torch.int64)
- criterion = kornia.losses.TverskyLoss(alpha=0.5, beta=0.5)
+ criterion = kornia.losses.TverskyLoss(alpha=0.5, beta=0.5, ignore_index=ignore_index)
loss = criterion(logits, labels)
self.assert_close(loss, torch.zeros_like(loss), atol=1e-3, rtol=1e-3)
+ @pytest.mark.parametrize("ignore_index", [-100, 255])
+ def test_ignore_index(self, device, dtype, ignore_index):
+ num_classes = 2
+
+ logits = torch.zeros(2, num_classes, 1, 4, device=device, dtype=dtype)
+ logits[:, 0, :, 0] = 100.0
+ logits[:, 1, :, 1:] = 100.0
+ labels = torch.zeros(2, 1, 4, device=device, dtype=torch.int64)
+
+ labels[..., 2:] = ignore_index
+ expected_loss = torch.tensor([1.0 / 2.0], device=device, dtype=dtype).squeeze()
+ criterion = kornia.losses.TverskyLoss(alpha=0.5, beta=0.5, ignore_index=ignore_index)
+ loss = criterion(logits, labels)
+ self.assert_close(loss, expected_loss, rtol=1e-3, atol=1e-3)
+
def test_gradcheck(self, device):
num_classes = 3
alpha, beta = 0.5, 0.5 # for tversky loss
logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=torch.float64)
labels = torch.randint(0, num_classes, (2, 3, 2), device=device)
+ ignore = torch.rand(2, 3, 2, device=device) > 0.8
+ labels[ignore] = -100
self.gradcheck(
kornia.losses.tversky_loss, (logits, labels, alpha, beta), dtypes=[torch.float64, torch.int64, None, None]