Module contents
Lesson 2 of 20Core 90 min

Overfitting, inductive bias and the No Free Lunch theorem

Explain how inductive bias supports generalization, decompose excess risk into approximation, estimation and optimization, and examine the scope of No Free Lunch and universal consistency.

After this lesson you can

  • Define overfitting and underfitting in terms of empirical risk, population risk and approximation error.
  • Decompose excess risk into approximation, estimation and optimization and reason about which term dominates in a given scenario.
  • Prove the No Free Lunch theorem in the version of Shalev-Shwartz and Ben-David.
  • Distinguish consistency, universal consistency and a uniform rate, and explain why there is no universal rate.
  • Design synthetic experiments that isolate each term of the decomposition.

Before you start

Learning requires preferences

In the previous lesson, memorizing training labels gave zero error and high population risk. Other rules could agree on all observed data and disagree on unobserved data. Why prefer one of them? A learning method needs a preference beyond compatibility with the sample. That preference can help when it matches the distribution and hurt when it excludes relevant structure.

The generalization gap R(h^)−R^S(h^)R(\hat h)-\widehat R_S(\hat h) and excess risk R(h^)−R∗R(\hat h)-R^* answer different questions. A large gap can accompany overfitting, but alone it does not determine whether the rule is good. High values for both curves alone do not diagnose underfitting either: there may be irreducible noise. Compare with a suitable reference and consider the loss and distribution. If the evaluation sample is used to choose the model, it is no longer an independent final evaluation.

For example, a classifier that ignores XX and always predicts the majority class may have similar training and test errors. If a covariate separates the classes, its excess risk can still be high: a small gap does not show that it has learned enough. Conversely, a rule that memorizes identifiers can have zero training error and fail on new identifiers. The difference is a useful measure of overfitting only if evaluation represents the future distribution and shares no duplicates with training.

Biases appear in several places. A fixed-degree polynomial excludes irregular functions. A norm penalty prefers some parameters over others without necessarily forbidding them. A prior assigns different weights to hypotheses. A convolutional architecture shares filters and favors certain local patterns; data order, initialization and early stopping can also cause an algorithm to prefer some solutions over others. These choices are not mathematically interchangeable, although they all affect what is learned from finite data.

Three causes of excess risk

Let h∗h^* be a Bayes rule, h∘∈arg min⁡h∈HR(h)h^\circ\in\argmin_{h\in\mathcal H}R(h), h^∈arg min⁡h∈HR^S(h)\hat h\in\argmin_{h\in\mathcal H}\widehat R_S(h), and h~∈H\tilde h\in\mathcal H the result of an approximate optimizer. When the minima exist, the excess-risk decomposition is the identity

R(h~)−R(h∗)=R(h∘)−R(h∗)⏟aproximacioˊn+R(h^)−R(h∘)⏟estimacioˊn+R(h~)−R(h^)⏟optimizacioˊn poblacional.R(\tilde h)-R(h^*)=\underbrace{R(h^\circ)-R(h^*)}_{\text{aproximación}}+\underbrace{R(\hat h)-R(h^\circ)}_{\text{estimación}}+\underbrace{R(\tilde h)-R(\hat h)}_{\text{optimización poblacional}}.

Approximation measures what the best rule in the class loses. Estimation measures the population cost of choosing from the sample using exact ERM; both terms are nonnegative. The third compares population risks and can be negative: incomplete optimization can act as regularization. It is not equal to R^S(h~)−R^S(h^)≥0\widehat R_S(\tilde h)-\widehat R_S(\hat h)\ge0, the empirical optimization error. If the minimum is not attained, infima and approximations are used. Classification requires measurable rules and the corresponding expectations.

For exact ERM, a bound connects the second term with uniform convergence. Write Δ=sup⁡h∈H∣R(h)−R^S(h)∣\Delta=\sup_{h\in\mathcal H}|R(h)-\widehat R_S(h)|. Inserting two empirical risks,

R(h^)−R(h∘)=[R(h^)−R^S(h^)]+[R^S(h^)−R^S(h∘)]+[R^S(h∘)−R(h∘)]≤2Δ.R(\hat h)-R(h^\circ)=[R(\hat h)-\widehat R_S(\hat h)]+[\widehat R_S(\hat h)-\widehat R_S(h^\circ)]+[\widehat R_S(h^\circ)-R(h^\circ)]\le2\Delta.

The middle term is nonpositive by ERM. The inequality does not say that enlarging the class always worsens risk on a particular sample: with nested classes approximation error cannot increase, but estimation can become harder. Sample size, distribution and algorithm matter.

To see where the sum in the figure comes from, take squared-error regression with f∗(x)=E[Y∣X=x]f^*(x)=\E[Y\mid X=x] and a linear class of functions. The projection f∘f^\circ minimizes E[(f(X)−f∗(X))2]\E[(f(X)-f^*(X))^2] within the class, and the residual f∗−f∘f^*-f^\circ is orthogonal to every difference between two functions in the class. Therefore, for each fit f^\hat f in the class,

R(f^)=R∗+E[(f∘(X)−f∗(X))2]+E[(f^(X)−f∘(X))2].R(\hat f)=R^*+\E[(f^\circ(X)-f^*(X))^2]+\E[(\hat f(X)-f^\circ(X))^2].

The inner expectation is over a new XX; afterwards we may average over samples that produce f^\hat f. This orthogonality is not a generic identity for every loss or class. For log-loss or 0-1 classification, use the risk decomposition rather than a squared distance between predictions.

The next figure uses X∼Unif⁡[−1,1]X\sim\Unif[-1,1], Y=sin⁡(πX)+ϵY=\sin(\pi X)+\epsilon, and ϵ∼N(0,0.32)\epsilon\sim\Normal(0,0.3^2). The population projection onto polynomials is calculated using 400-node quadrature; the fit distance from that projection is averaged over 200 independent samples per configuration. By orthogonality, the three bar components add to mean squared risk. Quadrature and Monte Carlo are numerical approximations and the values depend on seed 1302.

InteractiveApproximation versus estimation
Mean risk00.88
  • approximation
  • estimation
  • noise
1
40
Approximation0.1960
Mean estimation0.0159
Irreducible noise0.0900
Mean total risk0.3020
Change degree and sample size. With nested classes approximation error falls; find the lowest total and compare how the cost of estimation changes as n grows.
[ ]Measure each term with independent samplesBrowser
import numpy as np
import matplotlib.pyplot as plt
from numpy.polynomial.legendre import legvander, leggauss

rng = np.random.default_rng(1302)
xq, wq = leggauss(250)
wq /= 2
f = lambda x: np.sin(np.pi * x)
degrees, sizes, B = range(6), [20, 40, 80, 160, 320], 100
approx = np.zeros((len(degrees), len(sizes)))
estimate = np.zeros_like(approx)
for d in degrees:
    q = legvander(xq, d)
    c = np.linalg.solve(q.T @ (wq[:, None] * q), q.T @ (wq * f(xq)))
    a = np.sum(wq * (q @ c - f(xq)) ** 2)
    for j, n in enumerate(sizes):
        excess = []
        for _ in range(B):
            x = rng.uniform(-1, 1, n)
            y = f(x) + rng.normal(0, .3, n)
            fit = np.linalg.lstsq(legvander(x, d), y, rcond=None)[0]
            excess.append(np.sum(wq * (q @ fit - q @ c) ** 2))
        approx[d, j], estimate[d, j] = a, np.mean(excess)
print('Grado mínimo del riesgo medio para cada n:', np.argmin(approx + estimate, axis=0))
fig, axes = plt.subplots(1, 2, figsize=(9, 3))
for ax, values, title in zip(axes, [approx, estimate], ['aproximación', 'estimación']):
    image = ax.imshow(values, aspect='auto', origin='lower')
    ax.set_xticks(range(len(sizes)), sizes); ax.set_xlabel('n'); ax.set_ylabel('grado'); ax.set_title(title)
    fig.colorbar(image, ax=ax)
plt.tight_layout()
plt.show()

The projection is calculated outside each fitting sample. Cells repeated for estimation use new data; quadrature represents the known distribution, which is normally unavailable in a real problem. An independent test estimate approximates risk, but does not directly reveal h∘h^\circ or Bayes.

Consider a concrete reading of the maps: at degree zero, the signal oscillates but the predictor is constant; even as nn grows, approximation error remains. At degree five with small samples, the endpoints may be poorly represented and the fit varies greatly between samples. More data reduces this variability in this experiment. The minimum also depends on noise, the degree range and the distribution of XX; it is not a universal rule for the optimal degree.

When computation also has a cost

With a fixed budget, using more data leaves fewer passes per example. Bottou and Bousquet explain that the precision required for optimization depends on statistical error: solving a noisy empirical objective to high precision is not always worthwhile. This comparison depends on the method, class, data and budget; it is not a law that one pass is always optimal.

The figure uses correctly specified logistic regression: XX uniform on [−1,1][-1,1], P(Y=1∣X=x)=σ(3x)\Pr(Y=1\mid X=x)=\sigma(3x), class σ(wx)\sigma(wx) and log-loss. Quadrature calculates population risks; Newton estimates scalar ERM and SGD uses 8192 individual gradients divided into complete passes. Results average 80 samples per nn, seed 1302. The class contains w=3w=3, so approximation error is zero. Logistic Bayes risk is approximately 0.46694. The optimization curve is a signed population difference.

