F1 Score

~15 mincode completion

Implement . Assume 2*TP + FP + FN > 0.

Examples

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

Input
f1_score([1, 0, 1, 0, 1], [1, 1, 1, 0, 0])
Output
0.66667

Perfect predictions: F1 = 1.0

Input
f1_score([1, 1, 0, 0], [1, 1, 0, 0])
Output
1

All predictions wrong (FN only): F1 = 0.0

Input
f1_score([1, 1, 1, 0], [0, 0, 0, 0])
Output
0

Hints

Hint 1

Sum with , and check which axis you are summing over.

Hint 2

Do not forget to fn in denominator. That step is easy to skip.

Requirements

  • y_true: Ground truth binary labels (0 or 1)

  • y_pred: Predicted binary labels (0 or 1)

  • Return F1 score in [0, 1].

Constraints

  • Allowed library: NumPy only

  • Time limit: 200 ms, Memory: 64 MB

Where this shows up

~15 min

8 employers weight this skill

3 AI product companies, 2 frontier labs, 1 health and bio company, 1 big tech firm, 1 autonomy company. Top match scores 93.

Python
import numpy as np

def f1_score(y_true: np.ndarray, y_pred: np.ndarray) -> float:
    """
    Compute F1 score = 2*TP / (2*TP + FP + FN).

    Args:
        y_true: Ground truth binary labels (0 or 1)
        y_pred: Predicted binary labels (0 or 1)

    Returns:
        F1 score in [0, 1].
    """
    # YOUR CODE HERE
    pass
Loading docs…

The AI Mentor needs an account

It reads your code and the failing tests and nudges you toward the fix without handing you the answer. Free accounts get it on every problem you're working on today.