easyMetrics
Precision, Recall and F1
Compute precision, recall and F1 from true and predicted binary labels, the metrics interviewers expect you to derive by hand, with the zero-division cases handled.
JavaScript or Python
Given two lists of the same length, y_true (actual labels) and y_pred (predicted labels), where every value is 0 or 1 and 1 means positive, return [precision, recall, f1].
Precision is TP / (TP + FP), recall is TP / (TP + FN), and F1 is their harmonic mean, 2PR / (P + R). When a denominator is zero (for example, the model predicts no positives), that metric is 0. Results are checked to six significant digits.
Examples
Example 1
Input: y_true = [1, 0, 1, 1, 0, 1], y_pred = [1, 1, 1, 0, 0, 1] Output: [0.75, 0.75, 0.75] Why: TP = 3, FP = 1, FN = 1
Example 2
Input: y_true = [1, 1, 0], y_pred = [0, 0, 0] Output: [0, 0, 0] Why: No predicted positives: precision is 0 by definition here, and recall is 0
Constraints
1 <= y_true.length == y_pred.length <= 10^5- Every value is 0 or 1
Hints
Hint 1
Count true positives, false positives and false negatives in one pass.
Hint 2
Guard each division: no predicted positives means precision 0; no actual positives means recall 0.
Solution
Show the solution (try it yourself first)
Walk the pairs once, counting TP (both 1), FP (predicted 1, actual 0) and FN (predicted 0, actual 1). Then apply the formulas, returning 0 whenever a denominator is zero, which also covers F1 when both precision and recall are 0.
def precision_recall_f1(y_true, y_pred):
tp = sum(1 for t, p in zip(y_true, y_pred) if t == 1 and p == 1)
fp = sum(1 for t, p in zip(y_true, y_pred) if t == 0 and p == 1)
fn = sum(1 for t, p in zip(y_true, y_pred) if t == 1 and p == 0)
precision = tp / (tp + fp) if tp + fp else 0.0
recall = tp / (tp + fn) if tp + fn else 0.0
f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
return [precision, recall, f1]Complexity
Time O(n), space O(1). True negatives don't appear in any of the three metrics, which is exactly why they are preferred over accuracy for imbalanced problems such as fraud or disease screening. Expect a follow-up on when you would favour precision (spam filtering) or recall (cancer screening), and on F-beta, which weights recall beta times as much as precision.
Found a mistake in this problem, its tests or the solution?