---
title: Evaluating models
heading: Held-out data and k-fold cross-validation, the confusion matrix with precision, recall and F1, the base-rate effect on a positive result, ROC curves and the area under them, and how precisely a test set measures accuracy
eyebrow: S14 · Lesson 20 · Evaluating models
xp: 50
---

::: hook
A fault detector that never raises an alarm is 99% accurate on a line where 1% of boards are faulty, and completely useless. Judging a model needs the right numbers, measured on data it never trained on. This lesson covers the bookkeeping that every practitioner uses: cross-validation to estimate performance honestly, the confusion matrix and its ratios for imbalanced problems, the ROC curve for comparing detectors across all thresholds, and the error bars a finite test set puts on any of them.
:::

::: play
- A detector's score is Gaussian with unit variance, centered at 0 for good boards and at d for faulty ones. A board is flagged when its score exceeds the threshold t.
- The true positive rate (recall) is $Q(t - d)$ and the false positive rate $Q(t)$. Sweeping t trades one for the other; the area under the ROC curve, $\Phi(d/\sqrt{2})$, summarizes the whole trade.
- Watch the precision at a 1% fault rate: even a good detector raises mostly false alarms unless t is high.
:::

```sim plot
view: graph
x: t = -3..6
y: r = 0..1.05
slider: d = 0..5 step 0.1 = 2
slider: p = 0.001..0.5 = 0.01 log
plot: Q(t - d) | samples: 400 | label: true positive rate
plot: Q(t) | samples: 400 | color: ch3 | label: false positive rate
plot: p*Q(t - d)/(p*Q(t - d) + (1 - p)*Q(t)) | samples: 400 | color: ch4 | label: precision
readout: area under the ROC curve = 1 - Q(d/sqrt(2)) | digits: 4
```

::: predict
## A test catches 90% of faulty boards and passes 98% of good ones, and 0.5% of boards are faulty. What's its precision?

- [ ] 98%
- [ ] 90%
- [ ] 50%
- [x] About 18%

::: reveal
Out of 10,000 boards, 50 are faulty and 45 of them fail; 9,950 are good and 2% of them, 199, also fail. Of the 244 alarms, 45 are real: a precision of 18.4%, though the test's recall is 90% and its specificity 98%. Lesson 2's base-rate effect sets the precision of every detector of rare events.
:::
:::

::: nameit
## Held-out data

A model's error on its own training data is optimistic. Estimate performance on data it never saw: a held-out **test set**, or **k-fold cross-validation**, which splits the data into k parts, trains k times on k − 1 of them and tests on the remaining one, and averages. Each fit uses a fraction (k − 1)/k of the data. Model choices (λ, basis size) are made by cross-validation, and the test set is used once at the end.

## The confusion matrix

With true and false positives and negatives (TP, FP, TN, FN):

- **precision** TP/(TP + FP): of the alarms, how many are real;
- **recall** (sensitivity, true positive rate) TP/(TP + FN): of the real cases, how many are caught;
- **specificity** TN/(TN + FP), and the false positive rate 1 − specificity;
- **F1**, the harmonic mean of precision and recall, $2PR/(P + R) = 2\text{TP}/(2\text{TP} + \text{FP} + \text{FN})$.

By Bayes' theorem, precision at prevalence π is $\frac{\text{sens}\cdot\pi}{\text{sens}\cdot\pi + (1 - \text{spec})(1 - \pi)}$.

## ROC curves

Plotting the true positive rate against the false positive rate as the threshold sweeps gives the **ROC curve**. The area under it, **AUC**, is the probability that a random positive scores higher than a random negative: 0.5 for guessing, 1 for perfect. For Gaussian scores of equal variance separated by d standard deviations, AUC = $\Phi(d/\sqrt{2})$.

## Error bars

An accuracy p measured on n independent test examples has standard error $\sqrt{p(1 - p)/n}$: to tell 90% from 91% reliably takes thousands of examples.
:::

::: example
## A detector on 1000 boards gives TP = 40, FP = 10, FN = 20, TN = 930. Find accuracy, precision, recall, F1 and specificity.

::: solution
1. **Accuracy.**
   $$\begin{aligned} \text{accuracy} &= (40 + 930)/1000 \\ &= 0.97 \end{aligned}$$
   against 0.94 for a detector that never fires.
