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 defaulteps=0.0the result isF.one_hot(labels, num_classes).movedim(-1, 1).to(device, dtype).Kornia does not validate the labels: a label outside
[0, num_classes)raises aRuntimeErrorfrom torch on the CPU in eager mode.
- Parameters:
labels (
Tensor) – int64 class labels(N, *)in[0, num_classes).num_classes (
int) – number of classesC.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 withepsand keeps the ones, which needs a floating pointdtype. Default:0.0
- Return type:
- 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\) isalphafor a target of 1 and1 - alphafor a target of 0.\[\text{FL}(p_t) = -\alpha_t (1 - p_t)^{\gamma} \, \text{log}(p_t)\]- Convention:
Every element of
predis an independent binary logit:predis(B, C, *)with at least two dimensions andtargethas its shape, with values in[0, 1].'mean'and'sum'reduce the loss map as infocal_loss().alphadefaults to0.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_weightandweightare(C,)vectors applied along dim 1:pos_weight[c]scales the positive term of channelcandweight[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 infocal_loss().Losses and metrics maps this loss onto torchvision’s
sigmoid_focal_lossand torch’spos_weight.
- Parameters:
pred (
Tensor) – logits(B, C, *).target (
Tensor) – targets in[0, 1]with the shape ofpred, orignore_index.alpha (
Optional[float], optional) – weight \(\alpha \in [0, 1]\) of the positive term;Noneweights both terms by 1. Default:0.25gamma (
float, optional) – focusing exponent \(\gamma \ge 0\). Default:2.0reduction (
str, optional) –'none'(default) keeps the map ofpred’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:Noneweight (
Optional[Tensor], optional) – channel weights(C,). Default:Noneignore_index (
Optional[int], optional) – target value whose entries contribute 0 but stay in the'mean'denominator. Default:-100
- Return type:
- Returns:
the loss, a map with the shape of
predforreduction='none'and a scalar otherwise.
See also
BinaryFocalLossWithLogits: the module form.focal_loss(): a softmax over the classes against class indices, for exclusive classes.
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 byalpha.\[\text{FL}(p_t) = -\alpha_t (1 - p_t)^{\gamma} \, \text{log}(p_t)\]- Convention:
predholds logits(B, C, *)and the softmax over dim 1 is taken inside.targetholds int64 class indices(B, *)in[0, C); its batch and spatial sizes must equal those ofpred.Class 0 is the background:
alphaweights it by \(1 - \alpha\) and classes \(1, \dots, C - 1\) by \(\alpha\), so a relabelling that moves class 0 changes the loss.alpha=Noneweights every class by 1. WithC = 2the target slice equalsbinary_focal_loss_with_logits()of the logit differencepred[:, 1:] - pred[:, :1]and the targettarget[:, None], with the samealphaandgamma: 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,Ctimes the pixel count, so withgamma=0andalpha=Noneit is the mean cross entropy divided byC.weightmultiplies the slice of classcbyweight[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, wheredice_loss()andtversky_loss()drop it. Losses and metrics portscross_entropy()to this loss.alphaoutside[0, 1]and a negativegammaare not validated.On the CPU,
'mean'and'sum'withoutweight, with a finitegamma >= 0andalphaNoneor 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-sizelog_softmax, unlesstorch.exportortorch.jit.tracecaptures the call, a functorch transform or forward-mode AD runs, or autocast is on. It agrees withlog_softmaxto 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), orignore_index.alpha (
Optional[float]) – weight \(\alpha \in [0, 1]\) of classes \(1, \dots, C - 1\);Noneweights every class by 1.gamma (
float, optional) – focusing exponent \(\gamma \ge 0\). Default:2.0reduction (
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:Noneignore_index (
Optional[int], optional) – label whose pixels contribute 0 but stay in the'mean'denominator. Default:-100
- Return type:
- Returns:
the loss, a
(B, C, *)map forreduction='none'and a scalar otherwise.
See also
FocalLoss: the module form.binary_focal_loss_with_logits(): a sigmoid per element in place of the softmax over the classes.dice_loss(): an overlap loss; ignored pixels leave the average.
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 ofpredover the classes (\(X\)) and the one-hottarget(\(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:
predandtargetare those offocal_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-channelpredhas 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,weightscaling the terms of classcin 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 noreduction.epsis 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, ateps=0as well.On the CPU, float32 or float64 logits with at least \(2^{15}\) values and a
weightthat isNoneor of their dtype skip the one-hot target, unlesstorch.exportortorch.jit.tracecaptures 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 notignore_indexraises the sameRuntimeErrorasone_hot, also undertorch.compile. Some torch releases (2.5.1 and 2.9.1 among them) report atorch.compilecapture as an export: a compiled call keeps the one-hot target there, and its compiledone_hotdoes not check the labels.
- Parameters:
pred (
Tensor) – logits(B, C, H, W).target (
Tensor) – int64 class indices(B, H, W)in[0, C), orignore_index.average (
str, optional) –'micro'(default) or'macro'. Default:"micro"eps (
float, optional) – term added to the denominator, non-negative. Default:1e-8weight (
Optional[Tensor], optional) – class weights(C,);Noneweights every class by 1. Default:Noneignore_index (
Optional[int], optional) – label whose pixels are left out;Noneignores no label. Default:-100
- Return type:
- 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 ofpredover the classes (\(P\)) and the one-hottarget(\(G\)) on the non-ignored pixels.alphaweights the false positives \(P \setminus G\) andbetathe false negatives \(G \setminus P\).\[\text{loss} = 1 - \frac{|PG|}{|PG| + \alpha |P \setminus G| + \beta |G \setminus P|}\]- Convention:
pred,targetandignore_indexbehave as indice_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 noweight,averageorreduction.\(\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), orignore_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-8ignore_index (
Optional[int], optional) – label whose pixels are left out;Noneignores no label. Default:-100
- Return type:
- 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; addsaverageand classweight.
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 ofpred(\(X\)) and the one labelled intarget(\(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:
predholds one logit channel andtargetlabels 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 noreduction.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.
targetis not validated and there is noignore_index: a label of 2 is accepted, and-100, theignore_indexoffocal_loss()anddice_loss(), can make the loss negative.
- Parameters:
- Return type:
- Returns:
a scalar with the computed loss, in the dtype of a floating-point
predand in float32 for an integer or boolpred. The Jaccard weights and the sum over pixels are computed in float32 for a float16 or bfloat16pred.
See also
LovaszHingeLoss: the module form.lovasz_softmax_loss(): the multi-class loss, fromC >= 2logit channels against class indices.
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 ofpredover the classes (\(X\)) against the one-hottarget(\(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:
- Convention:
predholds logits(B, C, H, W)withC >= 2and the softmax over dim 1 is taken inside;targetholds class labels(B, H, W)in[0, C)with the spatial size ofpred. The batch sizes match, orpredholds one image, which is scored against every target. There is noignore_indexand the labels are not validated: a label of-100is not ignored, and on the CPU in eager mode it raises aRuntimeErrorfrom 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 allCclasses: a class absent from the image enters it with that image’s largest probability for the class.weightmultiplies the term of each class and the mean still divides byC, so a uniform weight of 2 doubles the loss, wheredice_loss(average='macro')divides by the summed weights of the classes it averages.
- Parameters:
- Return type:
- Returns:
a scalar with the computed loss, in the dtype of
predpromoted with the dtype ofweight. The Jaccard weights and the sum over pixels are computed in float32 for a float16 or bfloat16pred.
See also
LovaszSoftmaxLoss: the module form.lovasz_hinge_loss(): the binary loss, from one logit channel.dice_loss(): optimises the Dice overlap and drops ignored pixels.
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, andloss = criterion(pred, target)isbinary_focal_loss_with_logits(). A plain tensorpos_weightorweightis stored as a non-persistent buffer, socriterion.to(device)moves it andstate_dictomits it.- Convention:
See the Convention block of
binary_focal_loss_with_logits(). Unlike the function,alphahas no default here.
- Parameters:
alpha (
Optional[float]) – weight \(\alpha \in [0, 1]\) of the positive term;Noneweights both terms by 1.gamma (
float, optional) – focusing exponent \(\gamma \ge 0\). Default:2.0reduction (
str, optional) –'none'(default),'mean'or'sum', as inbinary_focal_loss_with_logits(). Default:"none"pos_weight (
Optional[Tensor], optional) – weight of the positive term of each channel(C,). Default:Noneweight (
Optional[Tensor], optional) – channel weights(C,). Default:Noneignore_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 ofpred, orignore_index.Output: a map with the shape of
predforreduction='none', a scalar otherwise.
See also
binary_focal_loss_with_logits(): the one-call form.FocalLoss: a softmax over the classes against class indices, for exclusive classes.
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, andloss = criterion(pred, target)isdice_loss(). A plain tensorweightis stored as a non-persistent buffer, socriterion.to(device)moves it andstate_dictomits it.- Convention:
See the Convention block of
dice_loss().
- Parameters:
average (
str, optional) –'micro'(default) or'macro', as indice_loss(). Default:"micro"eps (
float, optional) – term added to the denominator, non-negative. Default:1e-8weight (
Optional[Tensor], optional) – class weights(C,);Noneweights every class by 1. Default:Noneignore_index (
Optional[int], optional) – label whose pixels are left out;Noneignores no label. Default:-100
- Shape:
pred: logits
(B, C, H, W).target: int64 class indices
(B, H, W)in[0, C), orignore_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, andloss = criterion(pred, target)istversky_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-8ignore_index (
Optional[int], optional) – label whose pixels are left out;Noneignores no label. Default:-100
- Shape:
pred: logits
(B, C, H, W).target: int64 class indices
(B, H, W)in[0, C), orignore_index.Output: a 0-d tensor.
See also
tversky_loss(): the one-call form.DiceLoss: weights false positives and false negatives equally; addsaverageand classweight.
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, andloss = criterion(pred, target)isfocal_loss(). A plain tensorweightis stored as a non-persistent buffer, socriterion.to(device)moves it andstate_dictomits it.- Convention:
See the Convention block of
focal_loss().
- Parameters:
alpha (
Optional[float]) – weight \(\alpha \in [0, 1]\) of classes \(1, \dots, C - 1\);Noneweights every class by 1.gamma (
float, optional) – focusing exponent \(\gamma \ge 0\). Default:2.0reduction (
str, optional) –'none'(default),'mean'or'sum', as infocal_loss(). Default:"none"weight (
Optional[Tensor], optional) – class weights(C,). Default:Noneignore_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), orignore_index.Output: a
(B, C, *)map forreduction='none', a scalar otherwise.
See also
focal_loss(): the one-call form.BinaryFocalLossWithLogits: a sigmoid per element in place of the softmax over the classes.DiceLoss: an overlap loss; ignored pixels leave the average.
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, andloss = criterion(pred, target)islovasz_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
lovasz_hinge_loss(): the one-call form.LovaszSoftmaxLoss: the multi-class loss, fromC >= 2logit channels against class indices.
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)storesweight, andloss = criterion(pred, target)islovasz_softmax_loss(). A plain tensorweightis stored as a non-persistent buffer, socriterion.to(device)moves it andstate_dictomits it.- Convention:
See the Convention block of
lovasz_softmax_loss().
- Parameters:
weight (
Optional[Tensor], optional) – class weights(C,);Noneweights every class by 1. Default:None
- Shape:
pred: logits
(B, C, H, W)withC >= 2.target: class indices
(B, H, W)in[0, C).Output: a scalar.
See also
lovasz_softmax_loss(): the one-call form.LovaszHingeLoss: the binary loss, from one logit channel.DiceLoss: optimises the Dice overlap and drops ignored pixels.
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()