Dice Loss
Dice loss trains segmentation models by measuring mask overlap. It helps models learn small foreground regions when background pixels dominate.
Dice loss is a loss function that trains image segmentation models by measuring how closely their predicted masks overlap the ground truth. It is usually calculated as one minus a differentiable version of the Dice coefficient. Better overlap produces lower loss. This makes Dice loss useful when the region of interest occupies only a small fraction of an image or a 3D scan.
How Dice Loss Measures Overlap#
The Dice coefficient takes its name from Lee R. Dice's 1945 measure of ecological association. For binary masks, double the number of shared foreground pixels and divide by the sum of the foreground pixel counts in both masks. The coefficient is 1 for identical nonempty masks and 0 for disjoint masks with a nonempty union. Correctly predicted background pixels do not enter the foreground Dice calculation. An all-background prediction therefore gets a foreground Dice score of 0 whenever the target contains foreground, even if its pixel accuracy is high.
During training, soft Dice uses foreground probabilities so gradients can flow through backpropagation. A common form doubles the sum of prediction–target products and divides by the sum of predicted probabilities plus the sum of target values. Fausto Milletari, Nassir Navab, and Seyed-Ahmad Ahmadi introduced a Dice-based training objective in their 2016 V-Net paper for prostate MRI segmentation, an application of computer vision in healthcare where prostate boundaries support volume measurement and treatment planning. Their version sums squared values in the denominator; both forms give the same coefficient on binary masks.
On hard binary masks, the Dice coefficient equals the foreground F1 score. It also equals 2 × IoU / (1 + IoU), where intersection over union (IoU) is measured on the same mask pair with a nonempty union. Soft training loss and hard Dice on validation data can move differently because thresholding changes which pixels count as foreground.
Dice Loss vs. Cross-Entropy#
Cross-entropy loss scores each pixel's predicted class probability. Dice loss scores overlap across a region, so the effect of changing one pixel depends on the other pixels in that region. A combined objective uses both signals: Dice responds to how much foreground the prediction covers, while binary cross-entropy (BCE) provides a pixel-level penalty for false foreground responses even on an image with no foreground labels.
flowchart TD
P["Model predictions"] --> CE["Pixel-level cross-entropy"]
T["Ground truth mask"] --> CE
P --> D["Region-level Dice loss"]
T --> D
CE --> L["Combined training loss"]
D --> LUltralytics YOLO26 uses both signals in its semantic segmentation loss. It adds Dice to BCE in the single-class case and to multiclass cross-entropy when each pixel belongs to one of several classes.
Calculating Dice Loss in Python#
This PyTorch example uses MONAI's DiceLoss with a silhouette bundled in scikit-image. The target has shape [batch, channel, height, width]. Both predictions assign the same total foreground probability, but one shifts that probability sideways.
Install the dependencies with pip install torch monai scikit-image.
import torch
from monai.losses import DiceLoss
from skimage import data
# Invert the black silhouette so foreground is 1.
target = torch.from_numpy(~data.horse()).float()[None, None]
criterion = DiceLoss()
# Compare two probability masks with identical sums.
aligned = 0.01 + 0.98 * target
shifted = torch.roll(aligned, shifts=25, dims=-1)
print(f"Aligned: {criterion(aligned, target).item():.3f}")
print(f"Shifted: {criterion(shifted, target).item():.3f}")The aligned mask gives lower loss because more foreground probability falls inside the silhouette. In a model, sigmoid converts logits to probabilities for binary segmentation or independent labels. Softmax gives a probability distribution across mutually exclusive classes, and Dice can be computed separately for each class.
Why Smoothing and Averaging Matter#
Averaging per-image Dice gives each image equal weight. Pooling pixel sums across a batch before dividing gives images with larger combined mask sizes more influence. In multiclass segmentation, averaging one score per class gives rare classes their own contribution. Including a background score lets strong background predictions raise that average.
For a class absent from an image, the unsmoothed foreground Dice numerator is zero even when the model predicts false positives. With a nonzero predicted foreground sum, the loss is a constant 1 and supplies no gradient for that class. With an empty prediction too, the ratio becomes zero divided by zero. Adding the same positive smoothing constant to the numerator and denominator gives zero loss when both masks are empty and makes the loss rise as predicted foreground probability accumulates.










