← back

Calculate F1 Score from Predicted and True Labels

#91 · Machine Learning · Easy

⊣ Solve on deep-ml.com

Problem

Calculate the F1 score given predicted labels and true labels. The F1 score is the harmonic mean of precision and recall, providing a single metric that balances both false positives and false negatives.

Solution

1
2
3
4
5
6
7
8
9
10
11
def f1_score(y_true: list[int], y_pred: list[int]) -> float:
    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.0
    recall = tp / (tp + fn) if (tp + fn) > 0 else 0.0

    if precision + recall == 0:
        return 0.0
    return round(2 * precision * recall / (precision + recall), 4)

Explanation

  1. True Positives (TP): Count cases where both true and predicted are 1.
  2. False Positives (FP): Count cases where true is 0 but predicted is 1.
  3. False Negatives (FN): Count cases where true is 1 but predicted is 0.
  4. Precision = TP / (TP + FP): Of all positive predictions, how many are correct.
  5. Recall = TP / (TP + FN): Of all actual positives, how many were found.
  6. F1 = 2 precision recall / (precision + recall): The harmonic mean balances precision and recall.

Complexity

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