AI Logic

Loss Functions

Dice Loss

Updated:

Graph of Dice loss and cross-entropy. The horizontal axis is the probability q given to foreground pixels and the vertical axis is the loss, overlaying the Dice loss when all background is predicted correctly (solid line) and the mean cross-entropy with 50% foreground (dotted line) and 1% foreground (dashed line). With 1% foreground, cross-entropy stays almost 0, while Dice loss approaches 1 for small q regardless of the foreground ratio. A legend is on the right

Background and overview

Dice loss is the Dice coefficient, which measures how much the predicted region and the ground-truth region overlap, subtracted from 1 to form a loss. It is used in segmentation, which labels each pixel of an image as "target or background," and it can learn without adjusting per-class weights even when the target (foreground) occupies only a tiny part of the image. Milletari et al. proposed it in 2016 together with V-Net, a network that segments the prostate in 3-D MRI volumes.

D=2∑i=1Npigi∑i=1Npi2+∑i=1Ngi2,LDice=1−DD = \frac{2 \sum_{i=1}^{N} p_i g_i}{\sum_{i=1}^{N} p_i^2 + \sum_{i=1}^{N} g_i^2}, \qquad L_{\mathrm{Dice}} = 1 - D

NN is the number of pixels (voxels in 3-D), pip_i is the foreground probability the model outputs for pixel ii, and gig_i is the ground truth (1 for foreground, 0 for background). DD takes values from 0 to 1 and equals 1 when the prediction matches the ground truth exactly.

The motivation was the class imbalance common in medical images.

  • The organ of interest is a tiny part of the image: A target such as the prostate occupies only a small region of the whole scan.
  • Per-pixel losses are pulled toward the background: When per-pixel cross-entropy is averaged over all pixels, the loss becomes small just by getting the overwhelming majority of background right. The paper points out that training falls into a state of "predicting only background," and the foreground is missed or only partly detected.

The figure at the top compares losses for a model that correctly predicts 0 for every background pixel and outputs probability qq for every foreground pixel. With only 1% foreground, the mean cross-entropy stays almost 0 even if the foreground is missed entirely. Dice loss, on the other hand, cancels the number of foreground pixels between the numerator and the denominator, so it follows the same curve regardless of the foreground ratio, and it approaches 1 when the foreground is missed.

Theory (how the loss is computed)

Dice loss is computed in the following steps. As an example, take a 1-D image of 10 pixels with ground truth g=(0,0,1,1,1,1,0,0,0,0)g = (0, 0, 1, 1, 1, 1, 0, 0, 0, 0) (4 foreground pixels) and predicted probabilities p=(0,0.1,0.9,0.8,0.6,0.2,0.1,0,0,0)p = (0, 0.1, 0.9, 0.8, 0.6, 0.2, 0.1, 0, 0, 0).

  1. Turn the network output into probabilities with softmax: V-Net outputs two channels, foreground and background, and applies softmax to get the foreground probability pip_i for each pixel.
  2. Compute the amount of overlap: ∑ipigi\sum_i p_i g_i is the total probability placed on the ground-truth foreground. In the example it is 0.9+0.8+0.6+0.2=2.50.9 + 0.8 + 0.6 + 0.2 = 2.5.
  3. Compute the size of each: ∑ipi2=1.87\sum_i p_i^2 = 1.87 and ∑igi2=4\sum_i g_i^2 = 4.
  4. Compute the Dice coefficient: D=2×2.51.87+4≈0.852D = \dfrac{2 \times 2.5}{1.87 + 4} \approx 0.852.
  5. Subtract from 1 to get the loss: LDice=1−0.852≈0.148L_{\mathrm{Dice}} = 1 - 0.852 \approx 0.148. In the paper's terms, training maximizes DD.

