---
title: Generalization bounds
heading: How far a measured error rate can sit from the true one, Hoeffding's inequality and the test examples a guarantee takes, zero-failure bounds, the price of choosing among many models, and sample complexity with the VC dimension
eyebrow: S14 · Lesson 5 · Generalization bounds
xp: 50
---

::: hook
A classifier makes no mistakes on 300 test examples. Is its error rate zero? Certainly not, but how large could it be? And if you tried a hundred hyperparameter settings and kept the one that scored best on the validation set, how much should you trust that best score? Learning theory answers both with bounds that hold whatever the data's distribution, and turns them into the number of examples a guarantee requires.
:::

::: play
- The curves show how far, at worst, a measured error rate can sit from the true one, against the number of test examples N, holding with probability 1 − δ.
- The solid curve is for one fixed model; the dashed one for the best of M models picked on the same data.
- The gap shrinks as $1/\sqrt N$. Choosing among many models costs only $\ln M$ inside the square root, so even a million candidates need only a few times more data.
:::

```sim plot
view: graph
x: N = 10..100000 log
y: e = 0..0.5
slider: M = 1..1000000 = 100 log
slider: d = 0.01..0.2 = 0.05
plot: sqrt(ln(2/d)/(2*N)) | label: one model
plot: sqrt(ln(2*M/d)/(2*N)) | dashed | label: best of M models
```

::: predict
## A classifier makes no errors on 300 independent test examples. With 95% confidence, its true error rate is below about

- [ ] 0, since it made no errors
- [ ] 0.1%
- [x] 1%
- [ ] 5%

::: reveal
If the error rate were p, the chance of 300 clean results would be $(1 - p)^{300}$. That falls to 5% at p = $1 - 0.05^{1/300}$ = 0.99%, so 1% is the 95% bound. This is the "rule of three": zero failures in N trials bounds the rate at about 3/N.
:::
:::

::: nameit
## Measured against true error

A model's true error rate μ is the probability it errs on a new example; on N independent test examples it errs a fraction ν of the time. **Hoeffding's inequality** bounds how far apart they can be, for any distribution:
$$P(|\nu - \mu| > \epsilon) \le 2e^{-2N\epsilon^2}$$
Setting the right side to δ, with probability at least 1 − δ,
$$|\nu - \mu| \le \sqrt{\frac{\ln(2/\delta)}{2N}}, \qquad N \ge \frac{\ln(2/\delta)}{2\epsilon^2}$$
The bound is distribution-free and so conservative; when the error rate is known to be small, the binomial distribution or its normal approximation gives tighter intervals (lesson 20).

## Zero failures

With no errors in N trials, the one-sided bound at confidence 1 − δ is $p < 1 - \delta^{1/N} \approx \ln(1/\delta)/N$, which is 3/N at 95%.

## Choosing among models

If M models are scored on the same data and the best kept, the bound must hold for all of them at once. The **union bound** splits δ among them:
$$|\nu - \mu| \le \sqrt{\frac{\ln(2M/\delta)}{2N}}$$
Tuning many hyperparameters on one validation set therefore makes its best score optimistic, and a separate test set, used once, is needed for an honest number.

## Sample complexity

A finite class of M hypotheses that contains a perfect one: any hypothesis consistent with
$$N \ge \frac{\ln M + \ln(1/\delta)}{\epsilon}$$
training examples has error below ε with probability 1 − δ. Infinite classes are measured by their **VC dimension** $d_{VC}$, the largest number of points they can label in every possible way: $d + 1$ for linear classifiers in d dimensions. The VC bound replaces $\ln M$ by about $d_{VC}\ln N$; in practice, about ten examples per unit of VC dimension is a common rule of thumb.
:::

::: example
## How many test examples does it take to measure an error rate to within ±1 percentage point with 95% confidence? Compare Hoeffding's answer with the normal approximation for a classifier whose error is near 5%.

::: solution
1. **Hoeffding's bound.**
   $$\begin{aligned} N &\ge \frac{\ln(2/0.05)}{2 \times 0.01^2} \\ &= 18{,}445 \end{aligned}$$
2. **Normal approximation.** It uses the actual variance:
   $$\begin{aligned} N &= \frac{1.96^2 \times 0.05 \times 0.95}{0.01^2} \\ &= 1825 \end{aligned}$$
   ten times fewer.
3. **Why they differ.** Hoeffding assumes the worst case, a variance of 1/4 at an error rate of 50%; when the error rate is known to be small, the binomial calculation is the one to use.

**Answer:** Hoeffding asks for 18,445 examples, and the normal approximation for 1825, ten times fewer.
:::
:::

::: example
## A team tries 100 hyperparameter settings and keeps the one that scores best on a 2000-example validation set. How optimistic might that score be, at 95% confidence, compared with scoring a single model?

