861. Fix the F1 score that crashes on empty predictions
Why it matters Metric code that crashes on a quiet batch takes down evaluation jobs. Every metric needs a rule for empty denominators.
The starter code below runs, but it has a realistic bug. Read the spec, find the bug and fix it. Keep the function name and signature.
f1_score(y_true, y_pred) should return the binary F1 score for the positive class 1. Precision = tp / (tp + fp) and recall = tp / (tp + fn). If tp + fp == 0, precision is 0.0. If tp + fn == 0, recall is 0.0. If precision + recall == 0, F1 is 0.0. Otherwise F1 = 2 * p * r / (p + r).
Inputs: y_true and y_pred are lists or ndarrays of 0s and 1s with the same length (length >= 1).
Return a Python float rounded to 4 decimals.
def f1_score(y_true, y_pred)Example 1
Input: f1_score([1, 0, 1, 1], [1, 1, 0, 1])
Output: 0.6667
Example 2
Input: y_true = [1, 1, 0], y_pred = [0, 0, 0]
Output: 0.0
Example 3
Input: y_true = [1, 0], y_pred = [1, 0]
Output: 1.0
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 7 tests to be accepted.
Hint 1
Run the test with no positive predictions. Which line fails?
Hint 2
Guard each denominator separately.
Hint 3
Guard the final division as well.
Common mistakes
- Returning nan instead of 0.0.
- Catching the error with a bare except and returning 1.0.
- Rounding before the final division.
Understand the idea
When a model predicts no positives, tp + fp is 0 and Python raises ZeroDivisionError. The usual convention, also used by scikit-learn's zero_division=0, is to set that precision or recall to 0. When both are 0, F1 is 0 as well.
Shapes and data flow
Two 1D arrays of equal length. Output: scalar.