The budget counts individual gradients, not wall-clock time. Newton is calculated separately to define the ERM reference and is excluded from the SGD budget. The curves answer a controlled question: with this learning rate and data family, how does the approximate solution change when the same number of updates is spread over more examples? Data preparation cost, parallelism and run-to-run variation are outside the model. The optimization difference can be negative because exact ERM is adapted to the sample; it is not guaranteed to be the best population rule among optimizer trajectories.

InteractiveData and passes under a fixed budget
  • estimation
  • optimization
  • total excess
512
SGD passes16
Approximation (correct model)0
Mean estimation0.00096
Optimization difference−0.00003
Mean total excess0.00093
Move n: at 8192 examples one pass remains. Compare total excess with its two differences and avoid interpreting a negative term as an arithmetic error.

No Free Lunch: what can be guaranteed

The No Free Lunch theorem, in the version of Theorem 5.1 by Shalev-Shwartz and Ben-David, states the following. For any binary classification algorithm and any mm with 2m<∣X∣2m<|\mathcal X|, there exists a realizable distribution DD such that, when sampling S∼DmS\sim D^m, the learned rule has 0-1 risk at least 1/81/8 with probability at least 1/71/7. The adversarial distribution may depend on the algorithm and mm. The result extends to randomized algorithms when the probability includes their randomness.

The proof selects 2m2m points and distributes XX uniformly among them. There are 22m2^{2m} possible deterministic labelings, all realizable. Average first over a uniform labeling and then over the i.i.d. sample of size mm. The sample observes at most mm distinct points, even with repetitions. At each unseen point, its label remains an independent fair bit given what was observed, so any prediction fails with probability 1/21/2. Unseen mass is at least 1/21/2, hence joint expected risk is at least 1/41/4. By averaging, some fixed labeling produces expected risk at least 1/41/4.

If L∈[0,1]L\in[0,1] is risk under that labeling and p=P(L≥1/8)p=\Pr(L\ge1/8), then EL≤(1−p)/8+p=(1+7p)/8\E L\le(1-p)/8+p=(1+7p)/8. Since EL≥1/4\E L\ge1/4, it follows that p≥1/7p\ge1/7. The argument averages over tasks; it does not use an adversary that changes the label after seeing a prediction in the fixed problem.

Pay attention to the order of the quantifiers: first fix the algorithm and mm, then construct some realizable distribution on which it fails with the stated probability. The theorem does not assert that one distribution is difficult for all algorithms, or that the hard distribution remains the same for every sample size. Knowing the target function in advance would give a one-hypothesis class and solve that particular task, but such knowledge is additional information unavailable to the general construction.

On an infinite domain, the class of all binary functions has no distribution-free uniform PAC guarantee with finite sample size: for any mm, the construction finds a hard realizable task. On a fixed finite domain, the class is finite and can be learned with enough samples; the result does not claim impossibility when the data budget grows with the domain size.

The figure simplifies the game: four of eight positions are observed without replacement, and the average is over all 256 labelings. The unseen half has mean error 1/2 for every rule; if the learner memorizes the seen labels, mean risk over all eight points is 1/4. The theorem permits repetitions and only needs unseen mass of at least 1/2. Then restrict the family to nine monotone functions: rules can now be distinguished because the family has structure.

InteractiveThe No Free Lunch adversary
x=0
seen
actual 0
pred. 0
x=1
unseen
actual 0
pred. 0
x=2
seen
actual 0
pred. 0
x=3
unseen
actual 0
pred. 0
x=4
seen
actual 0
pred. 0
x=5
unseen
actual 0
pred. 0
x=6
seen
actual 0
pred. 0
x=7
unseen
actual 0
pred. 0
Rule
Target family
1 / 256
Errors on four unseen points0/4
Running average0.000
Full out-of-sample average0.500
Replay the enumeration and compare the cumulative mean with the exhaustive mean. The family includes 256 functions or nine monotone thresholds, with the same four observed points.
[ ]Exhaustive enumerationBrowser
import numpy as np
from sklearn.tree import DecisionTreeClassifier

seen = np.array([0, 2, 4, 6]); unseen = np.array([1, 3, 5, 7])
def loss(mask, rule):
    y = np.array([(mask >> i) & 1 for i in range(8)])
    if rule == 'mayoría':
        pred = np.full(4, int(y[seen].sum() > 2))
    elif rule == 'memoria':
        pred = np.zeros(4, dtype=int)
    elif rule == '1-NN':
        pred = y[seen[np.abs(unseen[:,None] - seen).argmin(axis=1)]]
    else:
        model = DecisionTreeClassifier(max_depth=1, random_state=0).fit(seen[:,None], y[seen])
        pred = model.predict(unseen[:,None])
    return np.mean(pred != y[unseen])
