#72 · Machine Learning · Easy
⊣ Solve on deep-ml.comCalculate 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.
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)