License YOLO
Back to Ultralytics Glossary

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 --> L

Ultralytics 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.

Explore solutions

Computer vision in sports

Computer vision in sports

Discover how Ultralytics YOLO powers sports vision with player and ball tracking, performance analytics, coaching insights, and athlete rehabilitation.
Learn more
Computer vision for aerial imagery

Computer vision for aerial imagery

Turn drone and aerial imagery into real-time insights for agriculture, aquaculture, conservation, and geospatial analysis with Ultralytics YOLO.
Learn more
Computer vision in aerospace

Computer vision in aerospace

Apply computer vision in aerospace with Ultralytics YOLO for aircraft inspection, runway FOD detection, airport ground operations, and composite defect detection.
Learn more
Computer vision in security

Computer vision in security

Protect every site with Ultralytics YOLO models. Vision AI powers perimeter monitoring, threat detection, license-plate recognition, and workplace safety.
Learn more
Computer vision in robotics

Computer vision in robotics

Power smarter machines with Ultralytics YOLO models. Vision AI in robotics drives autonomous navigation, perception, object tracking, and real-time control.
Learn more
Computer vision in logistics

Computer vision in logistics

Streamline logistics with Ultralytics YOLO models. Vision AI enables package inspection, sorting, vehicle tracking, and real-time warehouse safety monitoring.
Learn more
Computer vision in retail

Computer vision in retail

Reimagine retail with Ultralytics YOLO models. Vision AI powers inventory tracking, shelf monitoring, queue management, and smarter customer insights.
Learn more
Computer vision in healthcare

Computer vision in healthcare

Build healthcare solutions with Ultralytics YOLO models. Vision AI in healthcare powers faster medical imaging, smarter diagnostics, and patient monitoring.
Learn more
Computer vision in manufacturing

Computer vision in manufacturing

Optimize manufacturing with Ultralytics YOLO models. Vision AI drives quality control, defect detection, PPE compliance, and assembly line automation.
Learn more
Computer vision in automotive

Computer vision in automotive

Apply computer vision in automotive with Ultralytics YOLO models. Vision AI elevates road safety, driver assistance, and vehicle automation for smarter roads.
Learn more
Computer vision in agriculture

Computer vision in agriculture

Bring vision AI to smart agriculture with Ultralytics YOLO models. Power crop monitoring, livestock tracking, and precision farming for higher, smarter yields.
Learn more

Let's build the future of AI together!

Begin your journey with the future of machine learning