Deep LearningSegmentation Loss Functions

How do Dice loss and IoU loss differ for imbalanced image segmentation?

Question 304 of 314 · Updated

On this page

Dice loss and IoU loss are closely related overlap-based objectives for image segmentation. For the same hard binary masks, they rank predictions identically because Dice and IoU are monotonic transformations of each other. Their reported scores are different, and practical training behavior can differ when soft approximations, smoothing, class averaging, and batch aggregation are introduced.

This lesson extends Deep Learning Questions 229–231, which introduce IoU, the Dice coefficient, and Dice loss versus cross-entropy. Here the focus is the direct comparison between Dice loss and IoU (Jaccard) loss.

1. Start with the overlap counts#

For a binary segmentation mask, compare predicted foreground pixels with ground-truth foreground pixels:

  • True positives (TP): predicted foreground pixels that are actually foreground.
  • False positives (FP): background pixels incorrectly predicted as foreground.
  • False negatives (FN): foreground pixels missed by the model.

Both Dice and IoU measure overlap between predicted and ground-truth regions. They do not count true negatives directly.

Dice coefficient and Dice loss

LaTeX
LaTeX

Intersection over Union (IoU) and IoU loss

IoU is also called the Jaccard index:

LaTeX
LaTeX

Both scores range from 0 to 1. A score of 1 means a perfect overlap; a loss of 0 means a perfect prediction.

2. The important mathematical relationship#

For the same binary masks:

LaTeX

And in the reverse direction:

LaTeX

This has a useful consequence: for the same hard binary masks, Dice and IoU always rank two predictions in the same order. If one prediction has a higher Dice score than another, it also has a higher IoU score.

The numerical values are not equal. Dice is always at least as large as IoU for the same non-empty masks. Therefore, a Dice score of 0.80 is not equivalent to an IoU score of 0.80.

The corresponding losses are related too:

LaTeX

Do not compare the raw numerical value of a Dice loss with an IoU loss and conclude that the smaller number represents a better model. They use different scales.

3. Numerical example#

Suppose a segmentation model is evaluated on a small lesion:

  • Ground-truth foreground pixels: 10
  • Predicted foreground pixels: 12
  • Correctly predicted foreground pixels (TP): 8
  • Incorrect foreground predictions (FP): 4
  • Missed foreground pixels (FN): 2

Dice calculation

LaTeX
LaTeX

IoU calculation

LaTeX
LaTeX
MeasureResult
True positives8
False positives4
False negatives2
Dice score0.727
Dice loss0.273
IoU score0.571
IoU loss0.429

Both measures describe exactly the same predicted mask. The different scores come from their different denominators, not from a different model prediction.

4. Soft Dice loss versus soft IoU loss#

Hard segmentation metrics are calculated after pixels have been converted into binary decisions. A hard threshold operation is not suitable inside an ordinary gradient-based training loss because it removes useful gradient information.

During training, implementations commonly use predicted probabilities instead of thresholded masks.

Let:

  • be the predicted foreground probability for pixel .
  • be its ground-truth value, usually 0 or 1.
  • be a small smoothing constant to avoid division by zero.

A common soft Dice formulation is:

LaTeX
LaTeX

A common soft IoU formulation is:

LaTeX
LaTeX

These formulations replace discrete foreground membership with continuous probabilities, allowing gradients to flow back through the network.

With the same aggregation and compatible smoothing, these two standard soft formulations retain a close mathematical relationship. In real code, implementations can differ in:

  • Whether probabilities or squared probabilities appear in the denominator.
  • How the smoothing constant is applied.
  • Whether overlap is computed per image, per batch, or per class.
  • Whether background is included.
  • Whether class scores are averaged equally or weighted by class frequency.

Those choices can change optimization behavior and measured results. Inspect the exact implementation rather than assuming every function called “Dice loss” or “IoU loss” is identical.

5. Side-by-side comparison#

DimensionDice lossIoU loss
Underlying scoreSørensen–Dice coefficientJaccard index
Formula denominatorSum of predicted and true foreground sizesSize of the union
Hard-mask rankingSame ranking as IoUSame ranking as Dice
Typical score scaleNumerically higher than IoU for the same masksNumerically lower than Dice for the same masks
Common applicationsMedical and small-foreground segmentationSemantic segmentation and benchmarks reporting IoU/mIoU
Main benefitDirectly optimizes region overlap and foreground agreementDirectly aligns with intersection-over-union evaluation
Practical caveatSoft variants and aggregation affect gradientsSoft variants and aggregation affect gradients

