152. Compute precision, recall and F1 from predictions
Accuracy hides a lot when one class is rare. Precision asks how many flagged items were right; recall asks how many right items you flagged; F1 is their harmonic mean.
Write prf1(y_true, y_pred) for binary 0/1 lists. Return (precision, recall, f1). Define any 0 / 0 as 0.0.
def prf1(y_true, y_pred)Precision, recall and F1 as the threshold moves
Drag the threshold. Raising it trades recall for precision.
| predicted 1 | predicted 0 | |
|---|---|---|
| actual 1 | TP 114 | FN 36 |
| actual 0 | FP 33 | TN 117 |
- precision
- 0.776
- recall
- 0.76
- F1
- 0.768
- MCC
- 0.54
- ROC AUC
- 0.849
Synthetic scores made in your browser: 150 per class, sigmoid of a normal value centred at ±separation / 2. AUC counts every positive and negative pair.
Example 1
Input: y_true = [1, 0, 1, 1, 0, 0, 1], y_pred = [1, 1, 0, 1, 0, 0, 0]
Output: (0.666667, 0.5, 0.571429)
Example 2
Input: y_true = [1, 0, 1], y_pred = [0, 0, 0]
Output: (0.0, 0.0, 0.0)
Example 3
Input: y_true = [0, 1, 1], y_pred = [0, 1, 1]
Output: (1.0, 1.0, 1.0)
Constraints
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
Hint 1
Everything comes from three counts: true positives, false positives and false negatives.
Hint 2
Count tp, fp and fn by zipping the two lists, then precision = tp / (tp + fp), recall = tp / (tp + fn), and F1 = 2pr / (p + r).
Hint 3
Guard every division: if the denominator is 0, return 0.0 for that value, for example pr = tp / (tp + fp) if tp + fp else 0.0.
Common mistakes
- The buggy version swaps the denominators and uses the plain average.
Understand the idea
When positives are rare, accuracy can look great even if the model never finds them. Precision asks: of everything I flagged, how much was right? Recall asks: of everything truly positive, how much did I flag? F1 combines them with a harmonic mean, which stays low if either one is low. Think of a fishing net: precision is how many caught things are fish, recall is how many fish you caught.
y_true = [1, 1, 0, 0, 1], y_pred = [1, 0, 0, 0, 0]. True positives = 1, false positives = 0, false negatives = 2. Precision = 1 / 1 = 1.0. Recall = 1 / 3 = 0.333. F1 = 2 x 1 x 0.333 / (1 + 0.333) = 0.5, while a plain average would give 0.667.
P = TP / (TP + FP), R = TP / (TP + FN), F1 = 2PR / (P + R), with any 0 / 0 treated as 0.0
These metrics are standard for moderation, spam and retrieval classifiers.
Topics
Companies3
- Google the topic appears in interview reports Google Interview Prep (Deep-ML)
- Meta a candidate reported this question Timed ML screen: concept questions then classic models from scratch (Land the Lab)
- Microsoft a candidate reported this question Microsoft Machine Learning Engineer Interview Questions | Screna AI
From public interview reports and guides. Not affiliated with or endorsed by these companies.