DiceLoss#

class DiceLoss(smooth=1, exponent=2, loss_weight=1.0, ignore_index=-1)[source]#

Bases: Module

Soft multi-class Dice loss over per-point class probabilities.

Dice loss (V-Net, Milletari et al. 2016). forward(pred, target) reshapes pred to (N, C) (logits, soft-maxed internally) and target to (N,) (class indices), drops ignored points, one-hot encodes the targets, and averages 1 - Dice across classes. Returns the loss scaled by loss_weight. Registered as DiceLoss – use in a criteria=[...] list, commonly alongside a cross-entropy or Lovasz term.

Parameters:
  • smooth (float) – Smoothing constant added to the Dice numerator and denominator. Defaults to 1.

  • exponent (float) – Exponent applied to the per-class terms in the denominator. Defaults to 2.

  • loss_weight (float) – Global scale on the returned loss. Defaults to 1.0.

  • ignore_index (int) – Target value excluded from the loss. Defaults to -1.

Example

>>> import torch
>>> from pimm.models.losses.builder import build_criteria
>>> crit = build_criteria([dict(type="DiceLoss", loss_weight=1.0)])
>>> pred = torch.randn(4, 3)            # (N=4 points, C=3 classes) logits
>>> target = torch.tensor([0, 2, 1, 0]) # class indices
>>> crit(pred, target)                  # scalar 1 - Dice averaged over classes
tensor(0.5031)
DiceLoss.forward(pred, target, **kwargs)[source]#