Dice lossEasy

Dice loss

Background

Dice loss optimises overlap directly, which makes it the default for image segmentation with imbalanced foreground/background. It is 1Dice coefficient1 - \text{Dice coefficient}, 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):

Dice=2ipiti+smoothipi+iti+smooth,L=1Dice\text{Dice} = \frac{2\sum_i p_i\,t_i + \text{smooth}}{\sum_i p_i + \sum_i t_i + \text{smooth}}, \qquad \mathcal{L} = 1 - \text{Dice}

Input

  • prednp.ndarray: predicted mask (probabilities in [0,1][0, 1] or binary).
  • targetnp.ndarray: ground-truth mask (0/1), same shape.
  • smoothfloat: smoothing term to avoid division by zero.

Output

Returns a float in [0,1][0, 1] (0 = perfect overlap).

Examples

Example 1

Input:  pred = [1, 1, 0, 0], target = [1, 0, 0, 0]
Output: 0.3333

Explanation: intersection pt=1\sum p\,t = 1; p=2\sum p = 2, t=1\sum t = 1. Dice =2(1)/(2+1)=2/3= 2(1)/(2+1) = 2/3, so loss =12/3=0.3333= 1 - 2/3 = 0.3333.

Constraints

  • The Dice numerator is 2×2\times the elementwise-product sum; the denominator is the sum of both masks (with smooth added to both).
  • Loss =1Dice= 1 - \text{Dice}: 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: 2TP/(2TP+FP+FN)2\text{TP}/(2\text{TP}+\text{FP}+\text{FN}) for binary masks.
  • The smoothing term keeps the loss well-defined (→ 0) when both masks are empty, where Dice would otherwise be 0/00/0.
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)