2. **Precision and recall.**
   $$\begin{aligned} \text{precision} &= 40/50 \\ &= 0.80 \\ \text{recall} &= 40/60 \\ &= 0.667 \end{aligned}$$
3. **F1.**
   $$\begin{aligned} F_1 &= \frac{2 \times 0.8 \times 0.667}{1.467} \\ &= 0.727 \end{aligned}$$
4. **Specificity.**
   $$\begin{aligned} \text{specificity} &= 930/940 \\ &= 0.989 \end{aligned}$$

**Answer:** accuracy 0.97, precision 0.80, recall 0.667, F1 0.727 and specificity 0.989.
:::
:::

::: example
## What AUC do score separations of d = 1 and d = 2 give? And what's the standard error of a 90% accuracy measured on 500 examples?

::: solution
1. **AUC.** For d = 1 and d = 2:
   $$\begin{aligned} \text{AUC}_1 &= \Phi(1/\sqrt{2}) \\ &= 0.760 \\ \text{AUC}_2 &= \Phi(2/\sqrt{2}) \\ &= 0.921 \end{aligned}$$
2. **Standard error.**
   $$\begin{aligned} \text{SE} &= \sqrt{0.9 \times 0.1/500} \\ &= 0.0134 \end{aligned}$$
   so the true accuracy is roughly 90 ± 2.7% at two standard errors.

**Answer:** the AUCs are 0.760 for d = 1 and 0.921 for d = 2, and the standard error is 0.0134, so the accuracy is roughly 90 ± 2.7%.
:::
:::

::: example
## Two classifiers are tested on the same 1000 examples. A is wrong and B right on 30; A right and B wrong on 15; the rest they agree on. Is B significantly better?

::: solution
1. **Use the disagreements.** Only the disagreements carry information. If the two were equally good, each of the 45 disagreements would be a coin flip.
2. **McNemar's statistic.**
   $$\begin{aligned} \chi^2 &= \frac{(|30 - 15| - 1)^2}{45} \\ &= 4.36 \end{aligned}$$
3. **Compare the threshold.** That's above the 3.84 that a chi-square variable with one degree of freedom exceeds 5% of the time, so B's advantage of 1.5 points is significant at the 5% level.
4. **Why keep the pairing.** Comparing the two accuracies as if from separate test sets would waste the pairing and could call it noise.

**Answer:** yes: McNemar's statistic is 4.36, above 3.84, so B is significantly better at the 5% level.
:::
:::

::: check
given: T = 30 | 80; F = 3 | 6; N = 25 | 40
answer: T/(T + F)
tolerance: 0.5%

## A classifier has {T} true positives, {F} false positives and {N} false negatives. What's its precision?

::: right
Right. TP/(TP + FP) = {answer}.
:::

::: misses
- [T/(T + N)] That's recall; precision divides by all the alarms.
- [any] Not yet. Of the alarms, the fraction that are real.
:::
:::

::: check
given: T = 30 | 80; F = 3 | 6; N = 25 | 40
answer: 2*T/(2*T + F + N)
tolerance: 0.5%

## With {T} true positives, {F} false positives and {N} false negatives, what's the F1 score?

::: right
Right. $2\text{TP}/(2\text{TP} + \text{FP} + \text{FN})$ = {answer}.
:::

::: misses
- [(T/(T + F) + T/(T + N))/2] That's the arithmetic mean; F1 is the harmonic mean.
- [any] Not yet. Harmonic mean of precision and recall.
:::
:::

::: check
given: s = 0.9 | 0.99; f = 0.9 | 0.95 | 0.99; p = 0.001 | 0.01 | 0.1
answer: s*p/(s*p + (1 - f)*(1 - p))
tolerance: 0.5%

## A test has sensitivity {s} and specificity {f}, and the condition has prevalence {p}. What fraction of positive results are true?

::: right
Right. $\frac{s\pi}{s\pi + (1 - \text{spec})(1 - \pi)}$ = {answer}.
:::

::: misses
- [any] Not yet. Count true and false positives in a population.
:::
:::

