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