Neither loss is universally superior. The best choice depends on the evaluation metric, segmentation task, class imbalance, and exact implementation.

6. How do they behave with class imbalance?#

Imagine segmenting a tiny tumor in a medical scan. The tumor occupies only 1% of the pixels; the remaining 99% are background.

A pixel-wise loss can be dominated by the large background region if the training setup does not handle imbalance appropriately. A model that predicts background almost everywhere may achieve high pixel accuracy while missing the tumor.

Dice and IoU focus on overlap between foreground regions rather than rewarding every correctly predicted background pixel. This makes them useful objectives for foreground segmentation when the foreground occupies a small fraction of the image. The V-Net paper introduced a Dice-based objective for volumetric prostate MRI segmentation and discussed its usefulness under strong foreground/background imbalance.

However, neither loss automatically solves every imbalance problem:

  • If the model predicts almost no overlap initially, overlap-based gradients may be weak or difficult to optimize.
  • Very small structures can make the loss sensitive to a few pixels.
  • A batch-level score can allow large objects or images to dominate small ones.
  • Neither loss necessarily gives calibrated pixel probabilities.
  • False positives and false negatives are treated symmetrically in the basic formulas.

For severe imbalance, consider generalized Dice, class weighting, focal loss, or a combined region-overlap and pixel-wise objective. Choose based on validation results, not just the name of the loss.

7. When should you choose Dice loss?#

Dice loss is a sensible starting point when:

  • You are working on binary or multiclass segmentation with a foreground region of interest.
  • Foreground pixels are much rarer than background pixels.
  • You care about overlap between predicted and true regions.
  • Your established evaluation reports Dice score.
  • You want a common, relatively straightforward region-overlap objective.

It is widely used in medical segmentation. The V-Net work is an influential example of training a volumetric segmentation network with a Dice-based objective.

Be careful with the reduction strategy. Computing Dice independently for each image and averaging the results gives every image equal influence. Computing one global Dice over an entire batch gives larger masks and images more influence.

8. When should you choose IoU loss?#

IoU loss is a sensible choice when:

  • Your primary evaluation metric is IoU or mean IoU (mIoU).
  • You want the training objective to reflect the intersection-over-union measure.
  • You are comparing semantic segmentation models on benchmarks that report Jaccard/IoU.
  • Your implementation has a suitable differentiable approximation and well-behaved gradients for your data.

A useful distinction: plain soft IoU loss and Lovász-Softmax are not the same thing. Lovász-Softmax is a tractable surrogate designed to optimize the discrete IoU measure more directly. The CVPR 2018 paper by Berman and colleagues develops this approach for semantic segmentation and studies the difference between optimizing IoU per image and over a dataset.

If mIoU is the deployment or benchmark target, evaluate a Lovász-style objective as a separate experiment rather than treating every implementation named “IoU loss” as equivalent.

9. PyTorch implementation for binary segmentation#

The following example calculates per-image soft Dice and soft IoU losses from logits. It assumes:

  • Logits have shape [B, 1, H, W].
  • Targets have the same shape and contain 0/1 values.
  • The loss is averaged across images.
PYTHON
import torch import torch.nn as nn def soft_dice_loss(logits, targets, eps=1e-6): probs = torch.sigmoid(logits) dims = tuple(range(1, probs.ndim)) intersection = (probs * targets).sum(dim=dims) denominator = probs.sum(dim=dims) + targets.sum(dim=dims) dice = (2.0 * intersection + eps) / (denominator + eps) return 1.0 - dice.mean() def soft_iou_loss(logits, targets, eps=1e-6): probs = torch.sigmoid(logits) dims = tuple(range(1, probs.ndim)) intersection = (probs * targets).sum(dim=dims) union = ( probs.sum(dim=dims) + targets.sum(dim=dims) - intersection ) iou = (intersection + eps) / (union + eps) return 1.0 - iou.mean() logits = model(images) targets = masks.float() dice_loss = soft_dice_loss(logits, targets) iou_loss = soft_iou_loss(logits, targets) print("Dice loss:", dice_loss.item()) print("IoU loss:", iou_loss.item())