::: check
given: d = 0.5 | 1.5 | 3
answer: 1 - Q(d/sqrt(2))
tolerance: 0.5%

## Positive and negative scores are Gaussian with equal variance and means {d} standard deviations apart. What's the AUC?

::: right
Right. $\Phi(d/\sqrt{2})$ = {answer}.
:::

::: misses
- [1 - Q(d)] The difference of two scores has variance 2, so divide d by √2.
- [any] Not yet. The probability that a positive outscores a negative.
:::
:::

::: check
given: p = 0.8 | 0.9 | 0.97; n = 100 | 500 | 2000
answer: sqrt(p*(1 - p)/n)
tolerance: 0.5%

## A classifier scores {p} accuracy on {n} independent test examples. What's the standard error of that estimate?

::: right
Right. $\sqrt{p(1 - p)/n}$ = {answer}.
:::

::: misses
- [p*(1 - p)/n] That's the variance; take the square root.
- [any] Not yet. Binomial standard error.
:::
:::

::: check
given: N = 120 | 1000 | 5000; k = 5 | 10
answer: N*(k - 1)/k
tolerance: 0.5%

## {k}-fold cross-validation runs on {N} examples. How many examples does each fit train on?

::: right
Right. $N(k - 1)/k$ = {answer}.
:::

::: misses
- [N/k] That's the size of each held-out fold.
- [any] Not yet. Everything except one fold.
:::
:::

::: check
kind: parts
given: p = 0.8 | 0.95 | 0.99; s = 0.5 | 1 | 2

## A classifier's accuracy is about {p}, and the test set must measure it with a standard error of {s} percentage points.

::: part
answer: p*(1 - p)/(s/100)^2
unit: examples
tolerance: 1%

### How many independent test examples does that take?

::: misses
- [p*(1 - p)/(s/100)] The standard error is a square root; square it.
- [any] $N = p(1 - p)/\text{SE}^2$.
:::
:::

::: part
answer: 1.96*s
unit: %
tolerance: 0.5%

### How wide is the 95% confidence interval's half-width then, in percentage points?

::: misses
- [any] 1.96 standard errors.
:::
:::
:::

::: check
kind: derivation
vars: T = 1..500, F = 1..500, N = 1..500, M = 100..5000

## A confusion matrix has T true positives, F false positives, N false negatives and M true negatives.

::: step
answer: (T + M)/(T + F + N + M)

### What is the accuracy?
:::

::: step
answer: M/(M + F)

### What is the specificity?
:::

::: step
answer: (T/(T + N) + M/(M + F))/2

### What is the balanced accuracy (the mean of recall and specificity)?
:::

::: right
Right. Balanced accuracy isn't fooled by a rare positive class the way plain accuracy is.
:::
:::

::: explain
## Why can accuracy be a misleading measure for a fault detector, and what should be reported instead?

::: model
When faults are rare, a detector that labels everything as good achieves an accuracy equal to the fraction of good units, which can be 99% or higher while catching nothing. Accuracy is dominated by the large negative class, so it barely changes when the detector misses real faults. Precision and recall measure what matters on the rare class: how many alarms are real and how many faults are caught. An ROC curve or its area shows the whole trade-off between detection and false alarms across thresholds, independently of the base rate, and the chosen operating point should then be judged by the precision it gives at the real prevalence.
:::
:::

::: practice

::: check
given: T = 10 | 200; F = 1 | 50; N = 2 | 60
answer: T/(T + N)
tolerance: 0.5%

## Recall: TP = {T}, FP = {F}, FN = {N}?

::: misses
- [any] TP/(TP + FN).
:::
:::

::: check
given: s = 0.8 | 0.999; f = 0.8 | 0.999; p = 0.0005 | 0.3
answer: s*p/(s*p + (1 - f)*(1 - p))
tolerance: 0.5%

## Precision: sensitivity {s}, specificity {f}, prevalence {p}?

::: misses
- [any] Bayes' theorem.
:::
:::

::: check
given: d = 0.2 | 0.5 | 1 | 1.5 | 2 | 4
answer: 1 - Q(d/sqrt(2))
tolerance: 0.5%

## AUC for separation {d}?

::: misses
- [any] $\Phi(d/\sqrt{2})$.
:::
:::
:::
