Sub topic 10
Training losses: cross-entropy and Dice
A segmentation loss turns a predicted mask and a ground-truth mask into one number that gradient descent can reduce. This chapter covers the two losses you will meet most often: pixel-wise cross-entropy and Dice. It also covers why they behave differently when one class covers little of the image, and how to combine them.
This chapter assumes you know basic PyTorch tensors, how a softmax or sigmoid turns scores into probabilities, and how gradient-based training works. It also assumes you have read the earlier chapters on label maps and IoU.
Pixel-wise cross-entropy
A semantic segmentation network outputs logits of shape (B, C, H, W): one raw score per class at every pixel. The target is a label map of shape (B, H, W) holding an integer class per pixel. Cross-entropy treats each pixel as an independent classification problem. It applies softmax over the class dimension, takes the negative log probability of the true class, and averages over pixels.
import torch
import torch.nn.functional as F
torch.manual_seed(0)
logits = torch.randn(2, 3, 4, 4) # (B, C, H, W)
target = torch.randint(0, 3, (2, 4, 4)) # (B, H, W), int64
target[0, 0, 0] = 255 # 255 marks "ignore"
plain = F.cross_entropy(logits, target, ignore_index=255)
weighted = F.cross_entropy(
logits, target,
weight=torch.tensor([0.5, 1.0, 2.0]), # one weight per class
ignore_index=255,
)
print(plain.item(), weighted.item())Three details matter here.
- The target must be an integer tensor of class indices, not one-hot. Passing a float one-hot tensor changes how PyTorch interprets it.
ignore_indexremoves void pixels from both the sum and the average. Without it, a value such as 255 raises an out-of-range error or, worse, is silently counted as a class.weightscales each class's contribution. With a weight, PyTorch divides by the sum of the weights of the pixels that were counted, not by the pixel count.
Why cross-entropy struggles with imbalance
Cross-entropy sums the same kind of error over every pixel. Suppose a lesion fills 1% of a 100 x 100 image. A model that predicts "background" everywhere is right on 9,900 of 10,000 pixels. It has 99% pixel accuracy and a loss that looks small, yet it finds no lesion. The gradient from the 100 foreground pixels is swamped by the gradient from the 9,900 easy background pixels.
Two common mitigations stay within cross-entropy:
- Class weights. Weight rare classes more, for example by inverse frequency. This is simple but can be unstable when a class is very rare, and the weights must be tuned.
- Hard-pixel mining or focal loss. Down-weight pixels the model already classifies confidently, so the remaining error dominates.
Dice loss: optimize overlap directly
The Dice coefficient for a predicted mask P and a target mask T is 2|P ∩ T| / (|P| + |T|). It equals 1 for a perfect match and 0 for no overlap. It is closely related to IoU: Dice = 2·IoU / (1 + IoU). Both are 0 and 1 at the same points, and Dice is always at least as large as IoU in between.
The loss is 1 - Dice. To make it differentiable, replace the hard prediction with probabilities, so intersection becomes a sum of products and sizes become sums of probabilities. This is the "soft" Dice.
import torch
import torch.nn.functional as F
def dice_loss(logits, target, eps=1.0):
# logits: (B, H, W) raw scores for one class; target: (B, H, W) with values 0 or 1
probs = torch.sigmoid(logits).flatten(1)
target = target.flatten(1).float()
intersection = (probs * target).sum(dim=1)
denominator = probs.sum(dim=1) + target.sum(dim=1)
dice = (2 * intersection + eps) / (denominator + eps)
return (1 - dice).mean()
target = torch.zeros(1, 100, 100)
target[:, 40:50, 40:50] = 1 # 100 foreground pixels = 1% of the image
all_background = torch.full((1, 100, 100), -10.0) # confident "no lesion"
good = (target * 20 - 10) # confident and correct
print(dice_loss(all_background, target).item()) # close to 1.0 (about 0.99)
print(dice_loss(good, target).item()) # close to 0.0
print(F.binary_cross_entropy_with_logits(all_background, target).item()) # smallThe all-background prediction scores a small cross-entropy but a Dice loss near 1. Dice does not count the true negatives at all. Its value depends only on the overlap and the sizes of the two masks, so the 9,900 easy background pixels cannot dilute the signal.
What `eps` does
The eps term smooths the ratio. If both prediction and target are empty, the ratio is eps / eps = 1, so the loss is 0 instead of a division by zero. It also keeps gradients finite for tiny masks. A larger eps makes the loss gentler on small objects. Very small values make training noisy.
Where Dice causes trouble
- Noisy gradients. The gradient depends on the ratio of sums, so it can swing sharply when the mask is small. Training from scratch with Dice alone is often less stable than with cross-entropy.
- Poor calibration. Dice pushes probabilities toward 0 or 1. If you need meaningful confidence values, Dice-only training gives overconfident outputs.
- Per-image versus per-batch. The code above computes Dice per image and then averages. Computing it over the whole batch lets large objects dominate and makes images with no foreground contribute nothing useful.
- Ignored pixels.
ignore_indexdoes not exist in the Dice code. Multiply the probabilities and target by a validity mask before summing, or void pixels will count as background.
Combining the two
A common recipe is a weighted sum. Cross-entropy supplies stable, per-pixel gradients, and Dice supplies the overlap pressure.
import torch
import torch.nn.functional as F
def dice_loss(logits, target, eps=1.0):
probs = torch.sigmoid(logits).flatten(1)
target = target.flatten(1).float()
inter = (probs * target).sum(dim=1)
denom = probs.sum(dim=1) + target.sum(dim=1)
return (1 - (2 * inter + eps) / (denom + eps)).mean()
def bce_dice_loss(logits, target, dice_weight=1.0):
bce = F.binary_cross_entropy_with_logits(logits, target.float())
return bce + dice_weight * dice_loss(logits, target)
logits = torch.randn(4, 64, 64, requires_grad=True)
target = (torch.rand(4, 64, 64) > 0.95).long() # about 5% foreground
loss = bce_dice_loss(logits, target)
loss.backward()
print(loss.item(), logits.grad.abs().mean().item())For multi-class problems, compute Dice per class on softmax probabilities, average over classes, and add it to the multi-class cross-entropy.
Choosing a loss
| Situation | Reasonable choice |
|---|---|
| Balanced classes, large regions | Cross-entropy alone |
| Moderate imbalance | Cross-entropy with class weights |
| Small foreground (lesions, thin structures) | Cross-entropy plus Dice |
| Need calibrated probabilities | Cross-entropy, with Dice only as a small extra term |
| Many void pixels | Either loss, with void pixels masked out |
Common mistakes
- Passing probabilities to a function that expects logits, which applies softmax or sigmoid twice.
- Using the wrong target dtype:
cross_entropyneedsint64class indices. - Forgetting to mask void pixels in the Dice term.
- Computing Dice over the whole batch when many images contain no foreground.
- Using extreme class weights that make training diverge.
Exercise
A model predicts "background" for every pixel of a 100 x 100 image where the target object covers 100 pixels. Give its pixel accuracy and its Dice score, and explain which of cross-entropy or Dice loss is better at exposing the failure.
Show answer
Pixel accuracy is 9,900 / 10,000 = 99%. The intersection is 0, so Dice is 0 (or about eps / (100 + eps) with smoothing), and the Dice loss is close to 1. Dice loss exposes the failure because it ignores the true-negative background pixels, so it depends only on the overlap with the small object. Cross-entropy averages over all 10,000 pixels, so the 9,900 easy background pixels keep its value small.
Exercise
Why must a Dice term be given a validity mask when the dataset marks some pixels as "ignore"?
Show answer
Unlike F.cross_entropy with ignore_index, a hand-written Dice loss has no built-in way to skip pixels. Ignored pixels would be counted as background in the probability and target sums, which changes the intersection and size terms. Multiply the probabilities and the target by a 0/1 mask of valid pixels before summing.