BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Debug and fix6 of 16 in topic

861. Fix the F1 score that crashes on empty predictions

EasyDebug and fix

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.

Functiondef 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.
Topics
Debug and fix
Similar questions
  • Fix the softmax that returns nanEasy
  • Fix the LayerNorm that normalises the wrong axisEasy
  • Fix the cross-entropy that returns infEasy
  • Fix the agent memory shared between conversationsEasy
All Debug and fix problems
Report
861 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
7
8
9
10
11
12
import numpy as np
​
def f1_score(y_true, y_pred):
t = np.asarray(y_true)
p = np.asarray(y_pred)
tp = int(((t == 1) & (p == 1)).sum())
fp = int(((t == 0) & (p == 1)).sum())
fn = int(((t == 1) & (p == 0)).sum())
precision = tp / (tp + fp)
recall = tp / (tp + fn)
return round(2 * precision * recall / (precision + recall), 4)
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 7 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS