Dice lossEasynumpylosssegmentationcomputer-visiondice
Dice loss
Background
Dice loss optimises overlap directly, which makes it the default for image segmentation with imbalanced foreground/background. It is , where the Dice (F1) coefficient measures the overlap between predicted and ground-truth masks; unlike pixel-wise cross-entropy it isn't drowned out by the sea of easy background pixels.
Problem statement
Implement dice_loss(pred, target, smooth=1e-6):
Input
pred—np.ndarray: predicted mask (probabilities in or binary).target—np.ndarray: ground-truth mask (0/1), same shape.smooth—float: smoothing term to avoid division by zero.
Output
Returns a float in (0 = perfect overlap).
Examples
Example 1
Input: pred = [1, 1, 0, 0], target = [1, 0, 0, 0]
Output: 0.3333
Explanation: intersection ; , . Dice , so loss .
Constraints
- The Dice numerator is the elementwise-product sum; the denominator is the sum of both masks (with
smoothadded to both). - Loss : perfect overlap → 0, no overlap → ~1.
- Works on flattened or full arrays; tests compare with
atol=1e-4.
Notes
- The Dice coefficient is the pixel-wise F1 score: for binary masks.
- The smoothing term keeps the loss well-defined (→ 0) when both masks are empty, where Dice would otherwise be .
Python
Loading...
This problem ships 4 hidden tests. They run in your browser via Pyodide — no backend, no submission queue. Press ▶ Run tests to execute.
- •Reference example: 0.3333
- •Perfect overlap -> ~0
- •No overlap -> ~1
- •Two empty masks -> loss ~0 (smoothing)