Dice Loss: Scoring How Much Two Masks Overlap

Loss FunctionsMedium+10 XP+10

Dice Loss: Scoring How Much Two Masks Overlap

Dice loss comes from image segmentation, where most pixels are background and a plain per-pixel loss barely notices the small foreground region. It instead measures the overlap between the predicted and true masks directly.

Dice=2∑(ytrue⋅ypred)+smooth∑ytrue+∑ypred+smooth\text{Dice} = \frac{2 \sum (y_{\text{true}} \cdot y_{\text{pred}}) + \text{smooth}}{\sum y_{\text{true}} + \sum y_{\text{pred}} + \text{smooth}}Dice=∑ytrue​+∑ypred​+smooth2∑(ytrue​⋅ypred​)+smooth​

Task: write dice_loss(y_true, y_pred, smooth) returning 1 - Dice, rounded to 4 decimal places.

  • y_true and y_pred are flat lists of values in [0, 1] — a mask and a prediction, one value per pixel.
  • smooth keeps the loss defined even when both masks are entirely empty; without it that case would divide by zero.

Examples

y_true = [1, 0, 1, 1]
y_pred = [0.9, 0.1, 0.8, 0.7]
smooth = 1.0
returns 0.1077
y_true = [1, 1, 1]
y_pred = [1, 1, 1]
smooth = 1.0
returns 0.0

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run