Module contents
Lesson 4 of 20Review 60 min

Concentration review: the test set bound and uniform convergence

Review Hoeffding, Bernstein and McDiarmid and derive useful test-set and finite-class uniform bounds. A counterexample shows why the same inequality fails when applied to training error.

After this lesson you can

  • Obtain a classifier risk upper bound from a test set using Hoeffding and exact binomial-tail inversion.
  • Explain with a counterexample why Hoeffding does not apply to empirical risk of a sample-selected hypothesis.
  • Prove finite-class uniform convergence: sup_h |R(h) - R̂(h)| ≤ √(log(2|H|/δ)/(2n)) with probability 1 - δ.
  • Quantitatively compare Hoeffding, empirical Bernstein and the binomial tail when error is small.
  • Calculate the test sample size needed to certify an error at a given precision.

Before you start

A test score fluctuates too

A classifier makes zero errors on 300 examples. Its true error need not be zero: another test set could contain difficult examples. The question is which risks are compatible with the observation and with what probability the guarantee fails. To answer it, fix the rule before seeing the test, or simultaneously control all rules from which a selection will be made.

Five concentration tools

The following are one-sided bounds. Throughout, t>0t>0 and the indicated expectations must exist.

  1. Markov. If Z≥0Z\ge0, then P(Z≥t)≤EZ/t\Pr(Z\ge t)\le\E Z/t. It uses only an expectation and does not require independence.
  2. Chernoff. For any s>0s>0 with finite exponential moment, P(Z≥t)≤e−stEesZ\Pr(Z\ge t)\le e^{-st}\E e^{sZ}. Apply Markov to esZe^{sZ}; optimizing ss and using independence to factor moments yields distribution-adapted tail bounds.
  3. Hoeffding. If ZiZ_i are independent and Zi∈[ai,bi]Z_i\in[a_i,b_i], then P(∑i(Zi−EZi)≥t)≤exp⁡[−2t2/∑i(bi−ai)2]\Pr(\sum_i(Z_i-\E Z_i)\ge t)\le\exp[-2t^2/\sum_i(b_i-a_i)^2]. For a mean of losses in [0,1][0,1], the tail is e−2nϵ2e^{-2n\epsilon^2}.
  4. Bernstein. For independent centered variables with ∣Zi∣≤1|Z_i|\le1 and variance sum vv, P(∑iZi≥t)≤exp⁡[−t2/(2(v+t/3))]\Pr(\sum_i Z_i\ge t)\le\exp[-t^2/(2(v+t/3))]. True variance enters the bound and may be unknown.
  5. McDiarmid. If F(Z1,…,Zn)F(Z_1,\ldots,Z_n) changes by at most cic_i when only coordinate ii is replaced, and inputs are independent, P(F−EF≥t)≤exp⁡[−2t2/∑ici2]\Pr(F-\E F\ge t)\le\exp[-2t^2/\sum_i c_i^2]. This applies to nonlinear functions of a sample. A two-sided tail is obtained by adding the two tails.

A bound is not an exact description of a distribution. Its assumptions matter: duplicates, temporal dependence or a test selected for its content can invalidate the i.i.d. model. Some bounds are valid but vacuous when they exceed 1.

The choice depends on available information. Markov may help when only the mean of a nonnegative quantity is known, but is usually looser. Chernoff is a procedure: it uses an exponential function and permits parameter optimization when the moment exists. Hoeffding uses the range without variance. Bernstein incorporates true variance and can improve when it is small. McDiarmid controls a general function but needs a uniform bound on each coordinate’s effect; bounding the average change is insufficient.

For example, if FF is the mean of nn losses in [0,1][0,1], changing one observation changes FF by at most 1/n1/n. McDiarmid then gives e−2nϵ2e^{-2n\epsilon^2} for one tail. If FF is the supremum of deviations over a fixed class of bounded losses, changing one observation still changes the supremum by at most 1/n1/n. This concentrates the supremum around its expectation; a numerical bound still requires controlling that expectation. Concentration alone does not show that it is small.

Certifying a fixed rule

