← back

Implement F-Score Calculation for Binary Classification

#61 · Machine Learning · Easy

⊣ Solve on deep-ml.com

Problem

Implement the F-Score (F1 Score) calculation for binary classification. Given true labels and predicted labels, compute the F1 score, which is the harmonic mean of precision and recall.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
def f1_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)

    precision = tp / (tp + fp) if (tp + fp) > 0 else 0
    recall = tp / (tp + fn) if (tp + fn) > 0 else 0

    if precision + recall == 0:
        return 0.0

    f1 = 2 * precision * recall / (precision + recall)
    return round(f1, 4)

Explanation

  1. Count true positives (TP): both true and predicted are 1.
  2. Count false positives (FP): true is 0 but predicted is 1.
  3. Count false negatives (FN): true is 1 but predicted is 0.
  4. Precision = TP / (TP + FP), Recall = TP / (TP + FN).
  5. F1 Score = 2 Precision Recall / (Precision + Recall).

Complexity

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