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