PIXELBANKv9.1.0
Menu

Dice Coefficient (F1 Score)

You are given predicted and ground truth binary masks and need to calculate the Dice coefficient, also known as the F1 score.

The Dice coefficient measures overlap between two binary masks:

Dice=2∣A∩B∣∣A∣+∣B∣=2⋅TP2⋅TP+FP+FNDice = \frac{2|A \cap B|}{|A| + |B|} = \frac{2 \cdot TP}{2 \cdot TP + FP + FN}

Where:

  • |A ∩ B| = number of pixels that are 1 in both masks (intersection)
  • |A| = number of pixels that are 1 in prediction
  • |B| = number of pixels that are 1 in ground truth

Dice ranges from 0 (no overlap) to 1 (perfect overlap).

This metric is especially popular in medical image segmentation where foreground (e.g., tumor) is often a small fraction of the image.

Example:

Input:
pred = [[1, 1], [0, 0]]
gt = [[1, 0], [0, 0]]
Output:
0.6667
Reasoning:

Count pixels:

  • Intersection (both=1): position (0,0) → 1 pixel
  • pred=1: positions (0,0), (0,1) → 2 pixels
  • gt=1: position (0,0) → 1 pixel

Dice = 2 × intersection / (|pred| + |gt|) = 2 × 1 / (2 + 1) = 2/3 = 0.6667

Constraints:

  • pred and gt are 2D binary masks (values are 0 or 1)
  • Return Dice coefficient rounded to 4 decimal places
  • If both masks are all zeros, return 1.0 (perfect match of empty sets)
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Dice Coefficient (F1 Score) - Medium | PixelBank