◆ AI All-in-One

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
↗ Plan a path here

Read first

Logistic RegressionTraining, Validation and Test Sets

This leads to

Evaluating LLMs and Benchmarks
The full path from zero — 12 concepts before this one
  1. What Is AI?
  2. Derivatives and Slopes
  3. Vectors
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Supervised, Unsupervised and Reinforcement Learning
  8. Gradient Descent
  9. Supervised Learning
  10. Linear Regression
  11. Training, Validation and Test Sets
  12. Logistic Regression
  13. 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.

Predicted sick (positive) healthy (negative) Actual sick (50) healthy (950) TP = 40 true positives FN = 10 missed cases FP = 90 false alarms TN = 860 true negatives Accuracy = (TP + TN) / all (40 + 860) / 1000 = 0.90 Precision = TP / (TP + FP) 40 / 130 = 0.31: of the alarms, how many were real? Recall = TP / (TP + FN) 40 / 50 = 0.80: of the sick, how many did we catch? F1 = 2PR / (P + R) 2 × 0.31 × 0.80 / 1.11 = 0.44 A model that calls everyone healthy scores accuracy 0.95, higher than this one, while catching nobody. 1,000 patients, 50 of them sick
Fig. 1 A confusion matrix for a screening test on 1,000 patients, 50 of whom are sick. The model catches 40 of the 50 but raises 90 false alarms. Its accuracy is 0.90, yet a model that calls everyone healthy would score 0.95.

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:

accuracy=TP+TNTP+TN+FP+FN=40+8601000=0.90\text{accuracy} = \frac{TP + TN}{TP + TN + FP + FN} = \frac{40 + 860}{1000} = 0.90

That sounds good until you notice that calling everyone healthy gives 950/1000=0.95950/1000 = 0.95. 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:

precision=TPTP+FP=40130=0.31\text{precision} = \frac{TP}{TP + FP} = \frac{40}{130} = 0.31

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:

recall=TPTP+FN=4050=0.80\text{recall} = \frac{TP}{TP + FN} = \frac{40}{50} = 0.80

The test catches 80% of sick people and misses 20%.

Specificity, of all real negatives, the fraction correctly cleared: TN/(TN+FP)=860/950=0.905TN/(TN + FP) = 860/950 = 0.905. Its complement, 1−0.905=0.0951 - 0.905 = 0.095, 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=2⋅precision⋅recallprecision+recall=2×0.31×0.800.31+0.80=0.44F_1 = \frac{2 \cdot \text{precision} \cdot \text{recall}}{\text{precision} + \text{recall}} = \frac{2 \times 0.31 \times 0.80}{0.31 + 0.80} = 0.44

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 FβF_\beta score weights recall β\beta times as much as precision (F2F_2 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.

-16 -8 0 8 16 10 20 model score (log-odds of malignant) number of tumours p = 0.5 p = 0.1 benign (negative) malignant (positive) (scores above 16 are counted in the last bar) Everything right of the threshold is flagged as malignant. Moving the line left (p = 0.1) catches more malignant tumours (recall 0.94 → 0.98) at the price of more false alarms (FP 4 → 14).
Fig. 2 Scores from a breast-cancer classifier on 171 test tumours. Benign tumours (blue) mostly get low scores and malignant ones (red) high scores, with some overlap. Moving the threshold from p = 0.5 to p = 0.1 catches more malignant tumours at the cost of more false alarms.

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).

0 0.5 1 0.5 1 false positive rate true positive rate (recall) random guessing ROC curve 0 0.5 1 0.5 1 recall precision random: precision = share of positives (0.37) Precision–recall curve All 30 features: ROC AUC 0.992, average precision 0.989 One feature (mean texture): ROC AUC 0.810, average precision 0.660
Fig. 3 Left, ROC curves: the full model (blue) hugs the top-left corner; a model using one weak feature (orange) is closer to the diagonal of random guessing. Right, precision–recall curves for the same two models. The dashed line is the precision of random guessing, which equals the share of positives.

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 3×3=93 \times 3 = 9 positive–negative pairs, the positive wins in 8 (only 0.4 versus 0.6 is wrong), so AUC =8/9=0.89= 8/9 = 0.89.

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 K×KK \times K 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 y^i−yi\hat{y}_i - y_i. 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, (0.2+0.1+0.4+0.3)/4=0.25(0.2 + 0.1 + 0.4 + 0.3)/4 = 0.25 points. Easy to explain and robust to outliers.
  • Root mean squared error (RMSE): MSE=0.075=0.27\sqrt{\text{MSE}} = \sqrt{0.075} = 0.27. 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 (R2R^2): the fraction of the label's variation the model explains. R2=1−∑(yi−y^i)2∑(yi−yˉ)2=1−0.30/14.75=0.98R^2 = 1 - \frac{\sum (y_i - \hat{y}_i)^2}{\sum (y_i - \bar{y})^2} = 1 - 0.30/14.75 = 0.98. 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 ∣y^−y∣/∣y∣\lvert \hat{y} - y \rvert / \lvert y \rvert. 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

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

  1. 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?
  2. 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.
  3. 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.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. A screening test on 1,000 people (50 sick) flags 130: 40 sick and 90 healthy. What is its precision?

  2. Only 1 in 1,000 card payments is fraud. A model that always says "not fraud" gets 99.9% accuracy. What does this show?

  3. For a cancer screen, you lower the decision threshold from 0.5 to 0.1. What typically happens?

  4. Positives score 0.9, 0.7, 0.4 and negatives score 0.6, 0.3, 0.2. What is the ROC AUC?

  5. Your insurer will price policies directly from the model's predicted probabilities. Which property matters most beyond ranking?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Course

Machine Learning Crash Course

Google · Beginner · Free

Short, practical lessons with interactive visualisations covering regression, classification, embeddings and neural nets.

Interactive

MLU-Explain: ROC & AUC

Amazon Machine Learning University (MLU-Explain) · Beginner · Free

Drag a threshold and watch the confusion matrix and ROC curve change; a clear visual introduction to ROC curves and the area under them.

Interactive

MLU-Explain: Precision & Recall

Amazon Machine Learning University (MLU-Explain) · Beginner · Free

An interactive explainer of precision, recall, the F1 score and the trade-off between them.

Docs

scikit-learn: Metrics and Scoring

scikit-learn · Intermediate · Free

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.

Video

StatQuest

Josh Starmer · Beginner · Free

Short, cheerful, very clear videos on statistics and nearly every ML algorithm.

Paper

An introduction to ROC analysis

Tom Fawcett · 2006 · Intermediate · Paid

The standard tutorial on ROC curves and AUC for machine learning: how to draw them, average them and avoid common mistakes (Pattern Recognition Letters).

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/ml/evaluation-metrics.md