Let hh be a classifier fixed before the test or built using independent data. Condition on training; its nn test losses are then i.i.d. Bernoulli with mean R(h)R(h). If kk is the number of errors and r^=k/n\hat r=k/n, Hoeffding’s test-set bound gives, with probability at least 1−δ1-\delta,

R(h)≤r^+log⁡(1/δ)2n.R(h)\le\hat r+\sqrt{\frac{\log(1/\delta)}{2n}}.

The probability refers to the procedure for generating the test before observing it, not to the fixed risk being random afterwards. The margin above is one-sided. To control both directions at joint level 1−δ1-\delta, replace log⁡(1/δ)\log(1/\delta) with log⁡(2/δ)\log(2/\delta). Clip the upper bound at 1, since 0-1 risk cannot exceed 1.

The binomial uses more information. For k<nk<n, define uu as the solution of

PK∼Bin(n,u)(K≤k)=δ.\Pr_{K\sim\mathrm{Bin}(n,u)}(K\le k)=\delta.

The tail decreases with uu; inversion gives an exact one-sided Clopper-Pearson upper bound. If k=nk=n, define u=1u=1. “Exact” means coverage is at least 1−δ1-\delta without an asymptotic approximation; discreteness can make it conservative. With k=0k=0, (1−u)n=δ(1-u)^n=\delta, so u=1−δ1/nu=1-\delta^{1/n}. For n=300n=300, δ=0.05\delta=0.05, the result is approximately 0.009940.00994, while the one-sided Hoeffding margin is 0.07070.0707.

Inversion corresponds to a tail test: a candidate risk pp is incompatible with such a small error count if Pp(K≤k)<δ\Pr_p(K\le k)<\delta. For each k<nk<n there is a unique root in (0,1)(0,1) because the tail is continuous and decreasing. The k=nk=n case has no such root: observing all errors is compatible with p=1p=1, so the bound is 1. A normal approximation can be unreliable with few errors, especially at k=0k=0, where a naive interval based only on observed variance would have zero width.

These formulas certify risk with respect to the distribution from which the test is drawn. If deployment changes, a narrow bound for the old distribution does not certify the new environment. Nor does it automatically control small groups: for each group define its population, relevant observation count and correction for comparisons. Choosing the worst group after inspecting many groups introduces another selection.

Theorem 4 of Maurer and Pontil gives another bound, valid for i.i.d. losses in [0,1][0,1] and n≥2n\ge2. With sample variance s2=1n−1∑i(Zi−Zˉ)2s^2=\frac1{n-1}\sum_i(Z_i-\bar Z)^2,

R(h)≤r^+2s2log⁡(2/δ)n+7log⁡(2/δ)3(n−1).R(h)\le\hat r+\sqrt{\frac{2s^2\log(2/\delta)}{n}}+\frac{7\log(2/\delta)}{3(n-1)}.

For Bernoulli, s2=nn−1r^(1−r^)s^2=\frac{n}{n-1}\hat r(1-\hat r). This is the empirical form: it does not replace the population variance in Bernstein with the observed variance without justification. With zero errors the square-root term vanishes, but not the term of order 1/n1/n. Each bound in the figure is calculated at the same nominal level; choosing the smallest of several bounds afterwards does not automatically preserve that level without correcting for selection.

The extra empirical Bernstein term protects against a sample that happens to look low-variance by chance. For a particular count, compare the three widths, but no visual comparison makes one bound superior for all losses and levels. The binomial exploits the fact that each loss takes only 0 or 1; the Bernstein version shown also applies to continuous bounded losses. To use two procedures simultaneously with total failure probability at most δ\delta, one simple option is to allocate δ/2\delta/2 to each and apply the union bound.

InteractiveTest bound calculator
Hoeffding: 0.0707
Empirical Bernstein: 0.0288
Exact binomial: 0.0099
  • Hoeffding
  • Empirical Bernstein
  • Exact binomial
300
0
0.05
Observed error0.0000
Hoeffding0.0707
Empirical Bernstein0.0288
Exact binomial0.0099
Change n, errors and δ. All three are one-sided upper bounds for a fixed rule independent of the test; the binomial uses the specific form of 0-1 loss.
[ ]Bounds, binomial inversion and coverageBrowser
import numpy as np
from scipy.stats import binom, beta

