Classification Metrics
Confusion matrix, accuracy, precision, recall, F1, ROC-AUC and precision–recall curves — what each one measures, how the decision threshold trades them off, and why accuracy lies on imbalanced data.
A Classification model rarely outputs a hard 'yes/no'. It outputs a score (often a probability), and you turn it into a decision with a Decision threshold. How good the model is depends on which mistakes you care about: missing a cancer is not the same as a false alarm; blocking a legitimate payment is not the same as letting fraud through. This lesson gives you the vocabulary — and the habit — to pick the right metric before you train anything.
The confusion matrix
Every binary metric is built from the four cells of the Confusion matrix: compare each prediction with the true Label (target).
| Predicted positive | Predicted negative | |
|---|---|---|
| Actually positive | TP — true positive (hit) | FN — false negative (miss, Type II error) |
| Actually negative | FP — false positive (false alarm, Type I error) | TN — true negative (correct rejection) |
confusion_matrix puts true labels in rows and predictions in columns, ordered by label value (so for 0/1 labels the first row is the negative class).The core metrics
- TP
- true positives: actually positive and predicted positive (hits)
- TN
- true negatives: actually negative and predicted negative
- FP
- false positives: actually negative but predicted positive (false alarms)
- FN
- false negatives: actually positive but predicted negative (misses)
- Accuracy
- Accuracy: share of all predictions that are correct
- Precision
- Precision: purity of the positive predictions
- Recall
- Recall: coverage of the real positives
- sensitivity
- another name for recall (common in medicine)
- TPR
- true positive rate = recall; the y-axis of the ROC curve (ROC curve & AUC)
- Specificity
- true negative rate: share of real negatives correctly rejected
- FPR
- false positive rate = FP / (FP + TN); the x-axis of the ROC curve
- F1
- F1 score: harmonic mean of precision and recall
- P
- shorthand for precision
- R
- shorthand for recall
▸Worked example
- [[accuracy|Accuracy]] — fraction of all predictions that are correct. Fine when classes are balanced and errors cost the same.
- [[precision|Precision]] — 'when the model says positive, how often is it right?' Optimize it when false positives are expensive (spam filter deleting real mail, sending an unnecessary technician).
- [[recall|Recall]] — 'of all real positives, how many did we find?' Optimize it when misses are expensive (disease screening, fraud, safety defects).
- [[f1-score|F1]] — single number balancing both. The Fβ score generalizes it: β > 1 weights recall more (F2 is common in screening), β < 1 weights precision more.
Worked example: the accuracy paradox
1,000 patients, 10 of them sick (1% prevalence). Model A always says 'healthy': TP = 0, FN = 10, FP = 0, TN = 990 → accuracy 99%, recall 0%. It is useless, yet it beats most real models on accuracy. Model B flags 48 patients: TP = 8, FN = 2, FP = 40, TN = 950 → accuracy 95.8% (lower!), recall 8/10 = 80%, precision 8/48 ≈ 16.7%, F1 ≈ 0.28. Model B is far more useful as a screening tool. This is why on imbalanced data you always compare against a Baseline (here: 'always negative' = 99% accuracy) and report precision/recall, not only accuracy.[4]
The threshold trades precision for recall
With a score s(x) ∈ [0, 1], you predict positive when s(x) ≥ t. Lowering t labels more examples positive: TP and FP both grow, so recall rises and precision usually falls. Raising t does the opposite. The default t = 0.5 is just a convention — choose t from the costs of errors, a required recall ('catch at least 95% of fraud'), or a capacity limit ('we can review 200 cases per day'). Always choose it on the validation set, never on the test set.
ROC curve and AUC
Sweep the threshold from 1 down to 0 and plot TPR (recall) on the y-axis against FPR = FP/(FP+TN) on the x-axis: that is the ROC curve. A random classifier lies on the diagonal; a perfect one hugs the top-left corner. The area under it, [[roc-auc|ROC-AUC]], has a neat meaning: the probability that a randomly chosen positive gets a higher score than a randomly chosen negative.[2] AUC = 0.5 is chance, 1.0 is perfect ranking. Because ROC uses rates *within* each class, it does not change when you change the class ratio — which is both its strength and its weakness.
Precision–recall curve (use it for imbalanced data)
The PR curve plots precision (y) against recall (x) over all thresholds; its summary is average precision (AP). With rare positives, a small FPR can still mean a huge number of false positives (1% of a million negatives = 10,000 false alarms), so ROC-AUC can look excellent while precision is terrible. Saito & Rehmsmeier showed the PR plot is more informative than ROC on imbalanced datasets.[3] Note the baseline differs: a random classifier has ROC-AUC 0.5 but AP ≈ the positive rate (e.g. 0.01 for 1% positives), so an AP of 0.3 can actually be a strong result.
- Move the threshold left and right. Watch FP and FN trade places in the confusion matrix, and the dot slide along both the ROC and PR curves. Find the threshold that maximizes F1.
- Increase class separation: the histograms pull apart, the ROC curve bulges toward the top-left, AUC → 1. The threshold matters less when the model separates classes well.
- Lower the positive % to ~1–5% while keeping separation fixed. Notice: ROC-AUC barely changes, accuracy goes *up*, but precision and the PR curve collapse. That is the accuracy paradox live.
- With heavy imbalance, push the threshold very high: accuracy approaches the 'always negative' baseline while recall drops to 0.
Knobs
- What it is
- Score cut-off above which an example is predicted positive. Applied after training; it does not change the model, only its decisions.
- ↑ If you increase it
- Fewer positives predicted: precision ↑, recall ↓, FP ↓, FN ↑.
- ↓ If you decrease it
- More positives predicted: recall ↑, precision ↓, FP ↑, FN ↓.
- Typical values
- 0.5 by default; tune on validation data to hit a target recall/precision or maximize F1 / expected profit.
- What it is
- Fβ = (1 + β²)·P·R / (β²·P + R). β says how many times more you value recall than precision.
- ↑ If you increase it
- β > 1 (e.g. F2): the metric rewards recall; the best threshold moves lower.
- ↓ If you decrease it
- β < 1 (e.g. F0.5): the metric rewards precision; the best threshold moves higher.
- Typical values
- 1 (F1); 2 for screening; 0.5 for high-precision alerting.
- What it is
- Training-time weight on each class's loss (scikit-learn
class_weight='balanced', PyTorchCrossEntropyLoss(weight=...)orBCEWithLogitsLoss(pos_weight=...)). - ↑ If you increase it
- Higher weight on the rare class: the model pays more attention to it → recall on that class ↑, more false positives, probabilities become less calibrated.
- ↓ If you decrease it
- Back toward uniform weights: the model optimizes overall accuracy and may ignore the minority class.
- Typical values
- None, or 'balanced' (inverse class frequency). Often threshold tuning alone gives a similar effect.
- What it is
- How per-class precision/recall/F1 are combined for more than two classes:
macro(plain mean over classes),weighted(mean weighted by class support),micro(pool all TP/FP/FN globally). - ↑ If you increase it
- Toward
macro: every class counts equally, so poor performance on rare classes is exposed. - ↓ If you decrease it
- Toward
micro/weighted: dominated by frequent classes (micro-F1 equals accuracy in single-label multiclass). - Typical values
- Report macro-F1 plus the per-class table.
In code (scikit-learn)
from sklearn.metrics import (classification_report, confusion_matrix,
roc_auc_score, average_precision_score,
precision_recall_curve)
import numpy as np
proba = model.predict_proba(X_val)[:, 1] # score for the positive class
y_pred = (proba >= 0.5).astype(int)
print(confusion_matrix(y_val, y_pred)) # [[TN FP] [FN TP]]
print(classification_report(y_val, y_pred, digits=3))
print("ROC-AUC:", roc_auc_score(y_val, proba)) # threshold-free
print("AP :", average_precision_score(y_val, proba))
print("baseline AP (positive rate):", y_val.mean())
# Pick the threshold that gives at least 90% recall with the best precision
prec, rec, thr = precision_recall_curve(y_val, proba)
ok = rec[:-1] >= 0.90
t_best = thr[ok][np.argmax(prec[:-1][ok])]
print("threshold for recall>=0.9:", t_best)precision_recall_curve returns one more precision/recall value than thresholds, hence the [:-1].▸Go deeper: log loss, MCC and calibration
Log loss (Cross-entropy (log loss)) evaluates the probabilities themselves, not just decisions: −(1/n)·Σ[y·ln p + (1−y)·ln(1−p)]. It is what the model trains on and punishes confident mistakes heavily.
sklearn.metrics.matthews_corrcoef).- MCC
- Matthews correlation coefficient, between −1 and +1
- TP
- true positives
- TN
- true negatives
- FP
- false positives (false alarms)
- FN
- false negatives (misses)
- ·
- multiplication
- √
- square root of the product of the four totals: predicted positives, actual positives, actual negatives, predicted negatives
▸Worked example
Calibration asks whether 'p = 0.8' really means 80% of such cases are positive. Check it with a reliability diagram (sklearn.calibration.CalibrationDisplay) and fix it with CalibratedClassifierCV (Platt/sigmoid or isotonic). AUC measures ranking only — a model can have a great AUC and badly calibrated probabilities.[1]
Quiz
References
- [1]scikit-learn User Guide — Metrics and scoring: quantifying the quality of predictionsDocsscikit-learn developersscikit-learn.org
- [2]
- [3]The Precision-Recall Plot Is More Informative than the ROC Plot When Evaluating Binary Classifiers on Imbalanced DatasetsPaperSaito & Rehmsmeier2015doi.orgPLOS ONE 10(3): e0118432.
- [4]Machine Learning Crash Course — ClassificationCourseGoogledevelopers.google.com