::: solution
1. **One model.**
   $$\sqrt{\ln 40/4000} = 0.030$$
2. **Best of 100.**
   $$\sqrt{\ln 4000/4000} = 0.046$$
3. **What selection does.** It widens the possible gap by half, and the selected model's score is biased low, because it partly won by luck.
4. **The cure.** The cure is a test set held back from all the tuning.

**Answer:** the best of 100 settings may look better than it is by up to 0.046, against 0.030 for a single model.
:::
:::

::: example
## A lookup table can represent any Boolean function of 10 binary inputs. How many training examples guarantee error below 5% with 95% confidence for a table consistent with them? Compare a linear threshold unit on the same inputs.

::: solution
1. **Count the functions.** There are $2^{1024}$ such functions, so
   $$\ln M = 1024\ln 2 \approx 710$$
2. **Examples needed.** With δ = 0.05, $\ln(1/\delta) = \ln 20 = 3.0$, and
   $$\begin{aligned} N &\ge \frac{\ln M + \ln 20}{0.05} \\ &= 14{,}256 \end{aligned}$$
   more examples than the table has entries (1024).
3. **What the bound says.** It says, rightly, that a table learns nothing about inputs it hasn't seen.
4. **Threshold unit.** It has VC dimension 11, and about ten examples per unit, a hundred or so, is typically enough.
5. **Why the class matters.** Restricting the hypothesis class is what makes generalization possible.

**Answer:** the table needs 14,256 examples, more than its 1024 entries; a threshold unit, with VC dimension 11, typically needs a hundred or so.
:::
:::

::: check
kind: parts
given: e = 0.005 | 0.01 | 0.02 | 0.05; d = 0.01 | 0.05

## An error rate must be measured to within ±{e} with probability {d} of failure, using Hoeffding's inequality.

::: part
answer: ln(2/d)/(2*e^2)
unit: examples
tolerance: 1%

### How many test examples does it need?

::: misses
- [ln(1/d)/(2*e^2)] The two-sided bound has 2/δ.
- [ln(2/d)/e^2] The exponent is $2N\epsilon^2$.
- [any] $N = \ln(2/\delta)/(2\epsilon^2)$.
:::
:::
:::

::: check
kind: parts
given: N = 100 | 1000 | 10000; d = 0.01 | 0.05; M = 10 | 1000 | 1000000

## A model is scored on {N} examples, and the bound must hold with failure probability {d}.

::: part
answer: sqrt(ln(2/d)/(2*N))
tolerance: 0.5%

### How far can its measured error sit from the true error?

::: misses
- [any] $\sqrt{\ln(2/\delta)/(2N)}$.
:::
:::

::: part
answer: sqrt(ln(2*M/d)/(2*N))
tolerance: 0.5%

### And for the best of {M} models scored on the same examples?

::: misses
- [sqrt(M*ln(2/d)/(2*N))] The union bound puts M inside the logarithm.
- [any] Replace δ by δ/M.
:::
:::
:::

::: check
kind: parts
given: N = 50 | 300 | 3000; c = 0.9 | 0.95 | 0.99

## A system passes {N} independent trials with no failures.

::: part
answer: (1 - (1 - c)^(1/N))*100
unit: %
tolerance: 0.5%

### What upper bound on its failure rate holds with confidence {c}?

::: misses
- [100/N] That's one failure per N; the bound depends on the confidence.
- [any] $1 - (1 - c)^{1/N}$.
:::
:::
:::

::: check
kind: parts
given: p = 0.01 | 0.05 | 0.2; e = 0.005 | 0.02

## A classifier's error rate is about {p}, and it must be measured to within ±{e} at 95% confidence.

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

### How many test examples does the normal approximation call for?

::: misses
- [1.96*p*(1 - p)/e^2] The 1.96 is squared.
- [any] $N = 1.96^2p(1 - p)/\epsilon^2$.
:::
:::

::: part
answer: ln(2/0.05)/(2*e^2)/(1.96^2*p*(1 - p)/e^2)
tolerance: 1%

### How many times more does Hoeffding's bound ask for?

::: misses
- [any] Divide the two counts.
:::
:::
:::

::: check
kind: parts
given: B = 8 | 16 | 20; e = 0.01 | 0.1; d = 0.01 | 0.05

## A learner picks any Boolean function of {B} binary inputs that fits its training data.

::: part
answer: (2^B*ln(2) + ln(1/d))/e
unit: examples
tolerance: 1%

### How many training examples guarantee error below {e} with failure probability {d}?

::: misses
- [(B*ln(2) + ln(1/d))/e] There are $2^{2^B}$ functions, so $\ln M = 2^B\ln 2$.
- [any] $(\ln M + \ln(1/\delta))/\epsilon$.
:::
:::
:::

