F1 Score

Easy
~15 min
code completion

F1 Score

F1 is the harmonic mean of precision and recall — a single metric that balances both:

where:

  • TP: predicted positive, actually positive
  • FP: predicted positive, actually negative
  • FN: predicted negative, actually positive
  • F1 = 1.0 means perfect precision and recall. F1 = 0.0 means at least one is zero.

    Your task:

    Implement f1_score(y_true, y_pred). Assume 2*TP + FP + FN > 0.

    Example Tests

    2 TP, 1 FP, 1 FN: F1 = 0.667

    Input: {"y_pred":[1,1,1,0,0],"y_true":[1,0,1,0,1]}

    Expected: 0.66667

    Perfect predictions: F1 = 1.0

    Input: {"y_pred":[1,1,0,0],"y_true":[1,1,0,0]}

    Expected: 1

    All predictions wrong (FN only): F1 = 0.0

    Input: {"y_pred":[0,0,0,0],"y_true":[1,1,1,0]}

    Expected: 0

    Sign in to solve this problem

    You can read the full problem statement above. Create a free account to run code in the browser, submit solutions, and track your progress.