AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
↘Training Results & Evaluation
  1. Reading Loss & Accuracy Curves
  2. Classification Metrics
  3. Regression Metrics & Validation
  4. Experiment Logging & Reproducibility
  5. Hyperparameter Tuning
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Training Results & Evaluation

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.

Intermediate~24 min·4 references
Key terms
Confusion matrixAccuracyPrecisionRecallF1 scoreDecision thresholdROC curve & AUCBaselineClassification

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 fishing net
You want to catch tuna (positives) without catching dolphins (negatives). Recall asks: of all the tuna in the sea, what fraction ended up in your net? Precision asks: of everything in your net, what fraction is tuna? A huge net (low threshold) catches nearly all the tuna — high recall — but also many dolphins — low precision. A tiny, selective net does the opposite.

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 positivePredicted negative
Actually positiveTP — true positive (hit)FN — false negative (miss, Type II error)
Actually negativeFP — false positive (false alarm, Type I error)TN — true negative (correct rejection)
scikit-learn's 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

Accuracy = (TP + TN) / (TP + TN + FP + FN) Precision = TP / (TP + FP) Recall = TP / (TP + FN) (= sensitivity = TPR) Specificity = TN / (TN + FP) (FPR = 1 − specificity) F1 = 2 · P · R / (P + R)
F1 is the harmonic mean of precision (P) and recall (R): it is high only if both are high.
In words: Read each line as a question about the Confusion matrix. Accuracy: what fraction of all predictions were right? Precision: of the cases flagged positive, how many really were? Recall: of the real positives, how many did we catch? Specificity: of the real negatives, how many did we correctly leave alone? F1 merges precision and recall into one number that is high only when both are.
Symbols(hover a symbol in the formula)
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
Spam filter on 100 emails: TP = 8, FN = 2, FP = 4, TN = 86 Accuracy = (8 + 86) / 100 = 0.94 Precision = 8 / (8 + 4) ≈ 0.667 (4 of the 12 flagged emails were not spam) Recall = 8 / (8 + 2) = 0.80 (caught 8 of the 10 spams) Specificity = 86 / (86 + 4) ≈ 0.956 → FPR ≈ 0.044 F1 = 2 · 0.667 · 0.8 / (0.667 + 0.8) ≈ 0.727 A filter that never flags anything: accuracy 0.90, but recall 0 and F1 0.
  • [[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.

Loading interactive…
Two overlapping score distributions, a movable threshold, live confusion matrix, ROC and PR curves.
  1. 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.
  2. 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.
  3. 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.
  4. With heavy imbalance, push the threshold very high: accuracy approaches the 'always negative' baseline while recall drops to 0.

Knobs

knobDecision threshold t
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.
knobβ in Fβ
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.
knobclass_weight
What it is
Training-time weight on each class's loss (scikit-learn class_weight='balanced', PyTorch CrossEntropyLoss(weight=...) or BCEWithLogitsLoss(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.
knobaverage (multiclass)
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)

python
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)
Metrics that need scores (ROC-AUC, AP) take probabilities, not hard labels. precision_recall_curve returns one more precision/recall value than thresholds, hence the [:-1].
!
Pitfalls
Reporting only accuracy on imbalanced data; computing ROC-AUC from hard 0/1 predictions instead of scores; tuning the threshold on the test set; comparing AP values across datasets with different positive rates; oversampling (e.g. SMOTE) *before* splitting, which leaks copies of validation examples into training; and forgetting that class weighting or resampling distorts predicted probabilities — recalibrate if you need real probabilities.
▸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.

MCC = (TP·TN − FP·FN) / √((TP+FP)(TP+FN)(TN+FP)(TN+FN))
Matthews correlation coefficient: from −1 to +1, uses all four cells, robust to imbalance (sklearn.metrics.matthews_corrcoef).
In words: “(product of the correct cells minus product of the wrong cells), divided by a normalizer built from the four row and column totals.” It is the correlation between predictions and truth: +1 perfect, 0 no better than chance, −1 always wrong. Because every cell enters, a model cannot score well just by predicting the majority class.
Symbols(hover a symbol in the formula)
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
Spam filter: TP = 8, TN = 86, FP = 4, FN = 2 Numerator: 8·86 − 4·2 = 688 − 8 = 680 Denominator: √(12 · 10 · 90 · 88) = √950,400 ≈ 974.9 MCC = 680 / 974.9 ≈ 0.70 Model B from the accuracy-paradox example (TP 8, FN 2, FP 40, TN 950): accuracy 95.8% but MCC ≈ 0.35 “Always negative”: MCC = 0 (scikit-learn returns 0 when the denominator is 0)

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

1.
A fraud dataset has 0.5% positives. A model predicts 'not fraud' for everything. What is its accuracy and recall?
2.
You lower the decision threshold from 0.5 to 0.2. What typically happens?
3.
What does ROC-AUC = 0.85 mean?
4.
On a dataset with 1% positives, which summary is usually most informative for comparing models?
5.
Precision = 0.9 and recall = 0.1. What is F1, approximately?
Score: 0/5

References

  1. [1]
    scikit-learn User Guide — Metrics and scoring: quantifying the quality of predictions
    Docsscikit-learn developersscikit-learn.org
  2. [2]
    An introduction to ROC analysis
    PaperFawcett2006doi.org
    Pattern Recognition Letters 27(8).
  3. [3]
    The Precision-Recall Plot Is More Informative than the ROC Plot When Evaluating Binary Classifiers on Imbalanced Datasets
    PaperSaito & Rehmsmeier2015doi.org
    PLOS ONE 10(3): e0118432.
  4. [4]
    Machine Learning Crash Course — Classification
    CourseGoogledevelopers.google.com
← Previous
Reading Loss & Accuracy Curves
Next →
Regression Metrics & Validation