🧭 Do not search for the first 15 minutes. When stuck: re-read the requirements → define I/O → choose the data structure → trace a small example by hand → write code.
Implement classification_metrics(y_true, y_pred) — the confusion matrix and its
derived metrics for binary classification, without sklearn.
A staple of MLE interviews, and what separates answers is how you handle division by zero.
Two lists of the same length. Each element is 0 or 1.
y_true = [1, 1, 0, 1, 0]
y_pred = [1, 0, 0, 1, 1]
The positive class is 1.
TP = actual 1, predicted 1 FN = actual 1, predicted 0
FP = actual 0, predicted 1 TN = actual 0, predicted 0
{"tp": 2, "tn": 1, "fp": 1, "fn": 1,
"precision": 0.666667, "recall": 0.666667, "f1": 0.666667}
precision = TP / (TP + FP) ← denominator is "what we predicted positive"
recall = TP / (TP + FN) ← denominator is "what actually is positive"
f1 = 2·precision·recall / (precision + recall)
0.0.
precision = 0.0recall = 0.0precision + recall == 0 → f1 = 0.0round(x, 6)).[], []) gives four zero counts and three 0.0 metrics.Implement classification_metrics(y_true, y_pred).
tp, tn, fp, fn, precision, recall, f1.tp and friends) are ints; metrics are floats.