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 and excess risk 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 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 be a Bayes rule, , , and the result of an approximate optimizer. When the minima exist, the excess-risk decomposition is the identity
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 , 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 . Inserting two empirical risks,
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 and a linear class of functions. The projection minimizes within the class, and the residual is orthogonal to every difference between two functions in the class. Therefore, for each fit in the class,
The inner expectation is over a new ; afterwards we may average over samples that produce . 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 , , and . 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.
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 or Bayes.
Consider a concrete reading of the maps: at degree zero, the signal oscillates but the predictor is constant; even as 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 ; 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: uniform on , , class 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 , seed 1302. The class contains , 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.
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 with , there exists a realizable distribution such that, when sampling , the learned rule has 0-1 risk at least with probability at least . The adversarial distribution may depend on the algorithm and . The result extends to randomized algorithms when the probability includes their randomness.
The proof selects points and distributes uniformly among them. There are possible deterministic labelings, all realizable. Average first over a uniform labeling and then over the i.i.d. sample of size . The sample observes at most 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 . Unseen mass is at least , hence joint expected risk is at least . By averaging, some fixed labeling produces expected risk at least .
If is risk under that labeling and , then . Since , it follows that . 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 , 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 , 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.
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 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 , Stone’s theorem gives universal consistency in expectation for nearest neighbors if and , 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 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 grows, while in the impossibility result the hard distribution may change with . 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 affect the required size. When choosing , increasing it reduces variation in the label average, but introduces bias if neighbors span regions with different probabilities. The condition makes the neighborhood local in the limit; permits averaging more labels. The theorem’s assumptions, including finite Euclidean geometry and tie-breaking, are part of the guarantee.
The figure uses uniform on and , with frequencies . Bayes risk is 0.1. Risks for 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.
Exercises
Step 1 of 2. How much expected risk do unseen points contribute at least?
Step 1 of 2. What is the sign of empirical risk of h-hat minus empirical risk of h°?
def decompose_error(degree, n, sampler, target, B):
pass