Module contents
Lesson 10 of 20Core 100 min

Structural risk minimization and model selection with guarantees

Study structural risk minimization and Occam bounds, formalize nonuniform learnability and validation guarantees, and examine adaptive overfitting from repeated test-set use.

After this lesson you can

  • Formulate SRM with a hierarchy and weights w_k and prove the oracle inequality.
  • Distinguish uniform and nonuniform learnability and characterize the latter as a countable union of finite-VC classes.
  • Derive the Occam bound from a prefix code for hypotheses.
  • Turn selection among k validation candidates into a guarantee with a log k term.
  • Explain adaptive overfitting, measure it by simulation and implement a simple reusable holdout.

Before you start

Choosing a class also consumes information

A high-degree polynomial can fit training data better than a low-degree one. Choosing degree by that same error favors large classes, even if each fixed class has its own guarantee. Structural risk minimization (SRM) adds a penalty paying for class complexity and the search among classes.

Let H1,H2,…\mathcal H_1,\mathcal H_2,\ldots be a countable family and choose weights wk>0w_k>0 with ∑kwk≤1\sum_k w_k\le1 before seeing data. If each class has a uniform two-sided bound ∣R(h)−R^(h)∣≤bk(δwk)|R(h)-\widehat R(h)|\le b_k(\delta w_k) with failure at most δwk\delta w_k, the weighted union gives a common event with probability at least 1−δ1-\delta. On it choose

h^∈arg⁡min⁡kinf⁡h∈Hk{R^(h)+bk(δwk)}.\widehat h\in\arg\min_k\inf_{h\in\mathcal H_k}\{\widehat R(h)+b_k(\delta w_k)\}.

Assume minima are attained; otherwise use approximations with an arbitrarily small extra term. For any class and h∈Hkh\in\mathcal H_k, on the same event,

R(h^)≤R^(h^)+bk^≤R^(h)+bk≤R(h)+2bk.R(\widehat h)\le\widehat R(\widehat h)+b_{\widehat k} \le\widehat R(h)+b_k\le R(h)+2b_k.

Taking the infimum yields the oracle inequality

R(h^)≤inf⁡k{inf⁡h∈HkR(h)+2bk(δwk)}.R(\widehat h)\le\inf_k\left\{\inf_{h\in\mathcal H_k}R(h)+2b_k(\delta w_k)\right\}.

The oracle knows the best class for the distribution, while SRM competes with it by paying the penalty. A nested hierarchy helps interpret increasing capacity, but the weighted union does not require nested classes. Weights allocate failure probability; they are not posterior probabilities learned from the same set without correction.

InteractiveSRM in bars
0.00.51.0012345★6

Blue: empirical error. Orange: penalty. The star marks the minimum; the test set is separate and does not participate in selection.

Sample size n
Weights
Selected degree5
Training error0.260
Test error0.312
SRM score0.529
Each bar stacks training error and penalty; the star marks the selected degree.

The classes are polynomial classifiers of degree at most kk with coefficients in {−1,0,1}\{-1,0,1\}, so they contain at most 3k+13^{k+1} formulas. They are enumerated on a nested synthetic sample and an independent 2000-example test is reported. Each class uses bk=log⁡(2∣Hk∣/(δwk))/(2n)b_k=\sqrt{\log(2|\mathcal H_k|/(\delta w_k))/(2n)} with δ=.05\delta=.05. The figure compares uniform weights across seven degrees with wk=2−k−1w_k=2^{-k-1}; the truncated geometric sum is below one. The test does not participate in selection.

Nonuniform learning and Occam

In uniform PAC, sufficient sample size depends on ε\varepsilon and δ\delta, not the target hypothesis. Nonuniform learnability also permits dependence on the target hypothesis, although the algorithm does not know it. In realizable binary classification, under usual measurability assumptions, this is equivalent to expressing H\mathcal H as a countable union of finite-VC subclasses. For sufficiency assign positive weights to classes and use SRM; each target belongs to a class of finite complexity. For necessity group targets by sample sizes allowing them to be learned at fixed accuracy and confidence; infinite VC dimension in such a group would let shattered points contradict its shared guarantee. The characterization promises neither computational efficiency nor a uniform rate for the whole union.

If every hypothesis has a prefix-free binary description of length L(h)L(h), Kraft gives ∑h2−L(h)≤1\sum_h2^{-L(h)}\le1. For a countable class, apply two-sided Hoeffding and allocate failure proportional to 2−L(h)2^{-L(h)}: with probability at least 1−δ1-\delta, simultaneously for all,

∣R(h)−R^(h)∣≤L(h)ln⁡2+ln⁡(2/δ)2n.|R(h)-\widehat R(h)|\le\sqrt{\frac{L(h)\ln2+\ln(2/\delta)}{2n}}.

This Occam bound permits hypothesis selection after seeing the sample, provided the code was fixed beforehand. A short description pays less among hypotheses with equal empirical error. MDL also uses code lengths, but a generalization bound and a compression criterion are not automatically identical.

