← back

Calculate Jaccard Index for Binary Classification

#72 · Machine Learning · Easy

⊣ Solve on deep-ml.com

Problem

Calculate the Jaccard Index (Intersection over Union) for binary classification. Given true labels and predicted labels, compute the ratio of the intersection to the union of positive predictions.

Solution

1
2
3
4
5
6
7
8
9
10
def jaccard_index(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 = tp + fp + fn
    if denominator == 0:
        return 1.0

    return round(tp / denominator, 4)

Explanation

  1. Count true positives (TP): correctly predicted positives.
  2. Count false positives (FP): incorrectly predicted as positive.
  3. Count false negatives (FN): missed positives.
  4. Jaccard Index = TP / (TP + FP + FN), which is the intersection over the union.
  5. Ranges from 0 (no overlap) to 1 (perfect agreement). Also known as IoU (Intersection over Union).

Complexity

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