The expression is differentiable, and the gradient with respect to the prediction for pixel jj is as follows (the paper's equation).

∂D∂pj=2[gj(∑ipi2+∑igi2)−2pj∑ipigi(∑ipi2+∑igi2)2]\frac{\partial D}{\partial p_j} = 2 \left[ \frac{g_j \left( \sum_i p_i^2 + \sum_i g_i^2 \right) - 2 p_j \sum_i p_i g_i}{\left( \sum_i p_i^2 + \sum_i g_i^2 \right)^2} \right]

When predictions are rounded to 0 or 1, pi2=pip_i^2 = p_i, so the Dice coefficient becomes 2 TP2 TP+FP+FN\dfrac{2\,\mathrm{TP}}{2\,\mathrm{TP} + \mathrm{FP} + \mathrm{FN}}, the same value as the F1 score (TP is the number of pixels correctly predicted as foreground, FP the number of background pixels mistaken for foreground, and FN the number of missed foreground pixels). Rounding the example above at 0.5, 3 pixels are predicted as foreground and all of them are ground-truth foreground, so D=2×33+4≈0.857D = \frac{2 \times 3}{3 + 4} \approx 0.857. Dice loss can be seen as the F1 score computed on probabilities so that it can be differentiated.

Why it is robust to class imbalance

Dice loss is hardly affected by how little foreground there is because the loss is determined by "a ratio between foreground regions."

  • Correct background does not enter the loss: The numerator ∑ipigi\sum_i p_i g_i sums over foreground pixels only. Correctly predicting 0 for a background pixel adds nothing to either the numerator or the denominator. However much background is right, the loss does not drop, and DD does not grow unless the foreground is predicted.
  • It is divided by the size of the foreground: Because the denominator is the sum of the sizes of the predicted and true foreground, small and large targets alike are judged by "what fraction could be overlapped."

To handle this imbalance with cross-entropy, the common approach is to put a large weight on the loss of foreground pixels. The paper reports that, without any weight tuning, Dice loss gave better results than weighted cross-entropy (multinomial logistic loss).

As an analogy, cross-entropy is grading that counts "how many answers on the whole-pixel answer sheet are correct," while Dice loss is grading that looks only at "how much of what should be colored was colored correctly." Even if answering "background" is correct for almost every question, the second kind of grading cannot be gamed.

Experimental results

The paper used prostate MRI from the PROMISE 2012 challenge, trained on 50 3-D volumes, and evaluated on 30 volumes whose ground truth is not public (the evaluation was run by the organizers). The results below compare the same V-Net with only the loss changed.

LossMean Dice coefficient (higher is better)Mean Hausdorff distance (lower is better)Challenge score
Dice loss0.869 ± 0.0335.71 ± 1.20 mm82.39
Multinomial logistic loss (cross-entropy)0.739 ± 0.08810.55 ± 5.38 mm63.30
  • The Dice coefficient rose by 0.13: With the same network, switching the loss to Dice loss raised the mean Dice coefficient from 0.739 to 0.869.
  • Contour errors also shrank: The Hausdorff distance, the largest deviation between the predicted and true contours, fell from 10.55 mm to 5.71 mm.
  • Variation also shrank: The standard deviation of the Dice coefficient dropped from 0.088 to 0.033, narrowing the gap between good and bad results across images.

It falls slightly short of the top method in the same challenge (mean Dice coefficient 0.879). The paper cites V-Net's speed, processing one volume in about 1 second, as an advantage.

Practical considerations

Dice loss is undefined for images with no foreground at all. If the ground truth and prediction are all 0, the denominator is 0. Implementations add a small value ε\varepsilon to the numerator and denominator to avoid division by zero. Also, for images with only a few foreground pixels, hitting or missing a single pixel changes the loss a lot, and the gradients tend to become unstable.

Keep the following points in mind as well.

  • Check the form of the denominator: In the paper's formula, the denominator is the sum of squares of the probabilities and the ground truth, ∑pi2+∑gi2\sum p_i^2 + \sum g_i^2. Some implementations use the unsquared ∑pi+∑gi\sum p_i + \sum g_i, so the same "Dice loss" can give different values and gradients. When comparing with the paper's results, use the same formula.
  • PyTorch has no built-in version: PyTorch's torch.nn does not include Dice loss, so write your own or use one from a library. Compute it on probabilities after softmax or the sigmoid function, and do not pass raw logits.
  • Decide whether to compute per image or over the whole batch: Pooling all pixels in the batch into one Dice coefficient versus computing it per image and averaging changes how small targets are treated.
  • The paper demonstrates it on two-class segmentation: The paper's conclusion presents Dice loss as suited to two-class (foreground and background) segmentation. For multiple classes, the natural extension is to compute Dice loss per class and average.

Comparison with other loss functions

The table compares losses used in segmentation from the same viewpoints.

Loss functionWhat it measuresWhen foreground is scarceMain uses
Per-pixel cross-entropyAverage of per-pixel probability errorsEasily pulled toward the background (needs weight tuning)Segmentation where foreground and background are similar in amount
Dice lossFraction of overlap between the predicted and true regionsHardly affected, since it measures a ratioTwo-class segmentation with small foreground (such as medical images)
Focal LossPer-pixel cross-entropy multiplied by a factor that down-weights easy pixelsLoss from easy background becomes smallClassification with overwhelmingly many easy background examples, such as object detection

Other losses that measure region overlap include the Tversky loss, based on the Dice coefficient, and Lovász-Softmax, which targets IoU (the overlap measure underlying mIoU).

Rules of thumb for choosing:

  • If the foreground is small and evaluation uses the Dice coefficient, use Dice loss: The training objective and the evaluation metric line up.
  • If foreground and background are similar in amount, start with per-pixel cross-entropy: No weight tuning is needed, and every pixel's loss counts equally.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F


def dice_loss(probs, target, eps=1e-6):
    """Paper's formula: 1 − 2Σ p·g / (Σ p² + Σ g²). probs are foreground probabilities, target is 0 or 1.
    Returns one value for a single image (or the whole batch)"""
    p = probs.reshape(-1)
    g = target.reshape(-1).float()
    inter = (p * g).sum()
    denom = (p * p).sum() + (g * g).sum()
    return 1 - (2 * inter + eps) / (denom + eps)   # eps: avoid division by zero for images with no foreground


# example from the text (10 pixels)
g = torch.tensor([0, 0, 1, 1, 1, 1, 0, 0, 0, 0])
p = torch.tensor([0, 0.1, 0.9, 0.8, 0.6, 0.2, 0.1, 0, 0, 0])
print(dice_loss(p, g).item())                       # about 0.148 (D ≈ 0.852)


# as in V-Net, turn the 2-channel output into probabilities with softmax
class SoftDiceLoss(nn.Module):
    def forward(self, logits, target):
        # logits: (B, 2, D, H, W), target: 0/1 of shape (B, D, H, W)
        probs = F.softmax(logits, dim=1)[:, 1]        # foreground probability
        losses = [dice_loss(probs[b], target[b]) for b in range(logits.shape[0])]
        return torch.stack(losses).mean()             # compute per image and average


criterion = SoftDiceLoss()
logits = torch.randn(2, 2, 16, 32, 32, requires_grad=True)   # dummy output
target = (torch.rand(2, 16, 32, 32) > 0.98).long()          # about 2% foreground
loss = criterion(logits, target)
loss.backward()

# combining with cross-entropy
loss2 = criterion(logits, target) + F.cross_entropy(logits, target)

FAQ

Q. Are the Dice coefficient and the F1 score the same thing?
A.

When predictions are rounded to 0 or 1 and pixels are counted, they give the same value, because both can be computed as 2TP / (2TP + FP + FN). Dice loss computes it on the unrounded probabilities so that it is differentiable and can be used as a training loss.

Q. How does Dice loss differ from IoU (the Jaccard index)?
A.

Both measure the overlap between the predicted and true regions, but IoU is "overlap ÷ union," while the Dice coefficient is "2 × overlap ÷ sum of the sizes of the two regions." For the same overlap, the Dice coefficient gives a larger value. Choosing the loss to match the evaluation metric aligns the goals of training and evaluation.

Q. Should I use cross-entropy or Dice loss?
A.

If the foreground is a tiny part of the image and evaluation uses the Dice coefficient, Dice loss is a candidate. In the paper, on prostate MRI, it raised the Dice coefficient substantially over weighted cross-entropy. If training is unstable, another option is to add the two together.

References

  1. F. Milletari, N. Navab, and S.-A. Ahmadi, "V-Net: Fully Convolutional Neural Networks for Volumetric Medical Image Segmentation," 3DV, 2016.