#140Dice lossEasy

Dice loss

Background

Dice loss optimises overlap directly, which makes it the default for image segmentation with imbalanced foreground/background. It is 1−Dice 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=2∑ipi ti+smooth∑ipi+∑iti+smooth,L=1−Dice\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

  • pred — np.ndarray: predicted mask (probabilities in [0,1][0, 1] 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,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 ∑p t=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 =1−2/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 =1−Dice= 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...

▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.

  • •Example: pred [1,1,0,0] vs target [1,0,0,0]
  • •Reference: perfect overlap gives zero loss
  • •Sample: disjoint masks give loss near one