Precision, Recall and F1: When Accuracy Misleads

Metrics & EvaluationMedium+20 XP+15

Precision, Recall and F1: When Accuracy Misleads

Accuracy alone is a trap. A model that predicts "not fraud" every single time scores 99.9% on a dataset where fraud is one in a thousand — and is completely useless. The other three metrics are what expose that.

From the four confusion-matrix counts (TP, TN, FP, FN):

metricformulaquestion it answers
accuracy(TP + TN) / totalhow often am I right?
precisionTP / (TP + FP)when I say yes, am I right?
recallTP / (TP + FN)of the real positives, how many did I catch?
F12PR / (P + R)the harmonic mean of the two

Task: write classification_metrics(y_true, y_pred) for binary labels (1 positive, 0 negative), returning [accuracy, precision, recall, f1], each rounded to 4 decimal places.

  • Any metric whose denominator would be zero is 0.0.

F1 uses the harmonic mean rather than the ordinary one on purpose: it collapses toward whichever of the two is worse. Precision 1.0 with recall 0.01 averages to 0.5 the usual way, but F1 gives about 0.02 — which is a far more honest description of that model.

The Metric Dashboard

Click a metric to see exactly which cells it reads from.

Pred +
Pred −
Actual +
TP91
FN9
Actual −
FP20
TN880
AUC (given, ranking across thresholds)
0.93

Examples

y_true = [1, 0, 1, 1, 0, 1]
y_pred = [1, 0, 0, 1, 1, 1]
returns [0.6667, 0.75, 0.75, 0.75]
y_true = [1, 1, 1]
y_pred = [1, 1, 1]
returns [1.0, 1.0, 1.0, 1.0]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run