Level 3 In-Depth AI · Classical Machine Learning
Evaluation Metrics
How to score a model so the number means something. Accuracy can be badly misleading; precision, recall, ROC and precision–recall curves, calibration and the regression metrics each answer a different question, and the right one is the one that matches what mistakes cost you.
- Level
- ●●●●● Easy
- Reading
- 15 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 12 concepts →
- Quiz
- 5 questions ↓
This leads to
Evaluating LLMs and BenchmarksThe full path from zero — 12 concepts before this one
- What Is AI?
- Derivatives and Slopes
- Vectors
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- Training, Validation and Test Sets
- Logistic Regression
- Evaluation Metrics
Read them roughly in this order. See it on the concept map →
Why it matters
Once you have a model you need a number that says how good it is. That number decides which model you ship, which experiment you continue, and whether the project gets funded. Choose the wrong number and you optimise the wrong thing.
The classic trap is accuracy on imbalanced data. If 1 in 1,000 card payments is fraud, a "model" that says "not fraud" to everything is 99.9% accurate and completely useless. Real systems are full of such imbalance: rare diseases, equipment failures, the few relevant documents among millions in search. The metrics in this chapter (precision, recall, ROC and precision–recall curves, calibration) were invented to see through it.
Metrics also encode values. A cancer screen that misses a tumour and a screen that sends a healthy person for a biopsy make very different mistakes. A good metric weighs them the way the real situation does. This chapter gives you the standard tools and, more importantly, the habit of asking what does a mistake cost here? The same habit carries over to evaluating language models and AI applications.
The intuition
Think of a smoke alarm. It can go wrong in two ways:
- It stays silent during a fire. That is a false negative: the thing was there and you said it wasn't. A missed case.
- It goes off when you burn toast. That is a false positive: you said the thing was there and it wasn't. A false alarm.
You can trade one for the other by adjusting the sensitivity. Make the alarm hair-trigger and it never misses a fire, but shrieks at every slice of toast. Make it sluggish and it never bothers you, but might sleep through a real fire. No setting eliminates both. A classifier that outputs a probability is exactly like this: the decision threshold is the sensitivity knob, and every metric below describes the trade-off from a different angle.
Two questions capture most of it:
- Precision: when the alarm goes off, how often is there really a fire?
- Recall: when there is a fire, how often does the alarm go off?
Key idea Accuracy hides the type of mistake. Count the four outcomes (true and false positives, true and false negatives), then pick the metric that weighs missed cases against false alarms the way your problem does. For ranking quality across all thresholds use ROC AUC, or average precision when positives are rare.
How it works
The confusion matrix
Every prediction of a two-class model falls into one of four boxes. Call the class you are looking for (sick, fraud, spam) positive.
- True positive (TP): actually positive, predicted positive. A correct catch.
- False negative (FN): actually positive, predicted negative. A miss.
- False positive (FP): actually negative, predicted positive. A false alarm.
- True negative (TN): actually negative, predicted negative. A correct all-clear.
Laid out as a 2×2 table, this is the confusion matrix. Statisticians call a false positive a type I error and a false negative a type II error.
A worked example by hand
A screening test is run on 1,000 people, of whom 50 are sick. It flags 130 people: 40 sick and 90 healthy. So TP = 40, FN = 10, FP = 90, TN = 860.
Accuracy, the fraction of predictions that are correct:
That sounds good until you notice that calling everyone healthy gives . With class imbalance, where one class is much rarer than the other, accuracy rewards ignoring the rare class.
Precision, of everything flagged, the fraction that was really positive:
Only 31% of the people sent for follow-up are actually sick.
Recall (also called sensitivity or the true positive rate), of all real positives, the fraction caught:
The test catches 80% of sick people and misses 20%.
Specificity, of all real negatives, the fraction correctly cleared: . Its complement, , is the false positive rate: 9.5% of healthy people get a false alarm.
F1 score, a single number that balances precision and recall:
F1 is the harmonic mean, which stays low if either input is low. A model with precision 1.0 and recall 0.01 has F1 of about 0.02, not 0.5. If you care more about one side, the general score weights recall times as much as precision ( for recall-heavy problems).
Which one matters?
- Missing a positive is very costly (cancer screening, fraud, safety faults): prioritise recall, then make precision as good as you can.
- False alarms are very costly (spam filters that might bin an important email, recommending content that must be appropriate, automated legal actions): prioritise precision.
- Both matter and positives are rare: F1, or the precision–recall curve below.
- Classes are balanced and errors cost about the same: accuracy is fine.
The threshold sets the trade-off
A probabilistic classifier outputs a score, and you choose where to cut. Lowering the threshold flags more examples, so recall rises and precision usually falls. Raising it does the opposite.
On that test set (real numbers from the code below):
| Threshold | TP | FP | FN | TN | Precision | Recall |
|---|---|---|---|---|---|---|
| 0.9 | 56 | 0 | 8 | 107 | 1.000 | 0.875 |
| 0.5 | 60 | 4 | 4 | 103 | 0.938 | 0.938 |
| 0.1 | 63 | 14 | 1 | 93 | 0.818 | 0.984 |
For a cancer screen, 0.1 is probably the better operating point: one missed tumour instead of four, at the cost of ten more biopsies. Choose the threshold on validation data, using the real costs, and never on the test set.
ROC curves and AUC
To judge the model across all thresholds at once, sweep the threshold from 1 down to 0 and plot, at each setting, the true positive rate (recall) against the false positive rate. This is the ROC curve (receiver operating characteristic, a name from radar engineering in the Second World War).
A perfect model shoots straight up to a true positive rate of 1 at a false positive rate of 0. Random guessing follows the diagonal. The area under the ROC curve (AUC) summarises it in one number: 1.0 is perfect, 0.5 is random.
AUC has a lovely interpretation: it is the probability that a randomly chosen positive gets a higher score than a randomly chosen negative. That makes it easy to compute by hand. Suppose three positives score 0.9, 0.7 and 0.4, and three negatives score 0.6, 0.3 and 0.2. Of the positive–negative pairs, the positive wins in 8 (only 0.4 versus 0.6 is wrong), so AUC .
AUC measures ranking. It doesn't care about the threshold or whether the scores are good probabilities, and it is unaffected by the class balance. That last property is a weakness when positives are rare: with 1 positive per 10,000, a false positive rate of 1% means 100 false alarms per real catch, yet the ROC curve looks excellent.
Precision–recall curves
The precision–recall curve plots precision against recall across thresholds. Its random baseline is a flat line at the share of positives (0.37 in the figure; 0.001 for rare fraud), so it shows plainly how hard the rare-class problem is. Its area is summarised as average precision. Prefer it to ROC AUC when positives are rare and you care about the flagged list being clean.
Calibration
Ranking is not everything. If a model says "70% chance of rain", it should rain on about 70% of such days. A model whose probabilities match observed frequencies is well calibrated. You need this whenever the number itself drives a decision: pricing insurance, triaging patients by risk, combining models.
Check it with a reliability diagram: group predictions into bins (0–10%, 10–20%…) and plot the average predicted probability against the actual fraction of positives in each bin. A calibrated model lies on the diagonal. The Brier score, the mean squared difference between predicted probability and the 0/1 outcome, measures calibration and sharpness together: 0 is perfect, and always predicting 0.5 scores 0.25. Logistic regression is usually fairly well calibrated. Many other models (boosted trees, SVMs, neural networks trained to overconfidence) need fixing, for example with scikit-learn's CalibratedClassifierCV.
Many classes
For more than two classes, compute precision, recall and F1 per class, then average. Macro-averaging gives each class equal weight, so rare classes count as much as common ones. Weighted averaging weights by class size. Micro-averaging pools all decisions, and for single-label problems equals accuracy. The confusion matrix becomes and shows which classes are confused with which. For image classifiers, top-5 accuracy (is the right answer among the five highest-scoring classes?) is also common.
Regression metrics
For numeric predictions, the errors are the residuals . On the four students from Linear Regression (actual 3, 5, 7, 8; predicted 3.2, 4.9, 6.6, 8.3):
- Mean absolute error (MAE): the average size of a miss, points. Easy to explain and robust to outliers.
- Root mean squared error (RMSE): . In the label's units, but weights big misses more heavily. RMSE is always at least MAE. A large gap between them signals a few big errors.
- Coefficient of determination (): the fraction of the label's variation the model explains. . 1 is perfect, 0 is no better than always predicting the mean, and it can be negative on test data for a really bad model.
- Mean absolute percentage error (MAPE): the average of . Intuitive for business ("we're 8% off on average") but explodes when true values are near zero.
In code
The confusion-matrix counts and precision, recall and F1 from scratch, at three thresholds, plus AUC computed literally as "the fraction of positive–negative pairs ranked correctly". The positive class is malignant:
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
y = 1 - y # make 1 = malignant, the class we hunt for
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)
model = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_tr, y_tr)
p = model.predict_proba(X_te)[:, 1] # predicted P(malignant)
def report(threshold):
pred = (p >= threshold).astype(int)
tp = np.sum((pred == 1) & (y_te == 1)); fp = np.sum((pred == 1) & (y_te == 0))
fn = np.sum((pred == 0) & (y_te == 1)); tn = np.sum((pred == 0) & (y_te == 0))
precision, recall = tp / (tp + fp), tp / (tp + fn)
f1 = 2 * precision * recall / (precision + recall)
print(f"t={threshold}: TP {tp} FP {fp} FN {fn} TN {tn} | "
f"precision {precision:.3f} recall {recall:.3f} F1 {f1:.3f}")
for t in [0.5, 0.1, 0.9]:
report(t)
# ROC AUC = probability a random positive scores higher than a random negative
pos, neg = p[y_te == 1], p[y_te == 0]
auc = np.mean(pos[:, None] > neg[None, :]) + 0.5 * np.mean(pos[:, None] == neg[None, :])
print(f"AUC by counting pairs: {auc:.4f}")
# t=0.5: TP 60 FP 4 FN 4 TN 103 | precision 0.938 recall 0.938 F1 0.938
# t=0.1: TP 63 FP 14 FN 1 TN 93 | precision 0.818 recall 0.984 F1 0.894
# t=0.9: TP 56 FP 0 FN 8 TN 107 | precision 1.000 recall 0.875 F1 0.933
# AUC by counting pairs: 0.9917
The same with scikit-learn's metric functions:
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import (confusion_matrix, classification_report, roc_auc_score,
average_precision_score, brier_score_loss)
X, y = load_breast_cancer(return_X_y=True)
y = 1 - y # 1 = malignant
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)
model = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_tr, y_tr)
p = model.predict_proba(X_te)[:, 1]
print(confusion_matrix(y_te, p >= 0.5)) # rows: true 0, 1; columns: predicted 0, 1
print(classification_report(y_te, p >= 0.5, target_names=["benign", "malignant"], digits=3))
print("ROC AUC: ", round(roc_auc_score(y_te, p), 4))
print("average precision:", round(average_precision_score(y_te, p), 4))
print("Brier score: ", round(brier_score_loss(y_te, p), 4))
# [[103 4]
# [ 4 60]]
# precision recall f1-score support
#
# benign 0.963 0.963 0.963 107
# malignant 0.938 0.938 0.938 64
#
# accuracy 0.953 171
# macro avg 0.950 0.950 0.950 171
# weighted avg 0.953 0.953 0.953 171
#
# ROC AUC: 0.9917
# average precision: 0.9887
# Brier score: 0.0326
Note scikit-learn's layout: rows are the true class, columns the predicted class, both in the order 0, 1. So the top-right 4 is false positives and the bottom-left 4 is false negatives. Other tools use other layouts; always check. The pair-counting AUC matches roc_auc_score exactly. For regression, sklearn.metrics has mean_absolute_error, mean_squared_error, root_mean_squared_error and r2_score.
Common pitfalls
- Accuracy on imbalanced data. Always compare with the trivial baseline that predicts the majority class.
- Forgetting which class is "positive". Precision and recall depend on it. In the breast-cancer dataset as shipped, 1 means benign, so
precision_score(y, pred)measures the wrong thing unless you flip it. - Tuning the threshold on the test set. The threshold is a hyperparameter. Choose it on validation data.
- Reporting ROC AUC alone for rare events. A 0.99 AUC can coexist with a precision of 5%. Show the precision–recall curve or the precision at the threshold you will use.
- Trusting probabilities without checking calibration, especially after oversampling the rare class during training, which inflates predicted probabilities.
- Metric mismatch. Optimising for one metric and being judged on another. Decide the metric with the people who will use the model before building it.
Watch out Goodhart's law: when a measure becomes a target, it ceases to be a good measure. Any single metric can be gamed by a model (or a team) that optimises it hard enough. Watch several metrics, read individual errors, and check that improvements show up in the real outcome you care about.
Where it leads
- Cross-Validation: average any metric over folds for a steadier estimate.
- Hyperparameter Tuning: the metric you choose is what the search optimises (
scoring=in scikit-learn). - Data Cleaning and Preparation: handling class imbalance with weights or resampling.
- Bias and Fairness: compare error rates across groups; a model can be accurate overall and much worse for some people.
- Anomaly Detection: an extreme case of imbalance where precision–recall thinking is essential.
- Evaluating LLMs and Benchmarks and Evaluating LLM Applications: evaluation for generative models, where "correct" is harder to define.
A bit of history
ROC analysis came from signal detection theory, developed in the 1940s and 1950s to describe how well radar operators distinguished enemy aircraft from noise. Psychologists adopted it in the 1950s and 1960s to study perception, and medicine in the 1970s and 1980s to evaluate diagnostic tests, where sensitivity and specificity were already standard. Hanley and McNeil (1982) popularised the AUC in radiology and its interpretation as a ranking probability. Precision and recall come from information retrieval in the 1950s and 1960s, where researchers such as Cyril Cleverdon measured how well library search systems found relevant documents. C. J. van Rijsbergen introduced the F-measure in the 1970s. The Brier score is older still: Glenn Brier proposed it in 1950 to score probabilistic weather forecasts. Tom Fawcett's 2006 tutorial made ROC analysis standard in machine learning.
Try it
- A fraud model flags 200 of 100,000 transactions. 150 of the flagged ones are fraud, and there are 300 frauds in total. Compute precision, recall, the false positive rate and accuracy. Which number looks misleadingly good?
- Compute the AUC by hand for positive scores 0.8, 0.6, 0.55 and negative scores 0.7, 0.5, 0.1, 0.05.
- In the code, find the highest threshold that gives recall of at least 0.98 on the test set. Then explain why you should really have chosen it on a validation set.
Hint for 1: TP = 150, FP = 50, FN = 150. Accuracy is 99.8% even though half the fraud is missed.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Machine Learning Crash Course
Short, practical lessons with interactive visualisations covering regression, classification, embeddings and neural nets.
MLU-Explain: ROC & AUC
Drag a threshold and watch the confusion matrix and ROC curve change; a clear visual introduction to ROC curves and the area under them.
MLU-Explain: Precision & Recall
An interactive explainer of precision, recall, the F1 score and the trade-off between them.
scikit-learn: Metrics and Scoring
Every classification, regression and ranking metric in scikit-learn (accuracy, precision, recall, ROC AUC, log loss, MSE, R² and more) with definitions and advice on choosing one.
StatQuest
Short, cheerful, very clear videos on statistics and nearly every ML algorithm.
An introduction to ROC analysis
The standard tutorial on ROC curves and AUC for machine learning: how to draw them, average them and avoid common mistakes (Pattern Recognition Letters).
An Introduction to Statistical Learning (with Python)
The friendliest rigorous introduction to classical ML, with Python labs. Free PDF.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/ml/evaluation-metrics.md