InteractiveDescription bits and the Occam bound
×
✓
✓
✓
✓
✓
×
✓
✓
×
✓
✓
✓
×
✓
✓
✓
✓
✓
✓
✓
✓
✓
✓
✓
✓
✓
✓
×
✓
✓
✓
×
✓
✓
✓
✓
✓
✓
✓

✓ correct, × error. Fixed samples are generated by arithmetic rules; the margin compares codes and is not a population evaluation of this deterministic sample.

Rule
4
Code length8 bits
Training errors6/40
Two-sided bound0.490
Build a simple rule and compare errors and its prefix-code length.

The example code reserves prefixes 00 and 01 for constants, 10 for a stump followed by six bits, and 11 for a conjunction of two stumps with twelve bits. The stump uses two bits for feature, three for threshold and one for orientation; the figure shows a subfamily. Its 40 examples are deterministic: the visual number shows the formula, not a statistical guarantee on that sample without an i.i.d. assumption.

Selection by validation

Suppose kk predictors and their transformations are fixed independently of an i.i.d. validation set of size nvn_v, with losses in [0,1][0,1]. A Hoeffding union bound gives simultaneously

∣R(hj)−R^v(hj)∣≤a,a=ln⁡(2k/δ)2nv.|R(h_j)-\widehat R_v(h_j)|\le a,\qquad a=\sqrt{\frac{\ln(2k/\delta)}{2n_v}}.

If h^\widehat h minimizes validation loss, then R(h^)≤min⁡jR(hj)+2aR(\widehat h)\le\min_jR(h_j)+2a. This validation selection guarantee includes the log⁡k\log k price. It may condition on training if candidates depend on training but not the holdout. If later proposals depend on earlier results from the same holdout, they are no longer a fixed independent list and this union bound does not apply directly.

Cross-validation reuses data for training and evaluation with dependent folds. It can help choose hyperparameters, but its scores are not automatically independent confidence intervals. Use nested validation to evaluate the selection procedure and reserve an independent final test. Fitting features, scales or imputation on all data before splitting introduces leakage.

[ ]SRM versus holdout across replicatesBrowser
import itertools
import numpy as np
from math import comb
rng=np.random.default_rng(1310)
classes=[np.array(list(itertools.product((-1.,0.,1.),repeat=k+1))) for k in range(5)]
def predictions(x,C): return np.vander(x,C.shape[1],increasing=True)@C.T>=0
for n in (60,120,300):
    excess={'SRM finita':[],'SRM VC':[],'SRM Rademacher':[],'validación':[]}
    for rep in range(12):
        x=rng.uniform(-1,1,n); eta=.5+.35*np.sin(4*x); y=rng.binomial(1,eta)
        xt=rng.uniform(-1,1,2000); et=.5+.35*np.sin(4*xt); bayes=np.minimum(et,1-et).mean()
        split=2*n//3; cand=[]; finite=[]; vc=[]; rad=[]; valid=[]
        for k,C in enumerate(classes):
            H=predictions(x,C); losses=(H[:split]!=y[:split,None]); errors=losses.mean(axis=0); best=errors.argmin(); cand.append(predictions(xt,C)[...,best])
            wk=2**(-k-1); delta=.05*wk; finite.append(errors[best]+np.sqrt(np.log(2*len(C)/delta)/(2*split)))
            traces=sum(comb(split,j) for j in range(min(k+1,split)+1))
            vc.append(errors[best]+2*np.sqrt(2*np.log(traces)/split)+3*np.sqrt(np.log(2/delta)/(2*split)))
            signs=rng.choice([-1,1],size=(400,split)); mc=(signs@losses).max(axis=1).mean()/split
            upper=mc+np.sqrt(2*np.log(2/delta)/len(signs))
            rad.append(errors[best]+2*upper+3*np.sqrt(np.log(4/delta)/(2*split)))
            valid.append(np.mean(H[split:,best]!=y[split:]))
        for key,values in [('SRM finita',finite),('SRM VC',vc),('SRM Rademacher',rad),('validación',valid)]:
            pred=cand[np.argmin(values)]; risk=np.mean(np.where(pred,1-et,et)); excess[key].append(risk-bayes)
    print('n',n,[(k,round(np.mean(v),4)) for k,v in excess.items()])

Each candidate is trained on the first two thirds; the last third selects by validation. Other selections use training only and geometric-weight penalties. The VC bound uses dimension at most k+1k+1 for signs of univariate degree-kk polynomials. For Rademacher, 400 draws estimate the loss-class supremum and a Hoeffding correction pays for Monte Carlo error and part of δwk\delta w_k. Excess is calculated on a random grid of 2000 inputs with known probabilities, not from test labels. These are 12 illustrative replicates, not a universal method comparison.

Adaptive queries

