Sub topic 10
Training losses: cross-entropy and Dice
Assume you know basic Python, NumPy, convolutional neural networks, gradient-based training, and object detection. This chapter focuses on how a segmentation model is trained, not how its output is represented.
A segmentation loss compares predicted pixels with a ground-truth label map. The loss is a number that training minimizes. Different losses emphasize different errors.
Cross-entropy: classify each pixel
For a semantic segmentation model with C classes, the model produces logits with shape (B, C, H, W). A logit is an unnormalized score. Cross-entropy applies softmax to these scores and penalizes the probability assigned to the correct class.
The target usually has shape (B, H, W). Each target value is an integer class ID, not a one-hot vector.
For one pixel, cross-entropy is:
-log(p_correct)
A confident correct prediction has a small loss. A confident incorrect prediction has a large loss.
import torch
import torch.nn.functional as F
logits = torch.tensor(
[[[[3.0, 0.2], [1.0, -1.0]],
[[0.1, 2.0], [-0.5, 1.5]]]]
) # shape: (B=1, C=2, H=2, W=2)
target = torch.tensor([[[0, 1], [1, 1]]]) # shape: (1, 2, 2)
loss = F.cross_entropy(logits, target)
print(float(loss))Cross-entropy treats every pixel as a classification example. If background occupies most pixels, the model can obtain a low loss by predicting background too often. Class weights, sampling, or an ignore label can reduce this problem.
Dice loss: measure overlap
Dice measures overlap between a predicted foreground region and the target region:
Dice = 2TP / (2TP + FP + FN)
Dice loss is 1 - Dice. It focuses on region overlap rather than counting each pixel independently. This makes it useful when the foreground is small or class frequencies are highly unequal.
The following implementation uses logits for a binary mask. The sigmoid converts logits into foreground probabilities.
import torch
def dice_loss(logits, target, eps=1.0):
probs = torch.sigmoid(logits).flatten(1)
target = target.float().flatten(1)
intersection = (probs * target).sum(dim=1)
total = probs.sum(dim=1) + target.sum(dim=1)
dice = (2 * intersection + eps) / (total + eps)
return (1 - dice).mean()
logits = torch.tensor([[[[2.0, -1.0], [0.5, -2.0]]]])
target = torch.tensor([[[[1, 0], [1, 0]]]])
print(float(dice_loss(logits, target)))The smoothing value eps prevents division by zero. It also affects behavior when both masks are empty, so choose it deliberately.
Combining losses
Cross-entropy gives strong pixel-level classification signals. Dice directly rewards shape overlap. A common objective is:
total_loss = cross_entropy + λ × dice_loss
The weight λ controls the influence of Dice. For multiclass segmentation, compute Dice per class after softmax, then average the relevant classes. Exclude ignored pixels from both losses.
Exercise
Why can Dice loss help when the foreground occupies only one percent of an image?
Show answer
It measures overlap using true positives, false positives, and false negatives, so the many background pixels do not dominate the objective as strongly as they can with ordinary pixel-wise cross-entropy.