For a multiclass segmentation problem, use softmax over the class dimension, compute overlap per class, and define how background and absent classes should be handled. Do not reuse a binary implementation without checking the class dimension and target encoding.

Combining overlap loss with BCE#

A region-overlap objective can be combined with a pixel-wise objective:

PYTHON
bce = nn.BCEWithLogitsLoss()(logits, targets) dice = soft_dice_loss(logits, targets) loss = bce + 0.5 * dice

The coefficient 0.5 is only an illustrative starting point. Tune the weighting on validation data and monitor both the training objective and the actual segmentation metrics.

BCE supplies local pixel-wise learning signals, while Dice or IoU adds a region-overlap objective. This can help when early predictions have very little overlap with the target. It does not guarantee better performance; test it against single-loss baselines.

10. Production example: detecting road cracks from images#

A city infrastructure team trains a segmentation model to mark road cracks. Cracks occupy a tiny fraction of each high-resolution image.

The team reports mean IoU because its evaluation benchmark uses that metric.

A practical experiment plan:

  1. Establish a pixel-wise BCE baseline and report per-image Dice and IoU.
  2. Train a soft Dice variant with the same architecture, data split, augmentation, and optimization budget.
  3. Train a soft IoU variant with the same experimental controls.
  4. If mIoU remains the main objective, test Lovász-Softmax as a separate surrogate rather than assuming plain soft IoU will optimize the benchmark identically.
  5. Evaluate per-image and per-class scores, especially on images containing very small cracks.
  6. Inspect false-positive crack fragments and missed crack segments. A strong average score can hide failures on thin or rare structures.
  7. Compare the training loss with the held-out hard-mask metric after applying the same inference threshold and post-processing rules.

Decision: Prefer the objective that improves held-out mIoU and maintains acceptable small-crack recall and false-positive rates. Do not choose Dice merely because its loss value looks smaller, or IoU merely because the benchmark reports it.

11. Common mistakes#

  • Comparing raw loss values: Dice loss and IoU loss use different scales. Compare the actual evaluation metric.
  • Thresholding probabilities during training: Hard thresholding removes useful gradients. Use continuous probabilities for soft overlap losses.
  • Assuming all implementations are identical: Smoothing, squared denominators, background handling, and reduction axes vary.
  • Ignoring absent classes: Decide how a class absent from both prediction and target should contribute; smoothing alone does not settle the evaluation policy.
  • Using global batch overlap without considering object size: Large masks can dominate small objects. Compare per-image and global aggregation.
  • Assuming overlap loss solves all imbalance: Severe imbalance may require generalized Dice, weighting, sampling, focal objectives, or a combined loss.
  • Ignoring calibration: Good overlap does not guarantee calibrated pixel probabilities.
  • Confusing IoU loss with Lovász-Softmax: Lovász-Softmax is a specific surrogate for the discrete IoU objective, not simply another name for the basic soft IoU formula.

12. Decision guide#

Choose Dice loss when foreground overlap is central, especially for small or imbalanced regions, and Dice is an important evaluation metric.

Choose IoU loss when intersection-over-union is the primary evaluation target and your chosen differentiable formulation matches the aggregation used at evaluation.

For the same hard binary masks, Dice and IoU rank predictions identically. The practical difference comes from their numerical scale and from how soft approximations, smoothing, class averaging, and batch aggregation are implemented.

Key takeaway: Dice and IoU measure the same kind of region overlap, but normalize it differently. Start with the metric your application actually reports, inspect the differentiable loss implementation, and validate performance on small objects and difficult cases—not just the average training loss.

Semantic deduplication / curriculum positioning: Deep Learning Question 229 introduces IoU as a segmentation metric, Question 230 introduces the Dice coefficient, and Question 231 compares Dice loss with cross-entropy. This lesson is distinct: it derives the Dice–IoU relationship, compares their soft differentiable forms and aggregation choices, and provides a controlled selection and implementation workflow.

Sources: V-Net: Fully Convolutional Neural Networks for Volumetric Medical Image Segmentation (Milletari et al., 2016); Generalised Dice Overlap as a Deep Learning Loss Function for Highly Unbalanced Segmentations (Sudre et al., 2017); The Lovász-Softmax Loss (Berman et al., CVPR 2018); Testing Segmentation Popular Loss and Variations in Three Multiclass Medical Imaging Problems.

Related questions

Explore other topics:Machine LearningLarge Language Models