def hoeffding_upper(k, n, delta):
    return min(1., k/n + np.sqrt(np.log(1/delta)/(2*n)))
def empirical_bernstein_upper(k, n, delta):
    p = k/n
    v = n/(n-1)*p*(1-p)
    return min(1., p + np.sqrt(2*v*np.log(2/delta)/n) + 7*np.log(2/delta)/(3*(n-1)))
def binomial_upper(k, n, delta):
    if k == n: return 1.
    lo, hi = 0., 1.
    for _ in range(50):
        mid = (lo+hi)/2
        if binom.cdf(k, n, mid) > delta: lo = mid
        else: hi = mid
    return (lo+hi)/2

n, delta = 100, .05
grid = np.arange(n+1)
upper = np.array([binomial_upper(k,n,delta) for k in grid])
ref = np.r_[beta.ppf(1-delta, grid[:-1]+1, n-grid[:-1]), 1.]
print('diferencia máxima con beta:', np.max(np.abs(upper-ref)))
rng = np.random.default_rng(1304)
for p in [.01,.1,.5]:
    counts = rng.binomial(n,p,20000)
    H = np.array([hoeffding_upper(k,n,delta) for k in grid])
    E = np.array([empirical_bernstein_upper(k,n,delta) for k in grid])
    print('p',p,'cobertura H / Bernstein / binomial:',
          *(round(np.mean(arr[counts] >= p),4) for arr in (H,E,upper)))
print('n=300, cero errores:', binomial_upper(0,300,delta), hoeffding_upper(0,300,delta))

The simulation checks specific configurations and has Monte Carlo error. It does not prove coverage for every distribution; the guarantee comes from the inequality or inversion. Binary loss and test size are fixed before simulation.

Why the same bound does not apply to training

Let XX be continuously uniform on [0,1][0,1] and YY a fair bit independent of XX. Define hSh_S to memorize labels at observed points and predict 0 everywhere else. With probability one there are no ties in XX, so training error is zero. A new point coincides with the sample with probability zero and its label remains fair: the risk of hSh_S is 1/2. For sufficiently large nn, the single-hypothesis Hoeffding margin is less than 1/2, so applying it to that training error fails.

There is no contradiction with Hoeffding: hSh_S was constructed using the same data whose losses are averaged. Conditioning on hSh_S does not turn those losses into i.i.d. observations with mean R(hS)R(h_S). You can use an independent test, control an entire class or prove another algorithm-specific property such as stability.

The lottery constructs kk classifiers with independent Bernoulli losses of probability 1/2 for each example. All have true risk 1/2; the figure shows 600 minimum errors generated with seed 1304 using the exact distribution of the minimum of kk binomials. The single-rule and union bounds are one-sided with δ=0.05\delta=0.05. This is a synthetic model: real model errors are often correlated, so their lottery can look different.

InteractiveThe classifier lottery
  • frequency of the best
  • threshold for one
  • union threshold
100
100
True risk0.500
Mean best observed error0.375
One-sided margin for one0.122
One-sided union margin0.195
Increase the number of candidates and observe how the best error moves. The single-rule line does not correct for selection; the union covers the fixed family simultaneously.

Uniform convergence and the union bound

For a finite class H\mathcal H chosen independently of SS, uniform convergence controls the largest discrepancy over all rules at once. Every hh satisfies Hoeffding’s bound

P{∣R(h)−R^S(h)∣>ϵ}≤2e−2nϵ2.\Pr\{|R(h)-\widehat R_S(h)|>\epsilon\}\le2e^{-2n\epsilon^2}.

The union bound adds failure probabilities without requiring independence between rules:

P{sup⁡h∈H∣R(h)−R^S(h)∣>ϵ}≤2∣H∣e−2nϵ2.\Pr\left\{\sup_{h\in\mathcal H}|R(h)-\widehat R_S(h)|>\epsilon\right\} \le 2|\mathcal H|e^{-2n\epsilon^2}.

