Neural Mastery
← Practice
Precision, Recall & F1 From a Confusion Matrixeasy

Precision, Recall & F1 From a Confusion Matrix

easy Classical ML from Scratch 10–15 min

NumPy allowed · plain Python earns 10 bonus points

Linear algebra step 1/4

A vector transforms

Matrix multiplication is the first computation behind every model.
Open lesson →
01vector
02matrix
03transform
04result
[2, −1] × [[1, 2], [−.5, 1]] = [0, −2]

Computed matrix × vector transformation

Implement the three classification metrics that matter far more than raw accuracy whenever classes are imbalanced -- the numbers behind every "high accuracy, useless model" cautionary tale in ML.

Task

Implement precision_recall_f1(tp, fp, fn), returning a dict with keys 'precision', 'recall', and 'f1', computed from the standard formulas with explicit zero-division guards.

Function Signature

precision_recall_f1(tp: int, fp: int, fn: int) -> dict

Examples

Example 1: Typical Confusion Matrix
Input: tp = 50 fp = 10 fn = 5
Output: {'precision': 0.8333333333333334, 'recall': 0.9090909090909091, 'f1': 0.8695652173913043}
Example 2: No Positive Predictions At All
Input: tp = 0 fp = 0 fn = 5
Output: {'precision': 0, 'recall': 0, 'f1': 0}
Explanation: tp+fp == 0 -- precision is defined as 0.0, not undefined

Constraints

  • Libraries (standard library only) are allowed and accepted normally.
  • A plain-Python solution earns 10 bonus points.
  • precision = tp / (tp + fp), or 0.0 if tp + fp == 0.
  • recall = tp / (tp + fn), or 0.0 if tp + fn == 0.
  • f1 = 2 * precision * recall / (precision + recall), or 0.0 if precision + recall == 0.
Python3Saved ✓
def precision_recall_f1(tp: int, fp: int, fn: int) -> dict:
"""tp, fp, fn: true positive / false positive / false negative counts
for the positive class. Return {'precision': ..., 'recall': ...,
'f1': ...}. Define precision = 0.0 if tp+fp == 0, recall = 0.0 if
tp+fn == 0, and f1 = 0.0 if precision+recall == 0, instead of
dividing by zero."""
# Your implementation here
pass

Case 1: Typical Confusion Matrix
Input: tp = 50 fp = 10 fn = 5
Expected: {'precision': 0.8333333333333334, 'recall': 0.9090909090909091, 'f1': 0.8695652173913043}
Case 2: No Positive Predictions At All
Input: tp = 0 fp = 0 fn = 5
Expected: {'precision': 0, 'recall': 0, 'f1': 0}