In medical or satellite segmentation the object of interest often covers a tiny fraction of the pixels. A per-pixel cross-entropy loss is then dominated by the easy background, and a model that predicts "background everywhere" scores 99% accuracy and learns nothing. The Dice coefficient measures overlap instead: twice the intersection divided by the sum of the two areas. It ranges from 0 (no overlap) to 1 (perfect), and the background does not enter it at all. As a loss we use 1 - Dice computed on predicted probabilities (so it stays differentiable), and a small eps keeps the ratio defined when both masks are empty.
Implement dice_coefficient and dice_loss.
pred holds probabilities in [0, 1] and target holds 0/1 labels, both of shape (N, H, W).dice_coefficient(pred, target, eps) computes, per sample, (2 * sum(pred * target) + eps) / (sum(pred) + sum(target) + eps) over the spatial dimensions and returns the (N,) array.dice_loss(pred, target, eps=1e-6) is 1 - mean(dice_coefficient(...)) as a Python float.Reshape to (N, -1) and reduce over axis 1.
When both masks are empty, eps in numerator and denominator makes the coefficient exactly 1.
No results yet
Run your code to check it against the examples, or submit to run every test.