On a leaderboard, each query result influences the next submission. Adaptive analysis can overfit even when individual proposals are random. The majority attack of Blum and Hardt retains random vectors whose public scores beat chance and combines them coordinatewise. Selection makes the vote correlate with public holdout labels without learning the distribution; on independent private coordinates it remains near chance in expectation.

InteractiveA leaderboard that leaks information
  • public vote
  • private vote
  • expected chance
Mechanism
10 submissions
Retained submissions4
Public vote accuracy0.537
Private vote accuracy0.490
Compare direct scores with a simplified Ladder; replay submissions and observe public and private results.

The model uses 80 public and 1000 private labels, 600 reproducible pseudorandom submissions, and votes over accepted proposals. With direct scoring a proposal is kept if it exceeds .5 publicly. The simplified Ladder variant releases and accepts only improvements over .05 relative to the previous best, rounded to .05; the vote is evaluated separately to show leakage. This is a teaching variant, not the full implementation or proof that every attack is neutralized. In both modes private results are shown for experiment evaluation and not used to select proposals.

The original Thresholdout mechanism compares training and holdout means with Laplace noise, returns the training mean if they agree and a noisy holdout mean if they differ. It consumes a finite budget on disagreements. Its theory uses differential privacy and requires specific parameters and assumptions; adding uncalibrated noise without budget control does not guarantee validity. The following cell implements pseudocode with a persistent noisy threshold and compares it with direct access in a bounded simulation.

[ ]Majority attack and ThresholdoutBrowser
import numpy as np
class Thresholdout:
    def __init__(self,threshold,sigma,budget,rng):
        self.t=threshold; self.s=sigma; self.b=budget; self.rng=rng
        self.noisy_t=threshold+rng.laplace(0,2*sigma)
    def query(self,train,hold):
        if self.b<1: return None
        eta=self.rng.laplace(0,4*self.s)
        if abs(hold-train)>self.noisy_t+eta:
            out=hold+self.rng.laplace(0,self.s); self.b-=1
            self.noisy_t=self.t+self.rng.laplace(0,2*self.s)
            return out
        return train
def simulate(mode,seed):
    rng=np.random.default_rng(seed); n=80; m=1000; k=300
    y=rng.choice([-1,1],size=2*n+m); vote=np.zeros(len(y)); accepted=0; answered=0
    mech=Thresholdout(.08,.01,20,np.random.default_rng(seed+100000))
    for i in range(k):
        proposal=rng.choice([-1,1],size=len(y)); train=np.mean(proposal[:n]==y[:n]); hold=np.mean(proposal[n:2*n]==y[n:2*n])
        value=hold if mode=='directo' else mech.query(train,hold)
        if value is None: break
        answered+=1
        if value>.5: vote+=proposal; accepted+=1
    pred=np.where(vote>=0,1,-1)
    return answered,accepted,np.mean(pred[n:2*n]==y[n:2*n]),np.mean(pred[2*n:]==y[2*n:])
for mode in ('directo','thresholdout'):
    results=np.array([simulate(mode,1310+i) for i in range(10)])
    print(mode,'consultas, aceptadas, público, privado:',np.round(results.mean(axis=0),3))

The mechanism returns None when its budget is exhausted; the cell does not present its chosen parameters as a formal guarantee for this sample. A separate noise sequence permits comparison of the same proposals in both modes until budget exhaustion. Votes use visible answers and the private set is inspected only at the end. Actual public accuracy is calculated for diagnosis, not as an additional mechanism response. The experiment compares two particular strategies, not every possible attack.

Changing the test can also reveal distribution shift. Recht et al. observed accuracy drops when constructing new CIFAR-10 and ImageNet tests, but their results suggest harder images and do not attribute the drops to adaptivity. Document each split’s source, fix decisions before the final test and record which responses have been reused.

Exercises

Proof
Prove: Prove the SRM oracle inequality.
0
For each class, two-sided deviation fails with probability at most δwₖ.

Step 1 of 2. What does the weighted union provide?

Proof
Prove: Derive the Occam bound using Kraft.
0
Each prefix code has length L(h) and weight 2⁻ᴸ⁽ʰ⁾.

Step 1 of 2. Why do allocated failures sum to at most δ?

Numeric
For k=100, n=5000 and δ=0.05, calculate √(ln(2k/δ)/(2n)).
Quiz
Which procedure introduces leakage that invalidates the direct test guarantee?
CodeA thresholded query
Implement thresholdout(train_val, holdout_val, threshold, sigma, rng): compare |holdout−train| with threshold plus Laplace noise of scale 4σ; if it exceeds the threshold, return holdout plus Laplace noise of scale σ; otherwise return train. This single-query version omits the persistent threshold and budget of the full mechanism.
def thresholdout(train_val, holdout_val, threshold, sigma, rng):
  pass
Shift+Enter to run

Summary

Key idea
SRM pays for class selection and competes with an oracle; Occam pays for description bits; validation pays for fixed candidates. Adaptive queries require controlling information leakage and reserving independent evaluation.

Sources: Ladder, Thresholdout and ImageNet v2.