Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(losses): Convention blocks and pins for the dense-prediction losses (batch 12b) (#5634)

Dmytro Mishkin4cafa022f0f0
diff --git a/changelog.d/5634.added.md b/changelog.d/5634.added.md
new file mode 100644
index 000000000..9969204a0
--- /dev/null
+++ b/changelog.d/5634.added.md
@@ -0,0 +1 @@
+Convention blocks for the dense-prediction losses (`focal_loss`, `binary_focal_loss_with_logits`, `dice_loss`, `tversky_loss`, the LovĂĄsz and Hausdorff losses and `one_hot`), with `test_convention_*` pins and a "Dense-prediction losses" sub-section on the conventions page.
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index ad6908eed..03ebdeaf9 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -852,6 +852,48 @@ The losses on the :doc:`segmentation page </losses.segmentation>` take raw logit
:func:`~kornia.losses.focal_loss` documents the multi-class input, with the classes on axis 1 and an integer label map
as the target.
+**Class 0 is the background** wherever a loss or a metric singles one class out:
+:func:`~kornia.losses.focal_loss` weights class 0 by ``1 - alpha`` and classes ``1`` to ``C - 1`` by ``alpha``, and
+:func:`~kornia.metrics.mean_average_precision` never scores class 0, which its ``n_classes`` still counts. Keep the
+background at label 0 when porting a label map: moving it changes both results. ``focal_loss`` with ``alpha=None``,
+:func:`~kornia.losses.dice_loss`, :func:`~kornia.losses.tversky_loss`, :func:`~kornia.losses.lovasz_softmax_loss` and
+:class:`~kornia.losses.HausdorffERLoss` treat class 0 like every other class.
+
+With ``alpha=None`` and ``gamma=0``, the target slice of :func:`~kornia.losses.focal_loss` is the cross entropy, but
+its ``'mean'`` is not that of :func:`~torch.nn.functional.cross_entropy`. It divides the sum by every element of the
+``(B, C, *)`` output, ``C`` times the pixel count, ignored pixels included, and it does not normalise ``weight``, where
+``cross_entropy`` divides by the summed weights of the target classes of the non-ignored pixels. To port
+``F.cross_entropy(pred, target, weight=w, ignore_index=i)``, divide
+``focal_loss(pred, target, alpha=None, gamma=0.0, reduction='sum', weight=w, ignore_index=i)`` by
+``w[target[target != i]].sum()``, or by the number of non-ignored pixels when there is no ``w``.
+
+The other dense-prediction losses against their references:
+
+- :func:`~kornia.losses.binary_focal_loss_with_logits` with its defaults, ``alpha=0.25`` on the positive term,
+ ``gamma=2`` and ``reduction='none'``, equals ``torchvision.ops.sigmoid_focal_loss`` on targets of 0 and 1. On a
+ fractional target ``t`` they differ: kornia weights its positive and negative focal terms by ``t`` and ``1 - t``,
+ torchvision applies ``alpha_t * (1 - p_t) ** gamma`` to the whole binary cross entropy. Its ``pos_weight`` of shape
+ ``(C,)`` runs along dim 1: ``binary_focal_loss_with_logits(pred, target, alpha=None, gamma=0.0, pos_weight=pw)``
+ equals ``F.binary_cross_entropy_with_logits(pred, target, pos_weight=pw.view(C, 1, 1), reduction='none')`` on
+ ``(B, C, H, W)``, where torch broadcasts a ``(C,)`` ``pos_weight`` along the last axis.
+- The LovĂĄsz losses score each image on its own, as the reference implementation of Berman et al.
+ (``bermanmaxim/LovaszSoftmax``) does with ``per_image=True``: :func:`~kornia.losses.lovasz_hinge_loss` is its
+ ``lovasz_hinge(pred[:, 0], target, per_image=True)``, the reference default, and
+ :func:`~kornia.losses.lovasz_softmax_loss` is ``lovasz_softmax(pred.softmax(1), target, classes='all',
+ per_image=True)``. The ``lovasz_softmax`` defaults, ``classes='present'`` and ``per_image=False``, score only the
+ classes present and flatten the batch into one image, which gives another value.
+
+A class absent from the target has no overlap to score, and the per-class functions treat it differently:
+
+- :func:`~kornia.metrics.mean_iou` returns IoU 1 for a class absent from both the target and the prediction, through
+ its ``eps``, and leaves the averaging over classes to the caller: drop the classes that occur in neither map before
+ averaging its ``(B, K)`` output. scikit-learn's ``jaccard_score`` leaves such a class out unless ``labels`` names it,
+ and then scores it 0, or 1 with ``zero_division=1.0``.
+- ``dice_loss(average='macro')`` and :func:`~kornia.losses.tversky_loss` leave it out of the sample's mean, whether
+ it is predicted or not.
+- :func:`~kornia.metrics.mean_average_precision` pools the images and leaves out a class without a ground-truth object
+ in any of them, detected or not; its entry in the per-class dictionary is ``-1``.
+
Task metrics
^^^^^^^^^^^^
diff --git a/kornia/losses/dice.py b/kornia/losses/dice.py
index 579b81b79..e14742666 100644
--- a/kornia/losses/dice.py
+++ b/kornia/losses/dice.py
@@ -51,8 +51,8 @@ def dice_loss(
\text{Dice}(x, class) = \frac{2 |X \cap Y|}{|X| + |Y|}
Where:
- - :math:`X` expects to be the scores of each class.
- - :math:`Y` expects to be the one-hot torch.Tensor with the class labels.
+ - :math:`X` is the softmax of ``pred`` over the classes.
+ - :math:`Y` is the one-hot encoding of ``target`` by :func:`~kornia.losses.one_hot`.
the loss, is finally computed as:
@@ -63,6 +63,25 @@ def dice_loss(
Reference:
[1] https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient
+ Convention:
+ - ``pred`` and ``target`` are those of :func:`~kornia.losses.focal_loss` (logits with the softmax taken
+ inside, int64 class indices; see its Convention block), restricted to ``(B, C, H, W)`` and ``(B, H, W)``.
+ A one-channel ``pred`` has a softmax of 1 everywhere and gives a constant loss with zero gradient: a binary
+ task passes two channels.
+ - ``'micro'`` (default) computes one Dice per sample over all classes and pixels, ``weight`` scaling the
+ terms of class ``c`` in both sums: :math:`1 - 2 \sum_c w_c |X_c \cap Y_c| / \sum_c w_c (|X_c| + |Y_c|)`.
+ ``'macro'`` computes one Dice per sample and class and averages them as
+ :math:`\sum_c w_c \, \text{loss}_c / \sum_c w_c` over the classes present in the sample's non-ignored
+ target: a class that is predicted but absent from the target is left out. Both then average over the batch
+ and return a 0-d tensor; there is no ``reduction``.
+ - ``eps`` is added to the denominator only: :math:`1 - 2 |X \cap Y| / (|X| + |Y| + \epsilon)`.
+ - Pixels labelled ``ignore_index`` (default ``-100``) leave both sums of their own sample. A sample whose
+ pixels are all ignored, or whose present classes all have weight 0, enters the batch mean as loss 1.
+ - Known defect: with ``eps=0``, a sample whose pixels are all ignored gives a NaN loss in ``'micro'`` and a
+ NaN gradient in ``'macro'``, and a ``weight`` that is 0 for every class gives a NaN ``'micro'`` loss; in
+ float16 that weight also gives a non-finite ``'micro'`` gradient at the default ``eps``
+ (`#5631 <https://github.com/kornia/kornia/issues/5631>`_).
+
Args:
pred: logits torch.Tensor with shape :math:`(N, C, H, W)` where C = number of classes.
target: labels torch.Tensor with shape :math:`(N, H, W)` where each value
@@ -71,10 +90,10 @@ def dice_loss(
Reduction applied in multi-class scenario:
- ``'micro'`` [default]: Calculate the loss across all classes.
- - ``'macro'``: Average class losses over classes present in each sample's non-ignored target.
- Samples with all pixels ignored, or whose present classes all have weight 0, have loss 1.
- eps: Scalar to enforce numerical stabiliy.
- weight: weights for classes with shape :math:`(num\_of\_classes,)`.
+ - ``'macro'``: Average the class losses of each sample; see the Convention block.
+ eps: Scalar added to the denominator of the Dice ratio for numerical stability.
+ weight: weights for classes with shape :math:`(num\_of\_classes,)`; see the Convention block for how each
+ ``average`` applies them.
ignore_index: labels with this value are ignored in the loss computation.
Return:
@@ -181,14 +200,12 @@ def dice_loss(
class DiceLoss(nn.Module):
r"""Criterion that computes Sørensen-Dice Coefficient loss.
- Dice-based objectives are common in medical and semantic segmentation because pixel classes
- are often highly imbalanced. This loss directly optimizes region-level agreement.
+ Convention:
+ See the Convention block of :func:`~kornia.losses.dice_loss`.
Args:
- average: Reduction strategy for multi-class computation. Use "micro" to aggregate
- classes globally, or "macro" to average over classes present in each sample's
- non-ignored target. Samples with all pixels ignored, or whose present classes all have
- weight 0, have loss 1.
+ average: Reduction strategy for multi-class computation. Use "micro" to pool the classes of each
+ sample, or "macro" to average over classes present in each sample's non-ignored target.
eps: Small constant added to the denominator for numerical stability.
weight: Optional class-weight tensor of shape :math:`(C,)`.
ignore_index: Label value to exclude from loss computation.
@@ -196,7 +213,7 @@ class DiceLoss(nn.Module):
Shapes:
- pred: :math:`(N, C, H, W)` where C is the number of classes.
- target: :math:`(N, H, W)` where each value is in the range :math:`[0, C-1]`.
- - Output: scalar by default.
+ - Output: scalar.
"""
def __init__(
diff --git a/kornia/losses/focal.py b/kornia/losses/focal.py
index e4770e779..3c9fecab5 100644
--- a/kornia/losses/focal.py
+++ b/kornia/losses/focal.py
@@ -48,13 +48,38 @@ def focal_loss(
\text{FL}(p_t) = -\alpha_t (1 - p_t)^{\gamma} \, \text{log}(p_t)
Where:
- - :math:`p_t` is the model's estimated probability for each class.
+ - :math:`p_t` is the softmax probability of the target class.
+ - :math:`\alpha_t` is :math:`1 - \alpha` for class 0 and :math:`\alpha` for every other class.
+
+ Convention:
+ - ``pred`` holds logits ``(B, C, *)`` and the softmax over dim 1 is taken inside. ``target`` holds int64
+ class indices ``(B, *)`` in ``[0, C)``; its batch and spatial sizes must equal those of ``pred``.
+ - Class 0 is the background: ``alpha`` weights it by :math:`1 - \alpha` and classes :math:`1, \dots, C - 1`
+ by :math:`\alpha`, so a relabelling that moves class 0 changes the loss. ``alpha=None`` weights every class
+ by 1. With ``C = 2`` the target slice equals :func:`~kornia.losses.binary_focal_loss_with_logits` of the
+ logit difference ``pred[:, 1:] - pred[:, :1]`` and the target ``target[:, None]``, with the same ``alpha``
+ and ``gamma``: class 1 is the positive class.
+ - The default ``reduction='none'`` returns a ``(B, C, *)`` map whose target slice holds the focal term above
+ and whose other slices are 0 where their log-probability is finite. ``'mean'`` divides its sum by every
+ element of that map, ``C`` times the pixel count, so with ``gamma=0`` and ``alpha=None`` it is the mean
+ cross entropy divided by ``C``.
+ - ``weight`` multiplies the slice of class ``c`` by ``weight[c]``; ``'mean'`` is not normalised by the
+ weights.
+ - A pixel labelled ``ignore_index`` (default ``-100``) is 0 in every slice and still counts in the ``'mean'``
+ denominator, where :func:`~kornia.losses.dice_loss` and :func:`~kornia.losses.tversky_loss` drop it.
+ :ref:`Losses and metrics <losses-metrics-conventions>` ports
+ :func:`~torch.nn.functional.cross_entropy` to this loss.
+ - ``alpha`` outside ``[0, 1]`` and a negative ``gamma`` are not validated.
+ - Known defect: a non-target class whose log-probability overflows to ``-inf``, at a logit gap beyond the
+ range of the dtype (about 65504 in float16), turns its slice, the reduced loss and the gradient of that
+ pixel's logits into NaN (`#5628 <https://github.com/kornia/kornia/issues/5628>`_).
Args:
pred: logits torch.Tensor with shape :math:`(N, C, *)` where C = number of classes.
target: labels torch.Tensor with shape :math:`(N, *)` where each value is an integer
representing correct classification :math:`target[i] \in [0, C)`.
- alpha: Weighting factor :math:`\alpha \in [0, 1]`.
+ alpha: Weighting factor :math:`\alpha \in [0, 1]` of classes :math:`1, \dots, C - 1`; class 0 is weighted by
+ :math:`1 - \alpha`. ``None`` weights every class by 1.
gamma: Focusing parameter :math:`\gamma >= 0`.
reduction: Specifies the reduction to apply to the
output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
@@ -62,7 +87,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.
+ ignore_index: labels with this value contribute 0 to the loss but stay in the ``'mean'`` denominator.
Return:
the computed loss.
@@ -155,10 +180,15 @@ class FocalLoss(nn.Module):
\text{FL}(p_t) = -\alpha_t (1 - p_t)^{\gamma} \, \text{log}(p_t)
Where:
- - :math:`p_t` is the model's estimated probability for each class.
+ - :math:`p_t` is the softmax probability of the target class.
+ - :math:`\alpha_t` is :math:`1 - \alpha` for class 0 and :math:`\alpha` for every other class.
+
+ Convention:
+ See the Convention block of :func:`~kornia.losses.focal_loss`.
Args:
- alpha: Weighting factor :math:`\alpha \in [0, 1]`.
+ alpha: Weighting factor :math:`\alpha \in [0, 1]` of classes :math:`1, \dots, C - 1`; class 0 is weighted by
+ :math:`1 - \alpha`. ``None`` weights every class by 1.
gamma: Focusing parameter :math:`\gamma >= 0`.
reduction: Specifies the reduction to apply to the
output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
@@ -166,7 +196,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.
+ ignore_index: labels with this value contribute 0 to the loss but stay in the ``'mean'`` denominator.
Shape:
- Pred: :math:`(N, C, *)` where C = number of classes.
@@ -209,9 +239,8 @@ class FocalLoss(nn.Module):
target: Integer class-label tensor with shape :math:`(B, *)`.
Returns:
- Focal-loss tensor reduced according to ``self.reduction``. The
- focusing factor ``self.gamma`` down-weights easy examples, while
- ``self.alpha`` and ``self.weight`` provide optional class weighting.
+ Focal-loss tensor reduced according to ``self.reduction``. See :func:`~kornia.losses.focal_loss` for
+ the class weighting by ``self.alpha`` and ``self.weight``.
"""
return focal_loss(pred, target, self.alpha, self.gamma, self.reduction, self.weight, self.ignore_index)
@@ -234,24 +263,41 @@ def binary_focal_loss_with_logits(
\text{FL}(p_t) = -\alpha_t (1 - p_t)^{\gamma} \, \text{log}(p_t)
- Where:
- - :math:`p_t` is the model's estimated probability for each class.
+ Where, for a target of 0 or 1:
+ - :math:`p_t` is the sigmoid probability of the target value.
+ - :math:`\alpha_t` is :math:`\alpha` for a target of 1 and :math:`1 - \alpha` for a target of 0.
+
+ Convention:
+ - Every element of ``pred`` is an independent binary logit: ``pred`` is ``(B, C, *)`` with at least two
+ dimensions and ``target`` has its shape, with values in ``[0, 1]``. The default ``reduction='none'``
+ returns that shape; ``'mean'`` and ``'sum'`` reduce it as in :func:`~kornia.losses.focal_loss`.
+ - ``alpha`` (default ``0.25``) weights the positive term and :math:`1 - \alpha` the negative term. A
+ fractional target :math:`t` weights the two terms by :math:`t` and :math:`1 - t`:
+ :math:`t \alpha (1 - p)^\gamma (-\log p) + (1 - t) (1 - \alpha) p^\gamma (-\log (1 - p))`, where :math:`p`
+ is the sigmoid of the logit.
+ - ``pos_weight`` and ``weight`` are ``(C,)`` vectors applied along dim 1: ``pos_weight[c]`` scales the
+ positive term of channel ``c`` and ``weight[c]`` its whole loss.
+ - A target entry equal to ``ignore_index`` (default ``-100``) contributes 0 and still counts in the
+ ``'mean'`` denominator, as in :func:`~kornia.losses.focal_loss`.
+ - :ref:`Losses and metrics <losses-metrics-conventions>` maps this loss onto torchvision's
+ ``sigmoid_focal_loss`` and torch's ``pos_weight``.
Args:
pred: logits torch.Tensor with shape :math:`(N, C, *)` where C = number of classes.
target: labels torch.Tensor with the same shape as pred :math:`(N, C, *)`
where each value is between 0 and 1.
- alpha: Weighting factor :math:`\alpha \in [0, 1]`.
+ alpha: Weighting factor :math:`\alpha \in [0, 1]` of the positive term; the negative term is weighted by
+ :math:`1 - \alpha`.
gamma: Focusing parameter :math:`\gamma >= 0`.
reduction: Specifies the reduction to apply to the
output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
will be applied, ``'mean'``: the sum of the output will be divided by
the number of elements in the output, ``'sum'``: the output will be
summed.
- 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.
+ pos_weight: a weight of the positive term of each channel, with shape :math:`(num\_of\_classes,)`.
weight: weights for classes with shape :math:`(num\_of\_classes,)`.
- ignore_index: labels with this value are ignored in the loss computation.
+ ignore_index: target entries with this value contribute 0 to the loss but stay in the ``'mean'``
+ denominator.
Returns:
the computed loss.
@@ -339,21 +385,27 @@ class BinaryFocalLossWithLogits(nn.Module):
\text{FL}(p_t) = -\alpha_t (1 - p_t)^{\gamma} \, \text{log}(p_t)
- where:
- - :math:`p_t` is the model's estimated probability for each class.
+ where, for a target of 0 or 1:
+ - :math:`p_t` is the sigmoid probability of the target value.
+ - :math:`\alpha_t` is :math:`\alpha` for a target of 1 and :math:`1 - \alpha` for a target of 0.
+
+ Convention:
+ See the Convention block of :func:`~kornia.losses.binary_focal_loss_with_logits`. Unlike the function,
+ ``alpha`` has no default here.
Args:
- alpha: Weighting factor :math:`\alpha \in [0, 1]`.
+ alpha: Weighting factor :math:`\alpha \in [0, 1]` of the positive term; the negative term is weighted by
+ :math:`1 - \alpha`.
gamma: Focusing parameter :math:`\gamma >= 0`.
reduction: Specifies the reduction to apply to the
output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
will be applied, ``'mean'``: the sum of the output will be divided by
the number of elements in the output, ``'sum'``: the output will be
summed.
- 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.
+ pos_weight: a weight of the positive term of each channel, with shape :math:`(num\_of\_classes,)`.
weight: weights for classes with shape :math:`(num\_of\_classes,)`.
- ignore_index: labels with this value are ignored in the loss computation.
+ ignore_index: target entries with this value contribute 0 to the loss but stay in the ``'mean'``
+ denominator.
Shape:
- Pred: :math:`(N, C, *)` where C = number of classes.
@@ -392,13 +444,13 @@ class BinaryFocalLossWithLogits(nn.Module):
"""Compute binary focal loss from logits.
Args:
- pred: Logit tensor for binary predictions with arbitrary shape.
+ pred: Logit tensor with shape :math:`(B, C, *)`, at least two dimensions.
target: Binary target tensor with the same shape as ``pred``.
Returns:
Binary focal-loss tensor reduced according to ``self.reduction``.
- Positive examples may be reweighted by ``self.pos_weight`` and
- examples matching ``self.ignore_index`` are ignored when configured.
+ Positive terms may be reweighted by ``self.pos_weight``, and entries
+ matching ``self.ignore_index`` contribute 0 when configured.
"""
return binary_focal_loss_with_logits(
pred, target, self.alpha, self.gamma, self.reduction, self.pos_weight, self.weight, self.ignore_index
diff --git a/kornia/losses/hausdorff.py b/kornia/losses/hausdorff.py
index 10de9091a..cdbf45585 100644
--- a/kornia/losses/hausdorff.py
+++ b/kornia/losses/hausdorff.py
@@ -26,18 +26,18 @@ from kornia.core.utils import is_exporting
class _HausdorffERLossBase(nn.Module):
- """Base class for binary Hausdorff loss based on morphological erosion.
+ """Base class for the Hausdorff losses based on morphological erosion, one binary map per class channel.
This is an Hausdorff Distance (HD) Loss that based on morphological erosion,which provided
a differentiable approximation of Hausdorff distance as stated in :cite:`karimi2019reducing`.
The code is refactored on top of `here <https://github.com/PatRyg99/HausdorffLoss/
- blob/master/hausdorff_loss.py>`__.
+ blob/master/hausdorff_loss.py>`__.
Args:
- alpha: controls the erosion rate in each iteration.
+ alpha: the exponent of the weight ``(i + 1) ** alpha`` of erosion ``i = 0, ..., k - 1``.
k: the number of iterations of erosion.
reduction: Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'.
- 'none': no reduction will be applied, 'mean': the weighted mean of the output is taken,
+ 'none': no reduction will be applied, 'mean': the mean of the output is taken,
'sum': the output will be summed.
Returns:
@@ -101,7 +101,7 @@ class _HausdorffERLossBase(nn.Module):
Args:
pred: predicted torch.Tensor with a shape of :math:`(B, C, H, W)` or :math:`(B, C, D, H, W)`.
Each channel is as binary as: 1 -> fg, 0 -> bg.
- target: target torch.Tensor with a shape of :math:`(B, 1, H, W)` or :math:`(B, C, D, H, W)`.
+ target: target torch.Tensor with a shape of :math:`(B, 1, H, W)` or :math:`(B, 1, D, H, W)`.
Returns:
Estimated Hausdorff Loss.
@@ -148,7 +148,7 @@ class _HausdorffERLossBase(nn.Module):
class HausdorffERLoss(_HausdorffERLossBase):
- r"""Binary Hausdorff loss based on morphological erosion.
+ r"""Hausdorff loss based on morphological erosion, one binary map per class channel.
Hausdorff Distance loss measures the maximum distance of a predicted segmentation boundary to
the nearest ground-truth edge pixel. For two segmentation point sets X and Y ,
@@ -169,16 +169,26 @@ class HausdorffERLoss(_HausdorffERLossBase):
The code is refactored on top of `here <https://github.com/PatRyg99/HausdorffLoss/
blob/master/hausdorff_loss.py>`__.
+ Convention:
+ - ``pred`` holds per-class probabilities ``(B, C, H, W)`` and nothing is applied to it, unlike the logits of
+ :func:`~kornia.losses.focal_loss`: pass a softmax. ``target`` holds int64 labels ``(B, 1, H, W)`` in
+ ``[0, C)``. Channel ``c`` is compared with ``target == c``, class 0 included.
+ - ``reduction='none'`` returns ``(C, B, 1, H, W)``, class axis first; the default ``'mean'`` is the plain
+ mean of that tensor.
+ - Each of the ``k`` erosions is min-max normalised per image and class and weighted by
+ :math:`(i + 1)^\alpha` for :math:`i = 0, \dots, k - 1`: the value is a unitless surrogate, not a distance
+ in pixels.
+
Args:
- alpha: controls the erosion rate in each iteration.
+ alpha: the exponent of the weight :math:`(i + 1)^\alpha` of erosion :math:`i = 0, \dots, k - 1`.
k: the number of iterations of erosion.
reduction: Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'.
- 'none': no reduction will be applied, 'mean': the weighted mean of the output is taken,
+ 'none': no reduction will be applied, 'mean': the mean of the output is taken,
'sum': the output will be summed.
Examples:
>>> hdloss = HausdorffERLoss()
- >>> input = torch.randn(5, 3, 20, 20)
+ >>> input = torch.randn(5, 3, 20, 20).softmax(1)
>>> target = (torch.rand(5, 1, 20, 20) * 2).long()
>>> res = hdloss(input, target)
@@ -216,7 +226,7 @@ class HausdorffERLoss(_HausdorffERLossBase):
class HausdorffERLoss3D(_HausdorffERLossBase):
- r"""Binary 3D Hausdorff loss based on morphological erosion.
+ r"""3D Hausdorff loss based on morphological erosion, one binary map per class channel.
Hausdorff Distance loss measures the maximum distance of a predicted segmentation boundary to
the nearest ground-truth edge pixel. For two segmentation point sets X and Y ,
@@ -237,16 +247,22 @@ class HausdorffERLoss3D(_HausdorffERLossBase):
The code is refactored on top of `here <https://github.com/PatRyg99/HausdorffLoss/
blob/master/hausdorff_loss.py>`__.
+ Convention:
+ - As in :class:`~kornia.losses.HausdorffERLoss` (see its Convention block), for ``pred`` of shape
+ ``(B, C, D, H, W)`` and ``target`` of shape ``(B, 1, D, H, W)``; ``reduction='none'`` returns
+ ``(C, B, 1, D, H, W)``. The erosion kernel is the voxel and its six face neighbours, so the erosion also
+ runs along ``D``.
+
Args:
- alpha: controls the erosion rate in each iteration.
+ alpha: the exponent of the weight :math:`(i + 1)^\alpha` of erosion :math:`i = 0, \dots, k - 1`.
k: the number of iterations of erosion.
reduction: Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'.
- 'none': no reduction will be applied, 'mean': the weighted mean of the output is taken,
+ 'none': no reduction will be applied, 'mean': the mean of the output is taken,
'sum': the output will be summed.
Examples:
>>> hdloss = HausdorffERLoss3D()
- >>> input = torch.randn(5, 3, 20, 20, 20)
+ >>> input = torch.randn(5, 3, 20, 20, 20).softmax(1)
>>> target = (torch.rand(5, 1, 20, 20, 20) * 2).long()
>>> res = hdloss(input, target)
diff --git a/kornia/losses/lovasz_hinge.py b/kornia/losses/lovasz_hinge.py
index 5fc87f427..81ca0dabb 100644
--- a/kornia/losses/lovasz_hinge.py
+++ b/kornia/losses/lovasz_hinge.py
@@ -35,17 +35,19 @@ def lovasz_hinge_loss(pred: Tensor, target: Tensor) -> Tensor:
\text{IoU}(x, class) = \frac{|X \cap Y|}{|X \cup Y|}
- [1] approximates this fomular with a surrogate, which is fully differentable.
+ [1] approximates this formula with a surrogate, which is fully differentiable.
Where:
- - :math:`X` expects to be the scores of each class.
- - :math:`Y` expects to be the binary tensor with the class labels.
+ - :math:`X` is the foreground predicted by the single logit channel of ``pred``.
+ - :math:`Y` is the foreground of the binary ``target``.
- the loss, is finally computed as:
+ the Jaccard loss is
.. math::
- \text{loss}(x, class) = 1 - \text{IoU}(x, class)
+ \Delta_J(x, class) = 1 - \text{IoU}(x, class)
+
+ and the loss is its LovĂĄsz extension [1], evaluated at the hinge errors; see the Convention block.
Reference:
[1] http://proceedings.mlr.press/v37/yub15.pdf
@@ -55,6 +57,18 @@ def lovasz_hinge_loss(pred: Tensor, target: Tensor) -> Tensor:
This loss function only supports binary labels. For multi-class labels please
use the Lovasz-Softmax loss.
+ Convention:
+ - ``pred`` holds one logit channel ``(B, 1, H, W)`` and ``target`` the labels ``(B, H, W)``, 1 for the
+ foreground and 0 for the background. The loss is computed per image and averaged over the batch into a
+ 0-d tensor; there is no ``reduction``.
+ - The loss is the LovĂĄsz extension of the Jaccard loss at the hinge errors :math:`\max(0, 1 - z (2t - 1))`
+ of logit :math:`z` and label :math:`t`, not :math:`1 - \text{IoU}`: logits of :math:`\pm 1` that are
+ positive on the predicted foreground give :math:`2 (1 - \text{IoU})` of that prediction, and correct
+ logits of magnitude at least 1 give 0.
+ - ``target`` is not validated and there is no ``ignore_index``: a label of 2 is accepted, and ``-100``, the
+ ``ignore_index`` of :func:`~kornia.losses.focal_loss` and :func:`~kornia.losses.dice_loss`, can make the
+ loss negative.
+
Args:
pred: logits tensor with shape :math:`(N, 1, H, W)`.
target: labels tensor with shape :math:`(N, H, W)` with binary values.
@@ -119,17 +133,19 @@ class LovaszHingeLoss(nn.Module):
\text{IoU}(x, class) = \frac{|X \cap Y|}{|X \cup Y|}
- [1] approximates this fomular with a surrogate, which is fully differentable.
+ [1] approximates this formula with a surrogate, which is fully differentiable.
Where:
- - :math:`X` expects to be the scores of each class.
- - :math:`Y` expects to be the binary tensor with the class labels.
+ - :math:`X` is the foreground predicted by the single logit channel of ``pred``.
+ - :math:`Y` is the foreground of the binary ``target``.
- the loss, is finally computed as:
+ the Jaccard loss is
.. math::
- \text{loss}(x, class) = 1 - \text{IoU}(x, class)
+ \Delta_J(x, class) = 1 - \text{IoU}(x, class)
+
+ and the loss is its LovĂĄsz extension [1], evaluated at the hinge errors.
Reference:
[1] http://proceedings.mlr.press/v37/yub15.pdf
@@ -139,9 +155,12 @@ class LovaszHingeLoss(nn.Module):
This loss function only supports binary labels. For multi-class labels please
use the Lovasz-Softmax loss.
+ Convention:
+ See the Convention block of :func:`~kornia.losses.lovasz_hinge_loss`.
+
Args:
pred: logits tensor with shape :math:`(N, 1, H, W)`.
- labels: labels tensor with shape :math:`(N, H, W)` with binary values.
+ target: labels tensor with shape :math:`(N, H, W)` with binary values.
Return:
a scalar with the computed loss, in the dtype of a floating-point ``pred`` and in float32 for an
diff --git a/kornia/losses/lovasz_softmax.py b/kornia/losses/lovasz_softmax.py
index a5b3c1ae2..656db9c6b 100644
--- a/kornia/losses/lovasz_softmax.py
+++ b/kornia/losses/lovasz_softmax.py
@@ -37,17 +37,19 @@ def lovasz_softmax_loss(pred: Tensor, target: Tensor, weight: Optional[Tensor] =
\text{IoU}(x, class) = \frac{|X \cap Y|}{|X \cup Y|}
- [1] approximates this fomular with a surrogate, which is fully differentable.
+ [1] approximates this formula with a surrogate, which is fully differentiable.
Where:
- - :math:`X` expects to be the scores of each class.
- - :math:`Y` expects to be the long tensor with the class labels.
+ - :math:`X` is the softmax of ``pred`` over the classes.
+ - :math:`Y` is the one-hot encoding of the integer class labels in ``target``.
- the loss, is finally computed as:
+ the Jaccard loss of each class is
.. math::
- \text{loss}(x, class) = 1 - \text{IoU}(x, class)
+ \Delta_J(x, class) = 1 - \text{IoU}(x, class)
+
+ and the loss is the mean over the classes of its LovĂĄsz extension, evaluated at the errors :math:`|X - Y|`.
Reference:
[1] https://arxiv.org/pdf/1705.08790.pdf
@@ -56,6 +58,17 @@ def lovasz_softmax_loss(pred: Tensor, target: Tensor, weight: Optional[Tensor] =
This loss function only supports multi-class (C > 1) labels. For binary
labels please use the Lovasz-Hinge loss.
+ Convention:
+ - ``pred`` holds logits ``(B, C, H, W)`` with ``C >= 2`` and the softmax over dim 1 is taken inside;
+ ``target`` holds class labels ``(B, H, W)`` in ``[0, C)``. There is no ``ignore_index`` and the labels are
+ not validated: a label of ``-100`` is not ignored, and the result for it is undefined.
+ - Each image is scored on its own and the losses are averaged over the batch into a 0-d tensor; there is no
+ ``reduction``. An image's loss is the mean over all ``C`` classes: a class absent from the image enters it
+ with that image's largest probability for the class.
+ - ``weight`` multiplies the term of each class and the mean still divides by ``C``, so a uniform weight of 2
+ doubles the loss, where ``dice_loss(average='macro')`` divides by the summed weights of the classes it
+ averages.
+
Args:
pred: logits tensor with shape :math:`(N, C, H, W)` where C = number of classes > 1.
target: labels tensor with shape :math:`(N, H, W)` where each value
@@ -146,17 +159,19 @@ class LovaszSoftmaxLoss(nn.Module):
\text{IoU}(x, class) = \frac{|X \cap Y|}{|X \cup Y|}
- [1] approximates this fomular with a surrogate, which is fully differentable.
+ [1] approximates this formula with a surrogate, which is fully differentiable.
Where:
- - :math:`X` expects to be the scores of each class.
- - :math:`Y` expects to be the binary tensor with the class labels.
+ - :math:`X` is the softmax of ``pred`` over the classes.
+ - :math:`Y` is the one-hot encoding of the integer class labels in ``target``.
- the loss, is finally computed as:
+ the Jaccard loss of each class is
.. math::
- \text{loss}(x, class) = 1 - \text{IoU}(x, class)
+ \Delta_J(x, class) = 1 - \text{IoU}(x, class)
+
+ and the loss is the mean over the classes of its LovĂĄsz extension, evaluated at the errors :math:`|X - Y|`.
Reference:
[1] https://arxiv.org/pdf/1705.08790.pdf
@@ -165,9 +180,12 @@ class LovaszSoftmaxLoss(nn.Module):
This loss function only supports multi-class (C > 1) labels. For binary
labels please use the Lovasz-Hinge loss.
+ Convention:
+ See the Convention block of :func:`~kornia.losses.lovasz_softmax_loss`.
+
Args:
pred: logits tensor with shape :math:`(N, C, H, W)` where C = number of classes > 1.
- labels: labels tensor with shape :math:`(N, H, W)` where each value
+ target: labels tensor with shape :math:`(N, H, W)` where each value
is in range :math:`0 ≤ targets[i] ≤ C-1`.
weight: weights for classes with shape :math:`(num\_of\_classes,)`.
diff --git a/kornia/losses/one_hot.py b/kornia/losses/one_hot.py
index a184f12ab..9d62109e5 100644
--- a/kornia/losses/one_hot.py
+++ b/kornia/losses/one_hot.py
@@ -26,6 +26,12 @@ def one_hot(
) -> torch.Tensor:
r"""Convert an integer label x-D torch.Tensor to a one-hot (x+1)-D torch.Tensor.
+ Convention:
+ - int64 ``labels`` of shape ``(N, *)`` become ``(N, C, *)``: the class axis is dim 1, where
+ :func:`~torch.nn.functional.one_hot` puts it last. With the default ``eps=0.0`` the result is
+ ``F.one_hot(labels, num_classes).movedim(-1, 1).to(device, dtype)``. Labels outside ``[0, num_classes)``
+ are not validated by kornia; the result for them is undefined.
+
Args:
labels: torch.Tensor with labels of shape :math:`(N, *)`, where N is batch size.
Each value is an integer representing correct classification.
diff --git a/kornia/losses/tversky.py b/kornia/losses/tversky.py
index 099828019..a7c77d3de 100644
--- a/kornia/losses/tversky.py
+++ b/kornia/losses/tversky.py
@@ -54,14 +54,19 @@ def tversky_loss(
penalties for FPs and FNs, respectively.
Note:
- - Scores are computed per class and averaged over classes present in each
- sample's non-ignored target, then over samples. Fully ignored samples have loss 1.
- - :math:`\alpha = \beta = 0.5` corresponds to macro Dice with exact targets
- and a denominator epsilon of :math:`2\,\text{eps}` in the Dice formula.
+ - :math:`\alpha = \beta = 0.5` gives :func:`~kornia.losses.dice_loss` with ``average='macro'`` and twice
+ the ``eps``.
- :math:`\alpha = \beta = 1` corresponds to the per-class Tanimoto coefficient.
- For :math:`\alpha + \beta = 1` and :math:`\alpha > 0`, the unsmoothed
per-class score is :math:`F_{\sqrt{\beta / \alpha}}`.
+ Convention:
+ ``pred``, ``target`` and ``ignore_index`` behave as in :func:`~kornia.losses.dice_loss`: logits
+ ``(B, C, H, W)`` with the softmax taken inside, int64 class indices ``(B, H, W)`` and ignored pixels removed
+ from their own sample. The index is computed per sample and class, averaged over the classes present in the
+ sample's non-ignored target, then over the batch into a 0-d tensor; a sample whose pixels are all ignored
+ enters the batch mean as loss 1. There is no ``weight``, ``average`` or ``reduction``.
+
Args:
pred: logits tensor with shape :math:`(N, C, H, W)` where C = number of classes.
target: labels tensor with shape :math:`(N, H, W)` where each value
@@ -144,14 +149,15 @@ class TverskyLoss(nn.Module):
penalties for FPs and FNs, respectively.
Note:
- - Scores are computed per class and averaged over classes present in each
- sample's non-ignored target, then over samples. Fully ignored samples have loss 1.
- - :math:`\alpha = \beta = 0.5` corresponds to macro Dice with exact targets
- and a denominator epsilon of :math:`2\,\text{eps}` in the Dice formula.
+ - :math:`\alpha = \beta = 0.5` gives :func:`~kornia.losses.dice_loss` with ``average='macro'`` and twice
+ the ``eps``.
- :math:`\alpha = \beta = 1` corresponds to the per-class Tanimoto coefficient.
- For :math:`\alpha + \beta = 1` and :math:`\alpha > 0`, the unsmoothed
per-class score is :math:`F_{\sqrt{\beta / \alpha}}`.
+ Convention:
+ See the Convention block of :func:`~kornia.losses.tversky_loss`.
+
Args:
alpha: the first coefficient in the denominator.
beta: the second coefficient in the denominator.
diff --git a/tests/losses/test_dice.py b/tests/losses/test_dice.py
index ca0efc5e8..7fef948a2 100644
--- a/tests/losses/test_dice.py
+++ b/tests/losses/test_dice.py
@@ -17,6 +17,7 @@
import pytest
import torch
+import torch.nn.functional as F
import kornia
@@ -454,3 +455,90 @@ class TestDiceLoss(BaseTester):
op_module = kornia.losses.DiceLoss()
self.assert_close(op(logits, labels), op_module(logits, labels))
+
+
+class TestConventionsDiceLoss(BaseTester):
+ """Pins for the averaging modes, ignored labels and known defect of :func:`dice_loss`."""
+
+ @staticmethod
+ def _exact_dice_loss(logits, labels, dims):
+ # 1 - 2 sum(p t) / sum(p + t) in float64, with an exact one-hot target
+ p = logits.cpu().double().softmax(1)
+ t = F.one_hot(labels.cpu(), logits.shape[1]).movedim(-1, 1).double()
+ return 1 - 2 * (p * t).sum(dims) / (p + t).sum(dims)
+
+ def test_convention_dice_loss_micro_pools_the_classes_and_macro_averages_them_per_sample(self, device, dtype):
+ # 'micro': one Dice per sample over every class and pixel; 'macro': one Dice per (sample, class), averaged over
+ # the classes of the sample's target (both, here); both are then averaged over the batch. A two-class map with
+ # unequal class sizes tells the two modes apart, and two samples with different balances tell 'macro' from
+ # pooling the batch (MONAI's DiceLoss(batch=True)). Every sample's 'micro' denominator is 2 H W here, so
+ # per-sample and batch-pooled 'micro' coincide;
+ # test_convention_dice_loss_ignore_index_excludes_pixels_per_sample separates them.
+ labels = torch.zeros(2, 4, 6, dtype=torch.long, device=device)
+ labels[0, 1:3, 1:4] = 1 # 6 of 24 pixels
+ labels[1, :, 2:] = 1 # 16 of 24 pixels
+ predicted = labels.clone()
+ predicted[0, 1, 1:4] = 0 # image 0 misses half of class 1
+ predicted[1, 0, :2] = 1 # image 1 over-segments class 1 by two pixels
+ g = torch.Generator().manual_seed(0)
+ logits = torch.randn(2, 2, 4, 6, generator=g).to(device=device, dtype=dtype)
+ logits = logits + 4.0 * F.one_hot(predicted, 2).movedim(-1, 1).to(dtype)
+ micro = self._exact_dice_loss(logits, labels, (1, 2, 3)).mean() # 0.1548
+ macro = self._exact_dice_loss(logits, labels, (2, 3)).mean() # 0.2085
+ pooled_macro = self._exact_dice_loss(logits, labels, (0, 2, 3)).mean() # 0.1564
+ assert (micro - macro).abs() > 0.04
+ assert (macro - pooled_macro).abs() > 0.04
+ self.assert_close(kornia.losses.dice_loss(logits, labels), micro.to(device=device, dtype=dtype))
+ self.assert_close(
+ kornia.losses.dice_loss(logits, labels, average="macro"), macro.to(device=device, dtype=dtype)
+ )
+
+ @pytest.mark.parametrize("average", ["micro", "macro"])
+ def test_convention_dice_loss_ignore_index_excludes_pixels_per_sample(self, average, device, dtype):
+ # Ignored pixels leave both sums of their own sample, which then enters the batch mean like the others: the
+ # same as cropping them out of that sample. An image whose pixels are all ignored enters the batch mean as
+ # loss 1.
+ def dice(logits, labels):
+ return kornia.losses.dice_loss(logits, labels, average=average)
+
+ g = torch.Generator().manual_seed(0)
+ logits = torch.randn(2, 3, 4, 7, generator=g).to(device=device, dtype=dtype)
+ labels = torch.randint(0, 3, (2, 4, 7), generator=g).to(device)
+ ignored = labels.clone()
+ ignored[0, :, -3:] = -100 # image 0 loses its last three columns
+ expected = (dice(logits[:1, ..., :-3], labels[:1, :, :-3]) + dice(logits[1:], labels[1:])) / 2
+ self.assert_close(dice(logits, ignored), expected)
+ ignored[0] = -100
+ self.assert_close(dice(logits, ignored), (1 + dice(logits[1:], labels[1:])) / 2)
+
+ def test_wart_dice_loss_all_ignored_sample_with_zero_eps_5631(self, device, dtype):
+ # With eps=0 a sample whose pixels are all ignored has empty sums and Dice divides 0 by 0 (#5631): 'micro'
+ # returns NaN, and 'macro' returns the documented loss 1 for that sample but a non-finite gradient, where
+ # tversky_loss substitutes a safe denominator. A weight of 0 for every class empties the weighted 'micro'
+ # cardinality of every sample the same way, while 'macro' keeps loss 1; in float16 that weight's 'micro'
+ # gradient is non-finite at the default eps too, its 2 / eps intersection gradient being past the float16
+ # range. The default eps keeps the all-ignored sample finite in both averages.
+ g = torch.Generator().manual_seed(0)
+ logits = torch.randn(2, 3, 4, 6, generator=g).to(device=device, dtype=dtype).requires_grad_()
+ labels = torch.randint(0, 3, (2, 4, 6), generator=g).to(device)
+ dice = kornia.losses.dice_loss
+ zero = torch.zeros(3, device=device, dtype=dtype)
+ assert dice(logits, labels, eps=0.0, weight=zero).isnan()
+ self.assert_close(dice(logits, labels, average="macro", eps=0.0, weight=zero).detach(), logits.new_tensor(1.0))
+ if dtype == torch.float16:
+ micro = dice(logits, labels, weight=zero)
+ (grad,) = torch.autograd.grad(micro, logits)
+ self.assert_close(micro.detach(), logits.new_tensor(1.0))
+ assert not grad.isfinite().all()
+ labels[0] = -100
+ assert dice(logits, labels, eps=0.0).isnan()
+ macro = dice(logits, labels, average="macro", eps=0.0)
+ rest = dice(logits[1:], labels[1:], average="macro", eps=0.0)
+ self.assert_close(macro.detach(), (1 + rest.detach()) / 2)
+ (grad,) = torch.autograd.grad(macro, logits)
+ assert not grad.isfinite().all()
+ for average in ("micro", "macro"):
+ loss = dice(logits, labels, average=average)
+ (grad,) = torch.autograd.grad(loss, logits)
+ assert loss.isfinite()
+ assert grad.isfinite().all()
diff --git a/tests/losses/test_focal_loss.py b/tests/losses/test_focal_loss.py
index 19d336d86..6e29f37f2 100644
--- a/tests/losses/test_focal_loss.py
+++ b/tests/losses/test_focal_loss.py
@@ -375,3 +375,183 @@ class TestFocalLoss(BaseTester):
op = kornia.losses.focal_loss
op_module = kornia.losses.FocalLoss(*args)
self.assert_close(op_module(logits, labels), op(logits, labels, *args))
+
+
+class TestConventionsFocalLoss(BaseTester):
+ """Pins for the class weighting, reductions, ignored labels and known defect of the focal losses."""
+
+ @staticmethod
+ def _logits_and_labels(device, dtype, scale=1.0):
+ # two 4 x 5 images with different class balances
+ g = torch.Generator().manual_seed(0)
+ logits = (scale * torch.randn(2, 3, 4, 5, generator=g)).to(device=device, dtype=dtype)
+ labels = torch.randint(0, 3, (2, 4, 5), generator=g).to(device)
+ return logits, labels
+
+ def test_convention_focal_loss_alpha_weights_class_0_by_one_minus_alpha(self, device, dtype):
+ # alpha_t is 1 - alpha for class 0 (background) and alpha for classes 1 .. C-1, as in Detectron's softmax
+ # focal loss: a relabelling that keeps class 0 in place leaves the loss unchanged, one that moves class 0
+ # changes it, and alpha=None is invariant under both
+ logits, labels = self._logits_and_labels(device, dtype, scale=2.0)
+ focal = kornia.losses.focal_loss
+ target = labels[:, None]
+ alpha_t = torch.where(target == 0, 0.75, 0.25).to(dtype)
+ self.assert_close(
+ focal(logits, labels, 0.25).gather(1, target), alpha_t * focal(logits, labels, None).gather(1, target)
+ )
+ for order, moves_class_0 in (([0, 2, 1], False), ([1, 2, 0], True)):
+ perm = torch.tensor(order, device=device) # class c becomes class perm[c]
+ relabelled = (logits[:, perm.argsort()], perm[labels])
+ self.assert_close(focal(*relabelled, None, reduction="sum"), focal(logits, labels, None, reduction="sum"))
+ moved = focal(*relabelled, 0.25, reduction="sum")
+ kept = focal(logits, labels, 0.25, reduction="sum")
+ if moves_class_0:
+ assert (moved - kept).abs() > 0.05 * kept.abs()
+ else:
+ self.assert_close(moved, kept)
+
+ def test_convention_focal_loss_default_reduction_is_none_in_the_input_layout(self, device, dtype):
+ # the default reduction is 'none': a (B, C, H, W) map whose target slice holds (1 - p_t)^gamma (-log p_t)
+ logits, labels = self._logits_and_labels(device, dtype)
+ out = kornia.losses.focal_loss(logits, labels, None)
+ assert out.shape == (2, 3, 4, 5)
+ log_p_t = logits.cpu().double().log_softmax(1).gather(1, labels.cpu()[:, None])
+ expected = (1 - log_p_t.exp()) ** 2 * -log_p_t
+ self.assert_close(out.gather(1, labels[:, None]), expected.to(device=device, dtype=dtype))
+ transposed = kornia.losses.focal_loss(logits.transpose(-2, -1), labels.transpose(-2, -1), None)
+ self.assert_close(transposed, out.transpose(-2, -1))
+
+ def test_convention_focal_loss_mean_divides_by_the_class_axis_too(self, device, dtype):
+ # 'mean' averages every element of the (B, C, *) output, so with gamma = 0 and alpha = None it is the per-pixel
+ # cross entropy divided by C, where torch's cross_entropy 'mean' averages over the pixels only
+ logits, labels = self._logits_and_labels(device, dtype)
+ cross_entropy = -logits.cpu().double().log_softmax(1).gather(1, labels.cpu()[:, None])
+ mean = kornia.losses.focal_loss(logits, labels, None, gamma=0.0, reduction="mean")
+ self.assert_close(mean, (cross_entropy.mean() / 3).to(device=device, dtype=dtype))
+ total = kornia.losses.focal_loss(logits, labels, None, gamma=0.0, reduction="sum")
+ self.assert_close(total, cross_entropy.sum().to(device=device, dtype=dtype))
+
+ def test_convention_focal_loss_does_not_validate_alpha_and_gamma(self, device, dtype):
+ # alpha outside [0, 1] and a negative gamma are accepted and give a finite loss: kornia checks neither
+ logits, labels = self._logits_and_labels(device, dtype, scale=0.5)
+ for alpha, gamma in ((2.0, 2.0), (0.25, -1.0)):
+ assert kornia.losses.focal_loss(logits, labels, alpha, gamma, "mean").isfinite()
+
+ def test_convention_focal_loss_weight_is_not_normalised_in_the_mean(self, device, dtype):
+ # weight (C,) scales each class's slice and 'mean' still divides by the element count, where torch's
+ # cross_entropy(weight=) 'mean' divides by the summed weights of the target labels
+ logits, labels = self._logits_and_labels(device, dtype)
+ weight = torch.tensor([0.2, 1.0, 4.0], device=device, dtype=dtype)
+ w_t = torch.tensor([0.2, 1.0, 4.0], dtype=torch.float64)[labels.cpu()[:, None]]
+ weighted = -w_t * logits.cpu().double().log_softmax(1).gather(1, labels.cpu()[:, None])
+ mean = kornia.losses.focal_loss(logits, labels, None, gamma=0.0, reduction="mean", weight=weight)
+ self.assert_close(mean, (weighted.sum() / (3 * labels.numel())).to(device=device, dtype=dtype))
+ assert (mean.cpu().double() * 3 - weighted.sum() / w_t.sum()).abs() > 0.05 * weighted.sum() / w_t.sum()
+
+ def test_convention_focal_losses_ignored_labels_are_zero_weighted_in_the_mean(self, device, dtype):
+ # A label equal to ignore_index (-100) contributes 0 but its elements stay in the 'mean' denominator; torch's
+ # cross_entropy(ignore_index=) and binary_cross_entropy over the valid entries drop them from the mean instead
+ logits, labels = self._logits_and_labels(device, dtype)
+ labels[0, 0, :4] = -100 # 4 ignored pixels in image 0, 3 in image 1
+ labels[1, 3, 2:] = -100
+ ignored = labels.cpu() == -100
+ safe = labels.cpu().clamp_min(0)[:, None]
+ out = kornia.losses.focal_loss(logits, labels, None, gamma=0.0)
+ assert (out.cpu().movedim(1, -1)[ignored] == 0).all()
+ cross_entropy = -logits.cpu().double().log_softmax(1).gather(1, safe)[:, 0][~ignored]
+ mean = kornia.losses.focal_loss(logits, labels, None, gamma=0.0, reduction="mean")
+ self.assert_close(mean, (cross_entropy.sum() / out.numel()).to(device=device, dtype=dtype))
+ assert (mean.cpu().double() * 3 - cross_entropy.mean()).abs() > 0.05 * cross_entropy.mean()
+ # binary: a target entry equal to -100 is zero-weighted the same way
+ target = (labels[:, None] > 0).to(dtype).expand(-1, 2, -1, -1).clone()
+ target[:, 0][ignored.to(device)] = -100
+ out = kornia.losses.binary_focal_loss_with_logits(logits[:, :2], target, None, gamma=0.0)
+ assert (out[target == -100] == 0).all()
+ target = target.cpu().double()
+ bce = F.binary_cross_entropy_with_logits(logits[:, :2].cpu().double(), target, reduction="none")
+ mean = kornia.losses.binary_focal_loss_with_logits(logits[:, :2], target.to(device, dtype), None, 0.0, "mean")
+ self.assert_close(mean, (bce[target != -100].sum() / target.numel()).to(device=device, dtype=dtype))
+
+ def test_convention_focal_loss_two_class_target_slice_is_binary_focal_loss(self, device, dtype):
+ # With C = 2, logits [z0, z1] and class 1 the positive class, the target slice of focal_loss is
+ # binary_focal_loss_with_logits(z1 - z0): alpha weights class 1 in both
+ logits, labels = self._logits_and_labels(device, dtype, scale=2.0)
+ labels = labels.clamp_max(1)
+ multiclass = kornia.losses.focal_loss(logits[:, :2], labels, 0.25).gather(1, labels[:, None])
+ binary = kornia.losses.binary_focal_loss_with_logits(logits[:, 1:2] - logits[:, :1], labels[:, None].to(dtype))
+ self.assert_close(multiclass, binary)
+
+ def test_convention_binary_focal_loss_matches_sigmoid_focal_loss_on_hard_targets(self, device, dtype):
+ # alpha weights the positive term and 1 - alpha the negative one, and the function defaults to alpha = 0.25,
+ # gamma = 2, reduction 'none'. Snippet used to generate expected (torchvision 0.29.0, torch 2.14.0, float64):
+ # torchvision.ops.sigmoid_focal_loss(z, t, alpha=0.25, gamma=2.0, reduction="none")
+ z = torch.tensor(
+ [[[[-2.0, -0.5, 0.0], [0.75, 1.5, 3.0]], [[2.5, -1.25, 0.25], [-3.0, 1.0, -0.75]]]],
+ device=device,
+ dtype=dtype,
+ )
+ t = torch.tensor(
+ [[[[1.0, 0.0, 1.0], [0.0, 1.0, 1.0]], [[0.0, 0.0, 1.0], [1.0, 0.0, 1.0]]]], device=device, dtype=dtype
+ )
+ expected = torch.tensor(
+ [
+ [
+ [[0.41252, 0.0506801, 0.0433217], [0.393315, 0.00167571, 2.73208e-05]],
+ [[1.65185, 0.00937088, 0.0276004], [0.69157, 0.526401, 0.131105]],
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ self.assert_close(kornia.losses.binary_focal_loss_with_logits(z, t), expected)
+
+ def test_convention_binary_focal_loss_fractional_target_mixes_the_two_terms(self, device, dtype):
+ # A target t in (0, 1) weights the positive term by t and the negative term by 1 - t:
+ # t alpha (1 - p)^gamma (-log p) + (1 - t) (1 - alpha) p^gamma (-log(1 - p)).
+ # torchvision's sigmoid_focal_loss applies alpha_t (1 - p_t)^gamma to the whole BCE instead; at t = 0.3 with the
+ # defaults alpha = 0.25, gamma = 2 it gives 0.0611245, 0.1039721, 0.2952082 for z = -1, 0, 1.5 (torchvision
+ # 0.29.0, torch 2.14.0, float64); the two agree at t in {0, 1}. Snippet used to generate those values:
+ # torchvision.ops.sigmoid_focal_loss(z, torch.full_like(z, 0.3), alpha=0.25, gamma=2.0, reduction="none")
+ z = torch.tensor([[-1.0, 0.0, 1.5]], dtype=torch.float64)
+ p = z.sigmoid()
+ expected = 0.3 * 0.25 * (1 - p) ** 2 * -p.log() + 0.7 * 0.75 * p**2 * -(1 - p).log()
+ actual = kornia.losses.binary_focal_loss_with_logits(
+ z.to(device, dtype), torch.full_like(z, 0.3).to(device, dtype)
+ )
+ self.assert_close(actual, expected.to(device, dtype))
+ assert (actual[0, 2].cpu().double() - 0.2952082).abs() > 0.1
+
+ def test_convention_binary_focal_loss_pos_weight_runs_along_the_channel_axis(self, device, dtype):
+ # pos_weight (C,) scales channel c's positive term: with gamma = 0 and alpha = None the loss is
+ # binary_cross_entropy_with_logits(pos_weight=pos_weight.view(C, 1, 1)); torch broadcasts a (C,) pos_weight
+ # along the last axis instead
+ logits, labels = self._logits_and_labels(device, dtype)
+ logits = logits[:, :2]
+ target = torch.stack([labels == 1, labels == 2], 1).to(dtype)
+ pos_weight = torch.tensor([3.0, 0.5], device=device, dtype=dtype)
+ actual = kornia.losses.binary_focal_loss_with_logits(logits, target, None, 0.0, pos_weight=pos_weight)
+ expected = F.binary_cross_entropy_with_logits(
+ logits.cpu().double(),
+ target.cpu().double(),
+ pos_weight=torch.tensor([3.0, 0.5]).double().view(2, 1, 1),
+ reduction="none",
+ )
+ self.assert_close(actual, expected.to(device=device, dtype=dtype))
+
+ def test_wart_focal_loss_overflowing_non_target_log_probability_5628(self, device, dtype):
+ # A logit gap beyond the range of the dtype overflows a non-target log-probability to -inf, and its term times
+ # the exact zero of the one-hot target is 0 * -inf = NaN (#5628): that slice, the reduced loss and the gradient
+ # of that pixel's logits are NaN, while the target slice is 0 and the other pixel stays finite
+ big = 0.75 * torch.finfo(dtype).max
+ logits = torch.tensor([[[[big, 1.0]], [[-big, -0.5]], [[0.0, 0.3]]]], device=device, dtype=dtype)
+ logits.requires_grad_()
+ labels = torch.zeros(1, 1, 2, device=device, dtype=torch.long)
+ out = kornia.losses.focal_loss(logits, labels, None)
+ assert out[0, 1, 0, 0].isnan()
+ assert out[0, 0, 0, 0] == 0
+ assert out[0, :, 0, 1].isfinite().all()
+ total = kornia.losses.focal_loss(logits, labels, None, reduction="sum")
+ assert total.isnan()
+ (grad,) = torch.autograd.grad(total, logits)
+ assert grad[..., 0].isnan().all()
+ assert grad[..., 1].isfinite().all()
diff --git a/tests/losses/test_hd.py b/tests/losses/test_hd.py
index 38bc4cdf8..dbc368603 100644
--- a/tests/losses/test_hd.py
+++ b/tests/losses/test_hd.py
@@ -178,3 +178,48 @@ class TestHausdorffLoss(BaseTester):
loss = hd(k=2)
self.gradcheck(loss, (logits, labels), dtypes=[torch.float64, torch.int64])
+
+
+class TestConventionsHausdorffERLoss(BaseTester):
+ """Pins for the input form, output layout and per-image scoring of the Hausdorff erosion losses."""
+
+ @pytest.mark.parametrize(
+ "hd,spatial", [(kornia.losses.HausdorffERLoss, (9, 13)), (kornia.losses.HausdorffERLoss3D, (5, 7, 9))]
+ )
+ def test_convention_hausdorff_er_loss_none_is_class_first_and_channel_c_scores_label_c(
+ self, hd, spatial, device, dtype
+ ):
+ # pred holds per-class probabilities and nothing is applied to it; channel c is compared with target == c,
+ # class 0 included, and reduction='none' returns (C, B, 1, *spatial), class axis first; the default 'mean' is
+ # the plain mean of that tensor
+ labels = torch.zeros(2, 1, *spatial, dtype=torch.long, device=device)
+ labels[0, 0, ..., 1:4, 1:4] = 1
+ labels[0, 0, ..., 3:6, 5:8] = 2
+ labels[1, 0, ..., 2:6, 4:8] = 1
+ labels[1, 0, ..., 0:2, 0:3] = 2
+ pred = (labels == torch.arange(3, device=device).view(1, 3, *[1] * len(spatial))).to(dtype)
+ none = hd(reduction="none")
+ self.assert_close(none(pred, labels), torch.zeros(3, 2, 1, *spatial, device=device, dtype=dtype))
+ pred[1, 0, ..., 3:6, 0:4] = 1 - pred[1, 0, ..., 3:6, 0:4] # a 3 x 4 error in class 0 of image 1
+ pred[0, 2, ..., 0:3, 5:8] = 1 - pred[0, 2, ..., 0:3, 5:8] # a 3 x 3 error in class 2 of image 0
+ out = none(pred, labels)
+ assert out.shape == (3, 2, 1, *spatial)
+ assert (out.flatten(2).sum(-1) > 0).tolist() == [[False, True], [False, False], [True, False]]
+ self.assert_close(hd()(pred, labels), out.mean())
+
+ @pytest.mark.parametrize(
+ "hd,spatial", [(kornia.losses.HausdorffERLoss, (9, 13)), (kornia.losses.HausdorffERLoss3D, (5, 7, 9))]
+ )
+ def test_convention_hausdorff_er_loss_scores_each_image_on_its_own(self, hd, spatial, device, dtype):
+ # The erosions are min-max normalised per image and class, so an image's 'none' slice does not depend on the
+ # other images of the batch: a thin error (image 0) and a thick one (image 1), scored together and alone
+ labels = torch.zeros(2, 1, *spatial, dtype=torch.long, device=device)
+ labels[0, 0, ..., 1:4, 1:4] = 1
+ labels[1, 0, ..., 2:6, 4:8] = 1
+ pred = (labels == torch.arange(2, device=device).view(1, 2, *[1] * len(spatial))).to(dtype)
+ pred[0, 1, ..., 2:3, 1:4] = 0.0 # image 0 misses one row of its object: a thin error
+ pred[1, 1, ..., 2:6, 4:8] = 0.0 # image 1 misses its whole object
+ none = hd(reduction="none")
+ batch = none(pred, labels)
+ self.assert_close(batch[:, :1], none(pred[:1], labels[:1]))
+ self.assert_close(batch[:, 1:], none(pred[1:], labels[1:]))
diff --git a/tests/losses/test_lovaz_hinge.py b/tests/losses/test_lovaz_hinge.py
index 6cc9df39b..174c4f5e3 100644
--- a/tests/losses/test_lovaz_hinge.py
+++ b/tests/losses/test_lovaz_hinge.py
@@ -179,3 +179,52 @@ class TestLovaszHingeLoss(BaseTester):
op_module = kornia.losses.LovaszHingeLoss()
self.assert_close(op(logits, labels), op_module(logits, labels))
+
+
+class TestConventionsLovaszHingeLoss(BaseTester):
+ """Pins for the batch reduction, value and target handling of :func:`lovasz_hinge_loss`."""
+
+ @staticmethod
+ def _logits_and_labels(device, dtype):
+ g = torch.Generator().manual_seed(0)
+ logits = torch.randn(2, 1, 4, 6, generator=g).to(device=device, dtype=dtype)
+ labels = torch.zeros(2, 4, 6, dtype=torch.long, device=device)
+ labels[0, 1:3, 1:3] = 1 # 4 foreground pixels in image 0, 15 in image 1
+ labels[1, 1:, 1:] = 1
+ return logits, labels
+
+ def test_convention_lovasz_hinge_loss_averages_per_image(self, device, dtype):
+ # One LovĂĄsz hinge per image, averaged over the batch (Berman's lovasz_hinge(per_image=True)); the batch
+ # flattened into one image (per_image=False) gives another value
+ logits, labels = self._logits_and_labels(device, dtype)
+ loss = kornia.losses.lovasz_hinge_loss
+ per_image = (loss(logits[:1], labels[:1]) + loss(logits[1:], labels[1:])) / 2
+ self.assert_close(loss(logits, labels), per_image)
+ flattened = loss(torch.cat([logits[0], logits[1]], -1)[None], torch.cat([labels[0], labels[1]], -1)[None])
+ assert (flattened - per_image).abs() > 0.02
+
+ def test_convention_lovasz_hinge_loss_unit_margin_logits_give_twice_the_jaccard_loss(self, device, dtype):
+ # The loss is the LovĂĄsz extension of the Jaccard loss at the hinge errors relu(1 - z (2t - 1)), not 1 - IoU:
+ # with logits of magnitude 1 every wrong pixel has error 2, so the loss is 2 (1 - IoU); confidently correct
+ # logits give 0
+ labels = torch.zeros(1, 4, 6, dtype=torch.long, device=device)
+ labels[0, 1:3, 1:5] = 1 # 8 foreground pixels
+ predicted = labels.clone()
+ predicted[0, 1, 1] = 0 # one false negative
+ predicted[0, 3, 4:] = 1 # two false positives
+ iou = (predicted & labels).sum() / (predicted | labels).sum() # 7 / 10
+ logits = (2.0 * predicted - 1.0)[:, None].to(dtype)
+ loss = kornia.losses.lovasz_hinge_loss(logits, labels)
+ self.assert_close(loss, (2 * (1 - iou)).to(dtype))
+ confident = (10.0 * (2 * labels - 1))[:, None].to(dtype)
+ self.assert_close(kornia.losses.lovasz_hinge_loss(confident, labels), torch.zeros_like(loss))
+
+ def test_convention_lovasz_hinge_loss_does_not_validate_the_target(self, device, dtype):
+ # The target is not checked to be binary and there is no ignore_index: a label of 2 or -100 is accepted, and
+ # -100 (the siblings' ignore_index) enters the hinge as a large negative sign that can make the loss negative,
+ # as it does on this fixture
+ logits, labels = self._logits_and_labels(device, dtype)
+ labels[:, 0, :2] = 2
+ assert kornia.losses.lovasz_hinge_loss(logits, labels).isfinite()
+ labels[:, 0, :2] = -100
+ assert kornia.losses.lovasz_hinge_loss(logits, labels) < 0
diff --git a/tests/losses/test_lovaz_softmax.py b/tests/losses/test_lovaz_softmax.py
index 9895f660b..9ebe9fee9 100644
--- a/tests/losses/test_lovaz_softmax.py
+++ b/tests/losses/test_lovaz_softmax.py
@@ -280,3 +280,49 @@ class TestLovaszSoftmaxLoss(BaseTester):
op_module = kornia.losses.LovaszSoftmaxLoss()
self.assert_close(op(logits, labels), op_module(logits, labels))
+
+
+class TestConventionsLovaszSoftmaxLoss(BaseTester):
+ """Pins for the batch, class and weight reduction of :func:`lovasz_softmax_loss`."""
+
+ @staticmethod
+ def _logits_and_labels(device, dtype):
+ g = torch.Generator().manual_seed(0)
+ logits = torch.randn(2, 4, 4, 6, generator=g)
+ labels = torch.randint(0, 3, (2, 4, 6), generator=g)
+ labels[1, 1:3, 2:5] = 3 # class 3 is absent from image 0
+ logits = logits + 3.0 * (labels[:, None] == torch.arange(4)[:, None, None])
+ logits[0, 3, 0, :2] += 6.0 # image 0 predicts the absent class 3 on two pixels
+ return logits.to(device=device, dtype=dtype), labels.to(device)
+
+ def test_convention_lovasz_softmax_loss_averages_all_classes_per_image(self, device, dtype):
+ # Berman's lovasz_softmax(softmax(pred), classes='all', per_image=True): each image is scored on its own (the
+ # batch flattened into one image, per_image=False, gives another value), and a class absent from an image
+ # still enters that image's mean over the C classes, with the image's largest probability for it (Berman's
+ # default classes='present' skips it)
+ logits, labels = self._logits_and_labels(device, dtype)
+ loss = kornia.losses.lovasz_softmax_loss
+ per_image = (loss(logits[:1], labels[:1]) + loss(logits[1:], labels[1:])) / 2
+ self.assert_close(loss(logits, labels), per_image)
+ flattened = loss(torch.cat([logits[0], logits[1]], -1)[None], torch.cat([labels[0], labels[1]], -1)[None])
+ assert (flattened - per_image).abs() > 0.02
+ image_0 = logits[:1].cpu(), labels[:1].cpu()
+ without_class_3 = _lovasz_softmax_reference(*image_0, torch.tensor([1.0, 1.0, 1.0, 0.0]))
+ largest_p_3 = image_0[0].double().softmax(1)[:, 3].max()
+ expected = without_class_3 + largest_p_3 / 4
+ self.assert_close(loss(logits[:1], labels[:1]), expected.to(device=device, dtype=dtype))
+ assert largest_p_3 / 4 - without_class_3 / 3 > 0.1 # the mean over the present classes would differ
+
+ def test_convention_lovasz_softmax_loss_weight_is_not_normalised(self, device, dtype):
+ # weight scales each class's term and the mean over classes still divides by C, not by sum(weight): a uniform
+ # weight of 2 doubles the loss, where dice_loss 'macro' divides by sum(weight)
+ logits, labels = self._logits_and_labels(device, dtype)
+ loss = kornia.losses.lovasz_softmax_loss
+ self.assert_close(
+ loss(logits, labels, torch.full((4,), 2.0, device=device, dtype=dtype)), 2 * loss(logits, labels)
+ )
+ weight = torch.tensor([1.0, 2.0, 3.0, 4.0], device=device, dtype=dtype)
+ one_class = torch.eye(4, device=device, dtype=dtype)
+ self.assert_close(
+ loss(logits, labels, weight), sum(w * loss(logits, labels, e) for w, e in zip(weight, one_class))
+ )
diff --git a/tests/losses/test_one_hot.py b/tests/losses/test_one_hot.py
index b78cd267d..263645923 100644
--- a/tests/losses/test_one_hot.py
+++ b/tests/losses/test_one_hot.py
@@ -22,7 +22,7 @@ import torch.nn.functional as F
from kornia.core.exceptions import BaseError
from kornia.losses.one_hot import one_hot
-from testing.base import assert_close
+from testing.base import BaseTester, assert_close
class TestOneHot:
@@ -74,3 +74,19 @@ class TestOneHot:
with pytest.raises(BaseError, match="floating point dtype"):
one_hot(labels, 2, device, torch.int64, eps=1e-6)
+
+
+class TestConventionsOneHot(BaseTester):
+ """Pins for the layout of :func:`kornia.losses.one_hot`."""
+
+ def test_convention_one_hot_class_axis_is_dim_1(self, device, dtype):
+ # int64 labels (N, *) -> (N, C, *): the class axis is dim 1 where F.one_hot puts it last, and with the default
+ # eps=0 the result is F.one_hot(labels, C).movedim(-1, 1).to(device, dtype)
+ labels = torch.tensor([[[0, 2, 1, 3, 3], [1, 0, 0, 2, 0], [3, 3, 1, 0, 2]]], device=device)
+ labels = torch.cat([labels, labels.flip(-1)]) # (2, 3, 5)
+ out = one_hot(labels, 4, device, dtype)
+ assert out.shape == (2, 4, 3, 5)
+ assert torch.equal(out, F.one_hot(labels, 4).movedim(-1, 1).to(dtype))
+ assert torch.equal(one_hot(labels.transpose(1, 2), 4, device, dtype), out.transpose(2, 3))
+ assert one_hot(labels[:, 0, 0], 4, device, dtype).shape == (2, 4)
+ assert one_hot(labels.cpu(), 4, torch.device("meta"), dtype).device.type == "meta"
diff --git a/tests/losses/test_tversky.py b/tests/losses/test_tversky.py
index 119e7a819..953c364ec 100644
--- a/tests/losses/test_tversky.py
+++ b/tests/losses/test_tversky.py
@@ -312,3 +312,41 @@ class TestTverskyLoss(BaseTester):
actual = op_module(logits, labels)
expected = op(logits, labels, *params)
self.assert_close(actual, expected)
+
+
+class TestConventionsTverskyLoss(BaseTester):
+ """Pins for the ignored labels and the Dice correspondence of :func:`tversky_loss`."""
+
+ def test_convention_tversky_loss_ignore_index_excludes_pixels_per_sample(self, device, dtype):
+ # Ignored pixels leave the sums of their own sample, which then enters the batch mean like the others: the same
+ # as cropping them out of that sample. An image whose pixels are all ignored enters the batch mean as loss 1.
+ def tversky(logits, labels):
+ return kornia.losses.tversky_loss(logits, labels, 0.3, 0.7)
+
+ g = torch.Generator().manual_seed(0)
+ logits = torch.randn(2, 3, 4, 7, generator=g).to(device=device, dtype=dtype)
+ labels = torch.randint(0, 3, (2, 4, 7), generator=g).to(device)
+ ignored = labels.clone()
+ ignored[0, :, -3:] = -100 # image 0 loses its last three columns
+ expected = (tversky(logits[:1, ..., :-3], labels[:1, :, :-3]) + tversky(logits[1:], labels[1:])) / 2
+ self.assert_close(tversky(logits, ignored), expected)
+ ignored[0] = -100
+ self.assert_close(tversky(logits, ignored), (1 + tversky(logits[1:], labels[1:])) / 2)
+
+ def test_convention_tversky_loss_half_half_is_macro_dice_with_twice_the_eps_5543(self, device, dtype):
+ # alpha = beta = 0.5 turns TP / (TP + alpha FP + beta FN + eps) into 2 TP / (2 TP + FP + FN + 2 eps), the
+ # per-class Dice with twice the eps, averaged as dice_loss(average='macro') averages it: per class, over the
+ # classes present in each sample's non-ignored target (#5543). Class 1 is absent from image 1 and three of its
+ # pixels are ignored; the pooled 'micro' Dice is another value.
+ g = torch.Generator().manual_seed(0)
+ logits = torch.randn(2, 3, 4, 6, generator=g).to(device=device, dtype=dtype)
+ labels = torch.randint(0, 3, (2, 4, 6), generator=g)
+ labels[1][labels[1] == 1] = 2
+ labels[1, 0, :3] = -100
+ labels = labels.to(device)
+ dice = kornia.losses.dice_loss
+ tversky = kornia.losses.tversky_loss(logits, labels, 0.5, 0.5)
+ self.assert_close(tversky, dice(logits, labels, average="macro", eps=2e-8))
+ assert (tversky - dice(logits, labels)).abs() > 0.01
+ tversky = kornia.losses.tversky_loss(logits, labels, 0.5, 0.5, eps=1.0)
+ self.assert_close(tversky, dice(logits, labels, average="macro", eps=2.0))