Compute the soft Dice loss

EasyLosses

Why it matters Medical and document-layout segmentation models use Dice for rare foreground pixels.

Segmentation models with tiny foreground regions train better on Dice than on pixel accuracy.

Write dice_loss(p, t, eps=1.0). p are predicted probabilities, t binary targets, same shape. Return 1 - (2 * sum(p * t) + eps) / (sum(p) + sum(t) + eps).

Signaturedef dice_loss(p, t, eps=1.0)

Example

dice_loss([1, 0], [1, 0]) is 1 - (2 * 1 + 1) / (1 + 1 + 1) = 0.0.

Understand the idea

In segmentation the object may cover only a tiny share of pixels, so pixel accuracy is fooled by predicting all background. Dice measures overlap instead: twice the shared area divided by the total area of prediction plus target. The soft version uses probabilities as fractional areas, so it is differentiable. Worked example: p = [0.8, 0.2, 0.6], t = [1, 0, 1], eps = 1. Overlap sum(p * t) = 0.8 + 0.6 = 1.4. sum(p) = 1.6 and sum(t) = 2. Dice = (2 * 1.4 + 1) / (1.6 + 2 + 1) = 3.8 / 4.6 = 0.826, so the loss is 1 - 0.826 = 0.174. Rule: loss = 1 - (2 * sum(p * t) + eps) / (sum(p) + sum(t) + eps), summing over all elements. The factor 2 makes a perfect prediction reach loss 0. The eps smooths the ratio and avoids 0/0 when both masks are empty. Used in: medical image segmentation such as U-Net models, and any task with heavy class imbalance at the pixel level.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: exampledice_loss([1, 0], [1, 0])
  • Sample 2: softdice_loss([[0.9, 0.2], [0.1, 0.7]], [[1, 0], [0, 1]])
  • Test 3: no overlapdice_loss([1, 1, 0], [0, 0, 1], eps=0.0)