DiceLoss

class topolosses.losses.dice.DiceLoss(*args: Any, **kwargs: Any)[source]

Bases: _Loss

Computes the Dice loss between two tensors.

Parameters:
  • smooth (float) – Smoothing factor to avoid division by zero added to numerator and denominator. Defaults to 1e-5.

  • sigmoid (bool) – If True, applies a sigmoid activation to the input before computing the loss. Defaults to False.

  • softmax (bool) – If True, applies a softmax activation to the input before computing the loss. Defaults to False.

  • batch (bool) – If True, reduces the loss across the batch dimension by summing intersection and union areas before division. Defaults to False, where the loss is computed independently for each item for the Dice calculation and reduced afterwards.

  • include_background (bool) – If False, channel index 0 (background class) is excluded from the calculation. Defaults to False.

  • weights (Tensor, optional) – A 1D tensor of class-wise weights, with length equal to the number of classes (adjusted for background inclusion). It allows emphasizing or ignoring classes. Defaults to None (unweighted).

Raises:

ValueError – If more than one of sigmoid, softmax, or convert_to_one_vs_rest is set to True.

forward(input: torch.Tensor, target: torch.Tensor) torch.Tensor[source]

Computes the Dice loss between two tensors.

Parameters:
  • input (torch.Tensor) – Predicted segmentation map of shape BC[spatial dimensions], where C is the number of classes, and [spatial dimensions] represent height, width, and optionally depth.

  • target (torch.Tensor) – Ground truth segmentation map of shape BC[spatial dimensions]

Returns:

The Dice loss as a scalar.

Return type:

torch.Tensor

Raises:
  • ValueError – If the shape of the ground truth is different from the input shape.

  • ValueError – If softmax=True and the number of channels for the prediction is 1.