Equating the right side with δ\delta gives the finite-class uniform bound sup⁡h∣R(h)−R^S(h)∣≤log⁡(2∣H∣/δ)/(2n)\sup_h|R(h)-\widehat R_S(h)|\le\sqrt{\log(2|\mathcal H|/\delta)/(2n)} with probability at least 1−δ1-\delta. The proof in the previous lesson then gives ERM R(h^)≤min⁡hR(h)+2ϵR(\hat h)\le\min_hR(h)+2\epsilon. If the minimum is not attained, use infima and approximations. The bound controls every family member on the same event, so it also applies to the rule selected after comparing errors.

For two-sided accuracy ϵ\epsilon it suffices that n≥log⁡(2∣H∣/δ)/(2ϵ2)n\ge\log(2|\mathcal H|/\delta)/(2\epsilon^2). Dependence on the number of candidates is logarithmic rather than linear. For example, with ϵ=0.05\epsilon=0.05 and δ=0.05\delta=0.05, increasing candidates from 10 to 10000 multiplies sufficient sample size by a little over two, not by a thousand. This is a sufficient condition, not a universal minimum.

InteractiveThe logarithmic cost of the union bound
0.05
100
0.05
Candidates100
sufficient n1659
n with one candidate738
The curve uses the two-sided bound for a family fixed before the test. Change ε, δ and candidate count to compare sufficient sample sizes.

The entire family must be fixed before seeing the test. You may choose adaptively among its members and the simultaneous guarantee still covers them, even when their errors are correlated. If test information guides creation of new models outside a fixed family, counting only the kk ultimately reported configurations is insufficient. An independent final test or an analysis covering the whole search avoids attributing a fixed-rule bound to adaptive selection.

A practical split can reserve training for fitting parameters, validation for choosing models and a final test for evaluating that choice. If the final test is reused to change the model, it is no longer final. A union bound can control a predefined list of experiments, but does not remove differences between the validation distribution and population of interest. For time series, the split must also respect when information became available.

[ ]Selecting among many classifiersBrowser
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(1305)
n, B, delta = 100, 4000, .05
for k in [1, 10, 100, 1000]:
    # Las pérdidas de cada regla son independientes Bernoulli(1/2).
    errors = rng.binomial(n, .5, size=(B,k)) / n
    best = errors.min(axis=1)
    one = np.sqrt(np.log(1/delta)/(2*n))
    union = np.sqrt(np.log(k/delta)/(2*n))
    print('k', k, 'mínimo medio', round(best.mean(),4),
          'fallo una regla', round(np.mean(.5-best > one),4),
          'fallo unión', round(np.mean(.5-best > union),4))
    plt.hist(best, bins=20, density=True, histtype='step', label=f'k={k}')
plt.axvline(.5, color='black', linestyle='--', label='riesgo real')
plt.xlabel('menor error observado'); plt.ylabel('densidad'); plt.legend(); plt.show()

The union margin depends on log⁡(k/δ)/n\sqrt{\log(k/\delta)/n}, but that upper bound does not establish equality for every family. The simulation uses independent predictions across rules to isolate the mechanism. If two rules are identical, repeating them does not create a new selection source even though the union bound counts both.

Exercises

Numeric
Calculate the one-sided Hoeffding margin with n=1000 and δ=0.05.
Numeric
What is the smallest integer n for zero errors to certify risk ≤ 0.01 using the one-sided binomial bound and δ=0.05?
Proof
Prove: Prove the uniform bound and its consequence for ERM.
0
The finite class is fixed before an i.i.d. sample and loss lies in [0,1].

Step 1 of 3. What is the two-sided failure bound for one hypothesis?

Quiz
Selection uses the test set. When is the union bound over k models valid?
CodeInvert the binomial tail
Implement binomial_tail_inversion(k, n, delta), with 0 ≤ k ≤ n and 0 < delta < 1. Return the one-sided upper bound by bisection of P(Bin(n,p) ≤ k)=delta. For k=n return 1.
def binomial_tail_inversion(k, n, delta):
  pass
Shift+Enter to run

Summary

Key idea
A rule independent of the test permits a single-hypothesis bound; selection among a fixed family requires a uniform event. Hoeffding, empirical Bernstein and binomial inversion have different assumptions and constants.