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, and the indicated expectations must exist.
- Markov. If , then . It uses only an expectation and does not require independence.
- Chernoff. For any with finite exponential moment, . Apply Markov to ; optimizing and using independence to factor moments yields distribution-adapted tail bounds.
- Hoeffding. If are independent and , then . For a mean of losses in , the tail is .
- Bernstein. For independent centered variables with and variance sum , . True variance enters the bound and may be unknown.
- McDiarmid. If changes by at most when only coordinate is replaced, and inputs are independent, . 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 is the mean of losses in , changing one observation changes by at most . McDiarmid then gives for one tail. If is the supremum of deviations over a fixed class of bounded losses, changing one observation still changes the supremum by at most . 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 be a classifier fixed before the test or built using independent data. Condition on training; its test losses are then i.i.d. Bernoulli with mean . If is the number of errors and , Hoeffding’s test-set bound gives, with probability at least ,
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 , replace with . Clip the upper bound at 1, since 0-1 risk cannot exceed 1.
The binomial uses more information. For , define as the solution of
The tail decreases with ; inversion gives an exact one-sided Clopper-Pearson upper bound. If , define . “Exact” means coverage is at least without an asymptotic approximation; discreteness can make it conservative. With , , so . For , , the result is approximately , while the one-sided Hoeffding margin is .
Inversion corresponds to a tail test: a candidate risk is incompatible with such a small error count if . For each there is a unique root in because the tail is continuous and decreasing. The case has no such root: observing all errors is compatible with , so the bound is 1. A normal approximation can be unreliable with few errors, especially at , 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 and . With sample variance ,
For Bernoulli, . 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 . 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 , one simple option is to allocate to each and apply the union bound.
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 be continuously uniform on and a fair bit independent of . Define to memorize labels at observed points and predict 0 everywhere else. With probability one there are no ties in , so training error is zero. A new point coincides with the sample with probability zero and its label remains fair: the risk of is 1/2. For sufficiently large , the single-hypothesis Hoeffding margin is less than 1/2, so applying it to that training error fails.
There is no contradiction with Hoeffding: was constructed using the same data whose losses are averaged. Conditioning on does not turn those losses into i.i.d. observations with mean . You can use an independent test, control an entire class or prove another algorithm-specific property such as stability.
The lottery constructs 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 binomials. The single-rule and union bounds are one-sided with . This is a synthetic model: real model errors are often correlated, so their lottery can look different.
Uniform convergence and the union bound
For a finite class chosen independently of , uniform convergence controls the largest discrepancy over all rules at once. Every satisfies Hoeffding’s bound
The union bound adds failure probabilities without requiring independence between rules:
Equating the right side with gives the finite-class uniform bound with probability at least . The proof in the previous lesson then gives ERM . 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 it suffices that . Dependence on the number of candidates is logarithmic rather than linear. For example, with and , 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.
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 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.
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 , 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
Step 1 of 3. What is the two-sided failure bound for one hypothesis?
def binomial_tail_inversion(k, n, delta):
pass