families = {'todas': range(256), 'monótonas': [sum((i >= t) << i for i in range(8)) for t in range(9)]}
for name, masks in families.items():
    print(name, {rule: round(np.mean([loss(m, rule) for m in masks]), 3)
                 for rule in ['mayoría', 'memoria', '1-NN', 'stump']})

Here the scikit-learn stump can choose either orientation, while the interactive threshold only predicts 1 to the right. Their averages on the restricted family therefore need not match. No Free Lunch also does not say that every algorithm performs equally on real data: tasks are not uniformly distributed across all functions. Images with locality, structured text and graphs with symmetries admit useful biases; evidence of their usefulness comes from the target distribution, not from the theorem.

Consistency does not imply a universal rate

A rule is consistent for a distribution if its excess risk converges to zero as nn increases; specify whether convergence is in expectation, in probability or almost surely. It is universally consistent over a family if this holds for each fixed distribution in that family. For classification on Rd\mathbb R^d, Stone’s theorem gives universal consistency in expectation for kk nearest neighbors if k→∞k\to\infty and k/n→0k/n\to0, with an appropriate tie-breaking rule; see Biau and Devroye, Chapter 19.

This gives no uniform rate for all distributions. No Free Lunch already shows the obstacle: for each nn another sufficiently hard realizable distribution can be chosen, so expected excess risk is at least 1/4. Thus no deterministic sequence tending to zero simultaneously bounds that excess for all distributions and sample sizes. There is no contradiction: consistency fixes a distribution before nn grows, while in the impossibility result the hard distribution may change with nn. Rates require quantitative assumptions, such as smoothness or a margin condition.

The distinction has a practical consequence. An asymptotic claim does not say how many observations a particular task needs to reach useful error. Dimension, noise, mass near the boundary and the variation scale of η\eta affect the required size. When choosing kk, increasing it reduces variation in the label average, but introduces bias if neighbors span regions with different probabilities. The condition k/n→0k/n\to0 makes the neighborhood local in the limit; k→∞k\to\infty permits averaging more labels. The theorem’s assumptions, including finite Euclidean geometry and tie-breaking, are part of the guarantee.

The figure uses XX uniform on [0,1][0,1] and η(x)=0.1+0.81{sin⁡(2πrx)≥0}\eta(x)=0.1+0.8\mathbf1\{\sin(2\pi r x)\ge0\}, with frequencies r=1,3,7r=1,3,7. Bayes risk is 0.1. Risks for k=⌊n⌋k=\lfloor\sqrt n\rfloor average 50 samples and a 2048-point grid integrates conditional loss. Curves over a finite range illustrate the delay; they do not prove convergence or uniform impossibility.

InteractiveConsistency without a guaranteed rate
  • k-NN, k = ⌊√n⌋
  • Bayes
1
Bayes risk0.100
Mean risk with n = 10240.102
Increase the frequency and observe when neighbors become local relative to the regions. The Bayes line is known by construction.

Exercises

Proof
Prove: Prove the No Free Lunch version with constants 1/8 and 1/7.
0
Take 2m equally likely points and average uniformly over their binary labelings.

Step 1 of 2. How much expected risk do unseen points contribute at least?

Proof
Prove: Bound ERM excess within its class.
0
Let h° be the population minimizer in H and h-hat an exact ERM; Δ is the supremum of the absolute risk discrepancy over H.

Step 1 of 2. What is the sign of empirical risk of h-hat minus empirical risk of h°?

Numeric
There are 20 equally likely points and 10 distinct observed points. A rule memorizes observed labels; average its risk over all binary labelings. What is the result?
Quiz
Which intervention can reduce estimation error at the cost of increasing approximation error?
CodeSeparate approximation and estimation
Implement decompose_error(degree, n, sampler, target, B), with degree ≥ 0, n > degree and B > 0. sampler(n, rng) returns iid inputs from a continuous distribution on [-1,1] and target(x) returns its noiseless signal. Using independent samples, calculate an approximate population polynomial projection and the mean squared distances between B noiseless least-squares fits and that projection. Return approximation and estimation. Use a fixed seed and at least 4000 independent points for projection and evaluation.
def decompose_error(degree, n, sampler, target, B):
  pass
Shift+Enter to run

Summary

Key idea
Prior structure enables generalization: approximation, estimation and optimization describe different sources of excess. No Free Lunch limits uniform guarantees without structure; universal consistency for each fixed distribution does not provide a uniform rate.