Back to Practice
#0015
Precision, Recall, and F1
MediumML18 min15 XP
Problem
Given TP, FP, and FN counts, return a dictionary with precision, recall, and F1. If a denominator is zero, return 0 for that metric.
Why This Matters
These metrics explain different failure modes. Precision asks "when we predict positive, are we right?" Recall asks "of actual positives, how many did we catch?"
Function Signature
def classification_metrics(tp, fp, fn):
Examples
Example 1
Inputtp = 8, fp = 2, fn = 4
Outputprecision = 0.8, recall = 0.6667, f1 = 0.7273
8 of 10 predicted positives were right; 8 of 12 real positives were caught.
Constraints
- Counts are non-negative integers.
- Return floats in a dictionary.
- Handle zero denominators safely.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 4 hidden categories
Typical metric values
Inputtp=8, fp=2, fn=4
Expectedprecision 0.8, recall 0.6667, f1 0.7273
The F1 score is the harmonic mean of precision and recall.
No predicted positives
Inputtp=0, fp=0, fn=5
Expectedprecision 0, recall 0, f1 0
The function should not divide by zero.
Hidden Test Categories
Perfect precision and recallPrecision high but recall lowRecall high but precision lowAll zero counts