Semantic segmentation#

The multi-class losses take class logits (B, C, H, W) and a label map (B, H, W), and apply the softmax themselves. dice_loss() and tversky_loss() optimise the class overlap, lovasz_softmax_loss() the IoU of every class, and lovasz_hinge_loss() the IoU of one foreground, from one logit channel. focal_loss() is a cross entropy over logits (B, C, *) that down-weights easy pixels, and binary_focal_loss_with_logits() is the same for independent sigmoid outputs, against targets of their shape. one_hot() turns a label map into a one-hot tensor.

Functions#

kornia.losses.one_hot(labels, num_classes, device, dtype, eps=0.0)[source]#

Convert int64 class labels (N, *) to a one-hot tensor (N, C, *).

onehot = one_hot(labels, num_classes, device, dtype) puts a 1 at each label’s class and 0 elsewhere.

Convention:
  • The class axis is dim 1, where 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).

  • Kornia does not validate the labels: a label outside [0, num_classes) raises a RuntimeError from torch on the CPU in eager mode.

Parameters:
  • labels (Tensor) – int64 class labels (N, *) in [0, num_classes).

  • num_classes (int) – number of classes C.

  • device (device) – device of the result.

  • dtype (dtype) – data type of the result.

  • eps (float, optional) – smoothing floor. The default 0 returns the exact one-hot. A non-zero value replaces the zeros with eps and keeps the ones, which needs a floating point dtype. Default: 0.0

Return type:

Tensor

Returns:

the one-hot tensor (N, C, *).

See also

  • dice_loss(): the segmentation losses take int64 class indices, not this tensor.

Examples

>>> labels = torch.LongTensor([[[0, 1], [2, 0]]])
>>> one_hot(labels, num_classes=3, device=torch.device('cpu'), dtype=torch.float32)
tensor([[[[1., 0.],
          [0., 1.]],

         [[0., 1.],
          [0., 0.]],

         [[0., 0.],
          [1., 0.]]]])
kornia.losses.binary_focal_loss_with_logits(pred, target, alpha=0.25, gamma=2.0, reduction='none', pos_weight=None, weight=None, ignore_index=-100)[source]#

Compute the binary focal loss of (B, C, *) logits against same-shape targets in [0, 1], using sigmoid.

loss = binary_focal_loss_with_logits(pred, target) scales the binary cross entropy of each logit by \(\alpha_t (1 - p_t)^{\gamma}\) [LGG+18], so that elements the sigmoid already classifies well count less. For a target of 0 or 1, \(p_t\) is the sigmoid probability of the target value, and \(\alpha_t\) is alpha for a target of 1 and 1 - alpha for a target of 0.

\[\text{FL}(p_t) = -\alpha_t (1 - p_t)^{\gamma} \, \text{log}(p_t)\]
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]. 'mean' and 'sum' reduce the loss map as in focal_loss().

  • alpha defaults to 0.25. A fractional target \(t\) weights the two terms by \(t\) and \(1 - t\): \(t \alpha (1 - p)^\gamma (-\log p) + (1 - t) (1 - \alpha) p^\gamma (-\log (1 - p))\), where \(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 with zero logit gradient, including for non-finite ignored logits, and still counts in the 'mean' denominator, as in focal_loss().

  • Losses and metrics maps this loss onto torchvision’s sigmoid_focal_loss and torch’s pos_weight.

Parameters:
  • pred (Tensor) – logits (B, C, *).

  • target (Tensor) – targets in [0, 1] with the shape of pred, or ignore_index.

  • alpha (Optional[float], optional) – weight \(\alpha \in [0, 1]\) of the positive term; None weights both terms by 1. Default: 0.25

  • gamma (float, optional) – focusing exponent \(\gamma \ge 0\). Default: 2.0

  • reduction (str, optional) – 'none' (default) keeps the map of pred’s shape, 'mean' averages it, 'sum' adds it. Default: "none"

  • pos_weight (Optional[Tensor], optional) – weight of the positive term of each channel (C,). Default: None

  • weight (Optional[Tensor], optional) – channel weights (C,). Default: None

  • ignore_index (Optional[int], optional) – target value whose entries contribute 0 but stay in the 'mean' denominator. Default: -100

Return type:

Tensor

Returns:

the loss, a map with the shape of pred for reduction='none' and a scalar otherwise.

See also

Examples

>>> C = 3  # num_classes
>>> pred = torch.randn(1, C, 5, requires_grad=True)
>>> target = torch.randint(2, (1, C, 5))
>>> kwargs = {"alpha": 0.25, "gamma": 2.0, "reduction": 'mean'}
>>> output = binary_focal_loss_with_logits(pred, target, **kwargs)
>>> output.backward()
kornia.losses.focal_loss(pred, target, alpha, gamma=2.0, reduction='none', weight=None, ignore_index=-100)[source]#

Compute the multi-class focal loss of (B, C, *) logits against (B, *) class indices, using softmax.

loss = focal_loss(pred, target, alpha) scales the cross entropy \(-\log p_t\) of each pixel’s target class by \(\alpha_t (1 - p_t)^{\gamma}\) [LGG+18], so that pixels the softmax already classifies well count less. \(p_t\) is the softmax probability of the target class and \(\alpha_t\) the class weight set by alpha.

\[\text{FL}(p_t) = -\alpha_t (1 - p_t)^{\gamma} \, \text{log}(p_t)\]
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 \(1 - \alpha\) and classes \(1, \dots, C - 1\) by \(\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 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 'none' map holds the focal term above in the target-class slice and 0 in the other slices, also where their log-probability overflows to -inf. '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 dice_loss() and tversky_loss() drop it. Losses and metrics ports cross_entropy() to this loss.

  • alpha outside [0, 1] and a negative gamma are not validated.

  • On the CPU, 'mean' and 'sum' without weight, with a finite gamma >= 0 and alpha None or a number in [0, 1], of float32 or float64 logits with at least \(2^{19}\) values compute the target-class log-probability with a custom autograd function, a batch chunk at a time, instead of a full-size log_softmax, unless torch.export or torch.jit.trace captures the call, a functorch transform or forward-mode AD runs, or autocast is on. It agrees with log_softmax to rounding, with the same NaN and infinity positions and a zero gradient at ignored pixels, and supports double backward.

Parameters:
  • pred (Tensor) – logits (B, C, *).

  • target (Tensor) – int64 class indices (B, *) in [0, C), or ignore_index.

  • alpha (Optional[float]) – weight \(\alpha \in [0, 1]\) of classes \(1, \dots, C - 1\); None weights every class by 1.

  • gamma (float, optional) – focusing exponent \(\gamma \ge 0\). Default: 2.0

  • reduction (str, optional) – 'none' (default) keeps the (B, C, *) map, 'mean' averages it, 'sum' adds it. Default: "none"

  • weight (Optional[Tensor], optional) – class weights (C,). Default: None

  • ignore_index (Optional[int], optional) – label whose pixels contribute 0 but stay in the 'mean' denominator. Default: -100

Return type:

Tensor

Returns:

the loss, a (B, C, *) map for reduction='none' and a scalar otherwise.

See also

Example

>>> C = 5  # num_classes
>>> pred = torch.randn(1, C, 3, 5, requires_grad=True)
>>> target = torch.randint(C, (1, 3, 5))
>>> kwargs = {"alpha": 0.5, "gamma": 2.0, "reduction": 'mean'}
>>> output = focal_loss(pred, target, **kwargs)
>>> output.backward()
kornia.losses.dice_loss(pred, target, average='micro', eps=1e-8, weight=None, ignore_index=-100)[source]#

Compute the Sørensen-Dice loss of (B, C, H, W) logits against (B, H, W) class indices.

loss = dice_loss(pred, target) is one minus the Dice overlap [1] between the softmax of pred over the classes (\(X\)) and the one-hot target (\(Y\)), averaged over the batch.

\[\text{loss} = 1 - \frac{2 |X \cap Y|}{|X| + |Y|}\]
Reference:

[1] https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient

Convention:
  • pred and target are those of 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: \(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 \(\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; there is no reduction.

  • eps is added to the denominator only: \(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 with a zero gradient, at eps=0 as well.

  • On the CPU, float32 or float64 logits with at least \(2^{15}\) values and a weight that is None or of their dtype skip the one-hot target, unless torch.export or torch.jit.trace captures the call, a functorch transform runs or autocast is on: the intersection takes each pixel’s target-class probability, 'micro' sums the (weighted) probabilities of each pixel over the classes, and 'macro' takes the probability mass of each class from a batched matrix-vector product and adds the per-class sums into (B, C) bins, so no full-size product with a one-hot target is formed. The result agrees with the one-hot sums to rounding, with the same NaN positions; a label outside [0, C) that is not ignore_index raises the same RuntimeError as one_hot, also under torch.compile. Some torch releases (2.5.1 and 2.9.1 among them) report a torch.compile capture as an export: a compiled call keeps the one-hot target there, and its compiled one_hot does not check the labels.

Parameters:
  • pred (Tensor) – logits (B, C, H, W).

  • target (Tensor) – int64 class indices (B, H, W) in [0, C), or ignore_index.

  • average (str, optional) – 'micro' (default) or 'macro'. Default: "micro"

  • eps (float, optional) – term added to the denominator, non-negative. Default: 1e-8

  • weight (Optional[Tensor], optional) – class weights (C,); None weights every class by 1. Default: None

  • ignore_index (Optional[int], optional) – label whose pixels are left out; None ignores no label. Default: -100

Return type:

Tensor

Returns:

the loss, a 0-d tensor.

Note

Spatial reductions use float32 for float16 and bfloat16 inputs to avoid overflow on large images. The returned loss retains the usual dtype promotion between the inputs and class weights.

See also

  • DiceLoss: the module form.

  • tversky_loss(): weights false positives and false negatives separately; averages the classes present in each sample, as 'macro' does.

  • lovasz_softmax_loss(): optimises the IoU instead of the Dice overlap.

  • focal_loss(): a per-pixel cross entropy that down-weights easy pixels, not an overlap.

Example

>>> N = 5  # num_classes
>>> pred = torch.randn(1, N, 3, 5, requires_grad=True)
>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
>>> output = dice_loss(pred, target)
>>> output.backward()
kornia.losses.tversky_loss(pred, target, alpha, beta, eps=1e-8, ignore_index=-100)[source]#

Compute the Tversky loss of (B, C, H, W) logits against (B, H, W) class indices.

loss = tversky_loss(pred, target, alpha, beta) is one minus the Tversky index [SEG17] of the softmax of pred over the classes (\(P\)) and the one-hot target (\(G\)) on the non-ignored pixels. alpha weights the false positives \(P \setminus G\) and beta the false negatives \(G \setminus P\).

\[\text{loss} = 1 - \frac{|PG|}{|PG| + \alpha |P \setminus G| + \beta |G \setminus P|}\]
Convention:
  • pred, target and ignore_index behave as in 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; a sample whose pixels are all ignored enters the batch mean as loss 1. There is no weight, average or reduction.

  • \(\alpha = \beta = 0.5\) gives dice_loss(average='macro', eps=2 * eps), and \(\alpha = \beta = 1\) the per-class Tanimoto coefficient. For \(\alpha + \beta = 1\) and \(\alpha > 0\), the unsmoothed per-class score is \(F_{\sqrt{\beta / \alpha}}\).

Parameters:
  • pred (Tensor) – logits (B, C, H, W).

  • target (Tensor) – int64 class indices (B, H, W) in [0, C), or ignore_index.

  • alpha (float) – weight of the false positives, non-negative and finite.

  • beta (float) – weight of the false negatives, non-negative and finite.

  • eps (float, optional) – term added to the denominator, non-negative and finite. Default: 1e-8

  • ignore_index (Optional[int], optional) – label whose pixels are left out; None ignores no label. Default: -100

Return type:

Tensor

Returns:

the loss, a 0-d tensor.

Note

Softmax, spatial reductions and the ratio use float32 for float16 and bfloat16 inputs to avoid overflow in large-image sums and ratio gradients. The returned loss retains the input dtype.

See also

  • TverskyLoss: the module form.

  • dice_loss(): weights false positives and false negatives equally; adds average and class weight.

Example

>>> N = 5  # num_classes
>>> pred = torch.randn(1, N, 3, 5, requires_grad=True)
>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
>>> output = tversky_loss(pred, target, alpha=0.5, beta=0.5)
>>> output.backward()
kornia.losses.lovasz_hinge_loss(pred, target)[source]#

Compute the binary Lovász-hinge IoU loss of (B, 1, H, W) logits against (B, H, W) labels.

loss = lovasz_hinge_loss(pred, target) optimises the intersection over union (IoU) of two foregrounds: the one predicted by the single logit channel of pred (\(X\)) and the one labelled in target (\(Y\)). It minimises the Lovász extension [1] of the Jaccard loss [2].

\[\Delta_J = 1 - \frac{|X \cap Y|}{|X \cup Y|}\]
Reference:

[1] http://proceedings.mlr.press/v37/yub15.pdf [2] https://arxiv.org/pdf/1705.08790.pdf

Convention:
  • pred holds one logit channel and target labels of 1 for the foreground and 0 for the background; the batch and spatial sizes must match. The loss is computed per image and averaged over the batch; there is no reduction.

  • The extension is evaluated at the hinge errors \(\max(0, 1 - z (2t - 1))\) of logit \(z\) and label \(t\), so the loss is not \(1 - \text{IoU}\): logits of \(\pm 1\) that are positive on the predicted foreground give \(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 focal_loss() and dice_loss(), can make the loss negative.

Parameters:
  • pred (Tensor) – logits (B, 1, H, W).

  • target (Tensor) – binary labels (B, H, W).

Return type:

Tensor

Returns:

a scalar with the computed loss, in the dtype of a floating-point pred and in float32 for an integer or bool pred. The Jaccard weights and the sum over pixels are computed in float32 for a float16 or bfloat16 pred.

See also

Example

>>> N = 1  # num_classes
>>> pred = torch.randn(1, N, 3, 5, requires_grad=True)
>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
>>> output = lovasz_hinge_loss(pred, target)
>>> output.backward()
kornia.losses.lovasz_softmax_loss(pred, target, weight=None)[source]#

Compute the multi-class Lovász-softmax IoU loss of (B, C, H, W) logits against (B, H, W) class indices.

loss = lovasz_softmax_loss(pred, target) optimises the intersection over union (IoU) of every class: the softmax of pred over the classes (\(X\)) against the one-hot target (\(Y\)). It averages over the classes the Lovász extension of the Jaccard loss of each class [1], evaluated at the errors \(|X - Y|\).

\[\Delta_J = 1 - \frac{|X \cap Y|}{|X \cup Y|}\]
Reference:

[1] https://arxiv.org/pdf/1705.08790.pdf

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) with the spatial size of pred. The batch sizes match, or pred holds one image, which is scored against every target. There is no ignore_index and the labels are not validated: a label of -100 is not ignored, and on the CPU in eager mode it raises a RuntimeError from torch.

  • Each image is scored on its own and the losses are averaged over the batch; 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.

Parameters:
  • pred (Tensor) – logits (B, C, H, W) with C >= 2.

  • target (Tensor) – class indices (B, H, W) in [0, C).

  • weight (Optional[Tensor], optional) – class weights (C,). Default: None

Return type:

Tensor

Returns:

a scalar with the computed loss, in the dtype of pred promoted with the dtype of weight. The Jaccard weights and the sum over pixels are computed in float32 for a float16 or bfloat16 pred.

See also

Example

>>> N = 5  # num_classes
>>> pred = torch.randn(1, N, 3, 5, requires_grad=True)
>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
>>> output = lovasz_softmax_loss(pred, target)
>>> output.backward()

Modules#

class kornia.losses.BinaryFocalLossWithLogits(alpha, gamma=2.0, reduction='none', pos_weight=None, weight=None, ignore_index=-100)[source]#

Compute the binary focal loss of (B, C, *) logits against same-shape targets in [0, 1] (module form).

criterion = BinaryFocalLossWithLogits(alpha, gamma, reduction, pos_weight, weight, ignore_index) stores its arguments, and loss = criterion(pred, target) is binary_focal_loss_with_logits(). A plain tensor pos_weight or weight is stored as a non-persistent buffer, so criterion.to(device) moves it and state_dict omits it.

Convention:

See the Convention block of binary_focal_loss_with_logits(). Unlike the function, alpha has no default here.

Parameters:
  • alpha (Optional[float]) – weight \(\alpha \in [0, 1]\) of the positive term; None weights both terms by 1.

  • gamma (float, optional) – focusing exponent \(\gamma \ge 0\). Default: 2.0

  • reduction (str, optional) – 'none' (default), 'mean' or 'sum', as in binary_focal_loss_with_logits(). Default: "none"

  • pos_weight (Optional[Tensor], optional) – weight of the positive term of each channel (C,). Default: None

  • weight (Optional[Tensor], optional) – channel weights (C,). Default: None

  • ignore_index (Optional[int], optional) – target value whose entries contribute 0 but stay in the 'mean' denominator. Default: -100

Shape:
  • pred: logits (B, C, *).

  • target: targets in [0, 1] with the shape of pred, or ignore_index.

  • Output: a map with the shape of pred for reduction='none', a scalar otherwise.

See also

Examples

>>> C = 3  # num_classes
>>> pred = torch.randn(1, C, 5, requires_grad=True)
>>> target = torch.randint(2, (1, C, 5))
>>> kwargs = {"alpha": 0.25, "gamma": 2.0, "reduction": 'mean'}
>>> criterion = BinaryFocalLossWithLogits(**kwargs)
>>> output = criterion(pred, target)
>>> output.backward()
class kornia.losses.DiceLoss(average='micro', eps=1e-8, weight=None, ignore_index=-100)[source]#

Compute the Sørensen-Dice loss of (B, C, H, W) logits against (B, H, W) class indices (module form).

criterion = DiceLoss(average, eps, weight, ignore_index) stores its arguments, and loss = criterion(pred, target) is dice_loss(). A plain tensor weight is stored as a non-persistent buffer, so criterion.to(device) moves it and state_dict omits it.

Convention:

See the Convention block of dice_loss().

Parameters:
  • average (str, optional) – 'micro' (default) or 'macro', as in dice_loss(). Default: "micro"

  • eps (float, optional) – term added to the denominator, non-negative. Default: 1e-8

  • weight (Optional[Tensor], optional) – class weights (C,); None weights every class by 1. Default: None

  • ignore_index (Optional[int], optional) – label whose pixels are left out; None ignores no label. Default: -100

Shape:
  • pred: logits (B, C, H, W).

  • target: int64 class indices (B, H, W) in [0, C), or ignore_index.

  • Output: a 0-d tensor.

See also

  • dice_loss(): the one-call form.

  • TverskyLoss: weights false positives and false negatives separately.

  • LovaszSoftmaxLoss: optimises the IoU instead of the Dice overlap.

  • FocalLoss: a per-pixel cross entropy that down-weights easy pixels, not an overlap.

Example

>>> criterion = DiceLoss()
>>> pred = torch.randn(1, 5, 3, 5, requires_grad=True)
>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(5)
>>> output = criterion(pred, target)
>>> output.backward()
class kornia.losses.TverskyLoss(alpha, beta, eps=1e-8, ignore_index=-100)[source]#

Compute the Tversky loss of (B, C, H, W) logits against (B, H, W) class indices (module form).

criterion = TverskyLoss(alpha, beta, eps, ignore_index) stores its arguments, and loss = criterion(pred, target) is tversky_loss().

Convention:

See the Convention block of tversky_loss().

Parameters:
  • alpha (float) – weight of the false positives, non-negative and finite.

  • beta (float) – weight of the false negatives, non-negative and finite.

  • eps (float, optional) – term added to the denominator, non-negative and finite. Default: 1e-8

  • ignore_index (Optional[int], optional) – label whose pixels are left out; None ignores no label. Default: -100

Shape:
  • pred: logits (B, C, H, W).

  • target: int64 class indices (B, H, W) in [0, C), or ignore_index.

  • Output: a 0-d tensor.

See also

  • tversky_loss(): the one-call form.

  • DiceLoss: weights false positives and false negatives equally; adds average and class weight.

Examples

>>> N = 5  # num_classes
>>> criterion = TverskyLoss(alpha=0.5, beta=0.5)
>>> pred = torch.randn(1, N, 3, 5, requires_grad=True)
>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
>>> output = criterion(pred, target)
>>> output.backward()
class kornia.losses.FocalLoss(alpha, gamma=2.0, reduction='none', weight=None, ignore_index=-100)[source]#

Compute the multi-class focal loss of (B, C, *) logits against (B, *) class indices (module form).

criterion = FocalLoss(alpha, gamma, reduction, weight, ignore_index) stores its arguments, and loss = criterion(pred, target) is focal_loss(). A plain tensor weight is stored as a non-persistent buffer, so criterion.to(device) moves it and state_dict omits it.

Convention:

See the Convention block of focal_loss().

Parameters:
  • alpha (Optional[float]) – weight \(\alpha \in [0, 1]\) of classes \(1, \dots, C - 1\); None weights every class by 1.

  • gamma (float, optional) – focusing exponent \(\gamma \ge 0\). Default: 2.0

  • reduction (str, optional) – 'none' (default), 'mean' or 'sum', as in focal_loss(). Default: "none"

  • weight (Optional[Tensor], optional) – class weights (C,). Default: None

  • ignore_index (Optional[int], optional) – label whose pixels contribute 0 but stay in the 'mean' denominator. Default: -100

Shape:
  • pred: logits (B, C, *).

  • target: int64 class indices (B, *) in [0, C), or ignore_index.

  • Output: a (B, C, *) map for reduction='none', a scalar otherwise.

See also

Example

>>> C = 5  # num_classes
>>> pred = torch.randn(1, C, 3, 5, requires_grad=True)
>>> target = torch.randint(C, (1, 3, 5))
>>> kwargs = {"alpha": 0.5, "gamma": 2.0, "reduction": 'mean'}
>>> criterion = FocalLoss(**kwargs)
>>> output = criterion(pred, target)
>>> output.backward()
class kornia.losses.LovaszHingeLoss[source]#

Compute the binary Lovász-hinge IoU loss of (B, 1, H, W) logits against (B, H, W) labels (module form).

criterion = LovaszHingeLoss() takes no arguments, and loss = criterion(pred, target) is lovasz_hinge_loss().

Convention:

See the Convention block of lovasz_hinge_loss().

Shape:
  • pred: logits (B, 1, H, W).

  • target: binary labels (B, H, W).

  • Output: a scalar.

See also

Example

>>> N = 1  # num_classes
>>> criterion = LovaszHingeLoss()
>>> pred = torch.randn(1, N, 3, 5, requires_grad=True)
>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
>>> output = criterion(pred, target)
>>> output.backward()
class kornia.losses.LovaszSoftmaxLoss(weight=None)[source]#

Compute the multi-class Lovász-softmax IoU loss of (B, C, H, W) logits against class indices (module form).

criterion = LovaszSoftmaxLoss(weight) stores weight, and loss = criterion(pred, target) is lovasz_softmax_loss(). A plain tensor weight is stored as a non-persistent buffer, so criterion.to(device) moves it and state_dict omits it.

Convention:

See the Convention block of lovasz_softmax_loss().

Parameters:

weight (Optional[Tensor], optional) – class weights (C,); None weights every class by 1. Default: None

Shape:
  • pred: logits (B, C, H, W) with C >= 2.

  • target: class indices (B, H, W) in [0, C).

  • Output: a scalar.

See also

Example

>>> N = 5  # num_classes
>>> criterion = LovaszSoftmaxLoss()
>>> pred = torch.randn(1, N, 3, 5, requires_grad=True)
>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
>>> output = criterion(pred, target)
>>> output.backward()