::: check
kind: parts
given: D = 2 | 10 | 100 | 784

## A linear classifier with a bias works on {D}-dimensional inputs.

::: part
answer: D + 1
tolerance: 0

### What is its VC dimension?

::: misses
- [D] The bias adds one.
- [any] d + 1 for a hyperplane in d dimensions.
:::
:::

::: part
answer: 10*(D + 1)
unit: examples
tolerance: 0

### About how many training examples does the ten-per-dimension rule of thumb suggest?

::: misses
- [any] Ten times the VC dimension.
:::
:::
:::

::: check
kind: choice

## Why is a model's score on the validation set used to tune it an optimistic estimate of its error?

- [ ] The validation set is always smaller than the training set
- [x] Among many settings, the one that scores best was partly favored by the particular validation examples, so its score is biased low; only data not used in any choice gives an unbiased estimate
- [ ] Validation examples are easier than test examples
- [ ] Hoeffding's inequality doesn't apply to validation sets

::: misses
- [1] Size isn't the issue; selection is.
- [3] They come from the same distribution.
- [4] It applies to each model; the trouble is choosing the best of many.
:::
:::

::: check
kind: derivation
vars: N = 10..100000, d = 0.001..0.2, M = 1..1000000

## A model's error is measured on N examples, and the bound must fail with probability at most δ.

::: step
answer: sqrt(ln(2/d)/(2*N))

### How wide is Hoeffding's bound for one model?
:::

::: step
answer: sqrt(ln(2*M/d)/(2*N))

### And for the best of M models?
:::

::: step
answer: ln(2*M/d)/ln(2/d)

### By what factor must N grow to keep the bound the same width when choosing among M models?
:::

::: right
Right. The cost of choosing grows only with ln M.
:::
:::

::: check
kind: python

## Write `hoeffding_n(eps, delta)` (the examples needed, rounded up), `zero_failure_bound(n, conf)` and `best_of_m(n, m, delta)` (the bound's width for the best of m models).

```python starter
def hoeffding_n(eps, delta):
    return 0

def zero_failure_bound(n, conf):
    return 0.0

def best_of_m(n, m, delta):
    return 0.0
```

```python solution
import math

def hoeffding_n(eps, delta):
    return math.ceil(math.log(2 / delta) / (2 * eps ** 2))

def zero_failure_bound(n, conf):
    return 1 - (1 - conf) ** (1 / n)

def best_of_m(n, m, delta):
    return math.sqrt(math.log(2 * m / delta) / (2 * n))
```

```python tests
assert hoeffding_n(0.01, 0.05) == 18445, "±1% at 95%: 18,445 examples."
assert abs(zero_failure_bound(300, 0.95) - 0.009936) < 1e-6, "300 clean trials: below 0.99%."
assert abs(best_of_m(2000, 100, 0.05) - 0.04554) < 1e-5, "Best of 100 on 2000: 0.046."
assert abs(best_of_m(2000, 1, 0.05) - 0.03037) < 1e-5, "One model on 2000: 0.030."
```

::: right
Right. Three lines settle most questions about how much test data a claim needs.
:::
:::

::: explain
## Why does choosing the best of many models on one data set weaken the guarantee its score carries?

::: model
For any one model fixed in advance, its measured error on fresh data is an unbiased estimate, and Hoeffding's inequality bounds how far chance can push it. When many models are scored on the same data, each has its own random error, and picking the lowest score preferentially picks a model whose error happened to be measured low. The guarantee then has to cover every candidate at once, which the union bound does by sharing the failure probability among them; that widens the bound by a factor growing with the logarithm of the number of candidates. Only data that played no part in any choice gives an unbiased final number.
:::
:::

::: practice
::: check
given: e = 0.01 | 0.03; d = 0.05 | 0.01
answer: ln(2/d)/(2*e^2)
unit: examples
tolerance: 1%

## Hoeffding test size: ±{e}, δ = {d}?

::: misses
- [any] $\ln(2/\delta)/(2\epsilon^2)$.
:::
:::

::: check
given: N = 100 | 1000; c = 0.95 | 0.99
answer: (1 - (1 - c)^(1/N))*100
unit: %
tolerance: 0.5%

## Zero failures in {N}: bound at confidence {c}?

::: misses
- [any] $1 - (1 - c)^{1/N}$.
:::
:::

::: check
given: N = 500 | 5000; M = 10 | 10000
answer: sqrt(ln(2*M/0.05)/(2*N))
tolerance: 0.5%

## Best of {M} models on {N} examples, δ = 0.05?

::: misses
- [any] $\sqrt{\ln(2M/\delta)/(2N)}$.
:::
:::
:::
