InterviewPrepKit

Home / Coding / Machine Learning Coding / Metrics from Scratch / Precision, Recall, and F1

Precision, Recall, and F1

medium 00:00
Solving tips
  • Get the confusion-matrix counts first: TP, FP, FN. Everything else is a ratio of these.
  • Precision's denominator is TP+FP (predicted positives); recall's is TP+FN (actual positives). Don't swap them.
  • Guard every division: return 0.0 when the denominator is 0 instead of producing nan.

Implement precision, recall, and F1 from scratch with NumPy for a binary classifier, without calling a library metric function. These three numbers summarize how a model trades off catching positives against being right when it says positive, and interviewers use them to check that you know the confusion matrix cold and handle the empty-denominator edge cases.

Definition

Given binary labels (positive class is 1), form the confusion-matrix counts:

  • TP (true positives): predicted 1 and actually 1
  • FP (false positives): predicted 1 but actually 0
  • FN (false negatives): predicted 0 but actually 1

Then:

precision = TP / (TP + FP)
recall    = TP / (TP + FN)
F1        = 2 * precision * recall / (precision + recall)

Task

Complete precision_recall_f1(y_true, y_pred) so it returns the tuple (precision, recall, f1) as floats. Both inputs are 1-D NumPy arrays of the same length holding 0/1 labels. Whenever a denominator is 0, return 0.0 for that quantity instead of dividing. Do not call sklearn or any built-in precision/recall/F1 helper.

Example

y_true = np.array([1, 1, 0, 0, 1, 0])
y_pred = np.array([1, 0, 0, 1, 1, 0])
precision_recall_f1(y_true, y_pred)   # -> (0.6666666666666666, 0.6666666666666666, 0.6666666666666666)

Here TP = 2, FP = 1, FN = 1, so precision = 2/3, recall = 2/3, and F1 = 2/3.

Constraints

  • 1 <= n <= 10^6; use vectorized NumPy, not a Python loop.
  • Every label is exactly 0 or 1; the positive class is 1.
  • If TP + FP == 0, precision is 0.0; if TP + FN == 0, recall is 0.0; if precision + recall == 0, F1 is 0.0.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug