← back

Calculate Dice Score for Classification

#73 · Machine Learning · Easy

⊣ Solve on deep-ml.com

Problem

Calculate the Dice Score (Dice Coefficient) for binary classification. The Dice score is similar to the F1 score and measures overlap between predicted and actual positive labels.

Solution

1
2
3
4
5
6
7
8
9
10
def dice_score(y_true, y_pred):
    tp = sum(1 for t, p in zip(y_true, y_pred) if t == 1 and p == 1)
    fp = sum(1 for t, p in zip(y_true, y_pred) if t == 0 and p == 1)
    fn = sum(1 for t, p in zip(y_true, y_pred) if t == 1 and p == 0)

    denominator = 2 * tp + fp + fn
    if denominator == 0:
        return 1.0

    return round((2 * tp) / denominator, 4)

Explanation

  1. Count TP, FP, and FN from the true and predicted labels.
  2. Dice Score = 2 TP / (2 TP + FP + FN).
  3. Equivalent to the F1 score for binary classification.
  4. Ranges from 0 (no overlap) to 1 (perfect match).
  5. Commonly used in image segmentation to measure overlap between predicted and ground-truth masks.

Complexity

  • Time: O(n) where n is the number of samples
  • Space: O(1)