The learning problem: risk, excess risk and ERM
Formalize learning as the minimization of expected risk under an unknown distribution observed through an i.i.d. sample. Starting from the Bayes predictor, derive exact excess-risk identities for squared and 0-1 loss, define empirical risk minimization, and identify the generalization gap.
After this lesson you can
- Formulate a learning problem using (Z, D, H, loss), including the supervised case Z = X × Y, and write its population and empirical risks.
- Prove the Bayes excess-risk identities for squared and 0-1 loss, and calculate Bayes risk in a Gaussian example.
- Prove that empirical risk is unbiased for a fixed hypothesis and explain why selection by ERM changes this.
- Implement exact ERM over thresholds and intervals and measure the generalization gap as a function of n.
- Distinguish risk, excess risk and the generalization gap.
Before you start
A training score is not enough
Two models can correctly predict every observation used to build them and behave very differently on a new one. Choosing the model uses the same data used to calculate its average loss. This lesson distinguishes population risk, excess risk and the generalization gap, and shows how these quantities depend on the choice of hypothesis.
Distribution, loss and sample
The population risk and empirical risk, when the expectations exist, are
In binary classification, the 0-1 loss is . In squared-error regression, . Risk is a property of the rule and distribution, whereas empirical risk varies with the sample. For an fixed before observing , linearity of expectation gives . The strong law of large numbers implies almost-sure convergence for an integrable loss and a fixed hypothesis.
If the loss also has finite variance, independence gives . For 0-1 loss with risk , the standard deviation of the empirical error is . For example, with and it is approximately . Unbiased does not mean exact: on a particular sample the estimate may fall on either side of . The rate describes the standard deviation for a fixed rule; by itself it does not establish the same rate for every rule selected by an algorithm.
Neither equality of expectations nor that convergence alone controls a rule selected from the same sample. The analysis must account for the dependence of on .
An independent test sample answers a different question. Conditional on training, the rule is fixed and the average test loss estimates its risk under the test distribution. This requires the test set to be independent of selection and drawn from the distribution you want to evaluate. If you try many models on the same test set and choose the best one, you have also used the test set for selection, so its error no longer has the interpretation of an independent final evaluation.
The general definition does not require each observation to have a label: can be a complete sequence and the loss a function of that sequence. Choosing this unit does not automatically make neighboring tokens independent or remove distribution shifts. You must state what object is sampled and what distribution represents deployment. In time-ordered financial data, shuffling observations can mix future information into training; in code corpora, copies and forks may appear in both splits.
The Bayes predictor and excess risk
For regression, if and is measurable with finite second moment, the Bayes predictor is . Conditioning on , conditional expectation makes the cross term vanish:
Thus . The second term is irreducible risk under this loss: a more flexible function cannot remove the conditional variability of . This applies the variance decomposition; it is not a claim about noise of every kind.
The identity also characterizes equality: two predictors attain the same minimum squared risk if they agree almost surely under the distribution of . They may differ outside the support without changing that risk. This matters for extrapolation: a guarantee under says nothing about how the model should behave on inputs that never presents.
For binary classification, define . The conditional cost of predicting 0 is ; that of predicting 1 is . A Bayes rule is and
The proof is pointwise: if , the extra conditional cost is zero; otherwise it is the difference between the larger and smaller costs, . Integrating with respect to gives the identity. If , both decisions have the same cost and the Bayes rule is not unique in that region.
The figure computes two two-dimensional Gaussian densities. The optimal boundary equates the densities weighted by their prior probabilities. Equal covariances give a straight line; different covariances can give a conic. Your rule is a line whose angle and offset you can choose. Blue intensity measures where it disagrees with Bayes. Risks are approximated by quadrature on a finite square, so they are not exact integrals over the whole plane.
A one-dimensional example allows a closed-form risk calculation. With equally likely classes and , the boundary is 0. Each class has conditional error , giving . The classes overlap, so no classifier based only on can go below that value under this distribution.
The derivation uses the likelihood ratio: the logarithm of is because both variances equal 1. Equal priors do not shift the threshold. For class 0, ; for class 1, . If you change the priors or variances, recalculate the rule; a boundary at 0 is no longer guaranteed. also depends on the information given to the predictor: adding covariates can reduce Bayes risk, although it need not eliminate the remaining noise.
ERM and the generalization gap
Empirical risk minimization (ERM) returns a hypothesis when the minimum exists. The class matters: when is attained, excess risk decomposes as
The first difference is the cost of selecting a rule within the class; the second is the approximation error of that class. The generalization gap of the selected rule is : it can be negative on a particular sample. It is not excess risk and may be small even when the entire class approximates the Bayes predictor poorly.
To see the optimism in expectation, use the facts that sample by sample, that is fixed, and that sample by sample. Taking expectations,
The first step uses the fact that selection saw ; the second uses the population optimality of within the class. If the class has no minimizer, an approximation to the infimum can be used. It does not follow that every sample has a positive gap.
A minimal example makes selection visible. Suppose is a fair coin and contains only the two constant rules. With one observation, ERM chooses the constant matching the observed label: its training error is 0. For an independent new label, however, either constant fails with probability 0.5. The gap is 0.5 in every realization, although each fixed rule has unbiased empirical error before selection. Selection turns two unbiased estimators into their minimum, which is optimistic.
The population risk of a class is also relative to the loss. A rule optimizing 0-1 loss can differ from one optimizing log-loss, which predicts probabilities instead of a single label. Even with a fixed class, comparing training losses of different methods is not equivalent to comparing their risks under a common metric. In the identities above, the same loss is used to define both and .
One way to control selection is to require a simultaneous guarantee for the whole class. If, for a particular sample, , then
The first and last inequalities use the same uniform bound; the middle one uses ERM. Thus excess risk relative to the best rule in the class is at most . This is a deterministic consequence once the event holds, not a claim that a small always exists. For a finite class of size , losses in and i.i.d. samples, Hoeffding combined with a union bound over hypotheses yields that event with probability at least for . Later lessons replace with suitable complexity measures for infinite classes.
The distinction is clear even numerically. If a rule has risk and observed error , its gap is . If Bayes risk is , its excess is . These differences compare different quantities; neither can be derived from the other without more information. These numbers are an arithmetic example, not experimental results.
Consider the explicit distribution and . For , integrating the conditional cost to the left and right yields . Its minimum occurs at and equals .
In the next model each hypothesis has true risk , and its losses are independent Bernoulli coordinates of each observation. Sampling is repeated 800 times: the fixed hypothesis has zero population mean gap, while ERM selects the empirical minimum and has a nonnegative mean gap. Independence between hypotheses is an assumption of this toy model, not a property of real networks.
Since is continuous, a finite set of memorized points has probability zero for a new observation. The memorizer always predicts 0 outside that sample and its risk is , even though its training error is zero. The threshold does not necessarily improve monotonically as each example is added: every new sample can change the minimizer.
Lab: exact search over thresholds and intervals
Sorting makes it possible to examine every prediction change without testing each rule over the entire sample. For a threshold, crossing a group of equal values updates the error count in one step. For an interval, start with the rule predicting 0 everywhere and switch to 1 over a segment, adding the cost of negatives minus positives for each group. The minimum-sum segment is found with a minimum-subarray algorithm; the empty interval is also allowed.
import numpy as np
def erm_thresholds(x, y):
x, y = np.asarray(x, float), np.asarray(y, int)
values, inverse = np.unique(x, return_inverse=True)
positives = np.bincount(inverse, weights=y, minlength=len(values))
counts = np.bincount(inverse, minlength=len(values))
neg = counts - positives
right = np.r_[neg.sum(), neg.sum() + np.cumsum(positives - neg)]
left = len(y) - right
scores = np.stack([right, left])
orientation, cut = np.unravel_index(np.argmin(scores), scores.shape)
edges = np.r_[-np.inf, np.nextafter(values[:-1], values[1:]), np.inf]
return float(edges[cut]), bool(orientation == 0), int(scores[orientation, cut])
def erm_interval(x, y):
x, y = np.asarray(x, float), np.asarray(y, int)
values, inverse = np.unique(x, return_inverse=True)
positives = np.bincount(inverse, weights=y, minlength=len(values))
counts = np.bincount(inverse, minlength=len(values))
delta = counts - 2 * positives
best = current = 0.0
start = best_start = best_end = 0
for j, change in enumerate(delta):
if current + change > 0:
current, start = 0.0, j + 1
else:
current += change
if current < best:
best, best_start, best_end = current, start, j + 1
if best_end == 0:
return None, int(y.sum())
return (float(values[best_start]), float(values[best_end - 1])), int(y.sum() + best)
rng = np.random.default_rng(1301)
x = rng.uniform(size=80)
y = (rng.uniform(size=80) < 0.15 + 0.7 * x).astype(int)
t, positive_right, errors = erm_thresholds(x, y)
interval, errors_i = erm_interval(x, y)
print('umbral, dirección derecha, errores:', round(t, 3), positive_right, errors)
print('intervalo y errores:', interval, errors_i)
def risk_right(t):
t = np.clip(t, 0, 1)
return 0.5 - 0.7 * t + 0.7 * t * t
def risk_interval(interval):
if interval is None:
return 0.5
a, b = np.clip(interval, 0, 1)
return 0.5 + 0.7 * (b - a) - 0.7 * (b * b - a * a)
print('riesgo verdadero de umbral e intervalo:',
round(risk_right(t) if positive_right else 1 - risk_right(t), 4), round(risk_interval(interval), 4))
# Contraste exhaustivo en muestras pequeñas con empates y etiquetas arbitrarias.
for _ in range(100):
xx = rng.integers(0, 5, size=20).astype(float)
yy = rng.integers(0, 2, size=20)
values = np.unique(xx)
cuts = np.r_[-np.inf, np.nextafter(values[:-1], values[1:]), np.inf]
brute_t = min(np.sum((xx >= c if right else xx < c) != yy) for c in cuts for right in (True, False))
_, _, got_t = erm_thresholds(xx, yy)
choices = [int(yy.sum())] + [int(np.sum(((xx >= a) & (xx <= b)) != yy))
for a in values for b in values if a <= b]
_, got_i = erm_interval(xx, yy)
assert got_t == brute_t and got_i == min(choices)
print('100 controles exhaustivos con empates: correctos')Sorting dominates the cost, ; the sweep is linear in the number of distinct values. Ties are grouped because a threshold cannot separate examples with the same value. If there are several minimizers, this implementation returns one of them. Noisy labels do not affect the correctness of the search, but they do affect which rule has the fewest errors.
To verify the threshold sweep, start with all points classified as 1: the number of errors is the number of 0 labels. As the threshold crosses a group, all its points switch to 0: add the number of 1 labels and subtract the number of 0 labels. This gives the error after each group without scanning the data again. The other orientation reverses all binary predictions, so it has minus that error count. The two constant rules are included through infinite thresholds.
For intervals, assign group the increment when its predictions change from 0 to 1. Every nonempty interval corresponds to a contiguous segment of groups and its error is the error of the constant 0 rule plus the sum over that segment. The algorithm maintains the smallest segment sum ending at the current group and the best found so far. If the accumulated sum is positive, starting over cannot worsen a future segment. The empty segment has increment zero. This explains why one sweep finds the minimum, even when tied points have conflicting labels.
Under the uniform model, the risk of predicting 1 on can be calculated without another sample: begin with the risk of always predicting 0, which is , and add . The result is . Endpoints do not affect the integral for continuous , although they matter when counting training ties. The cell compares both exact risks under this model and checks both sweeps against exhaustive search on 100 small discrete samples.
To observe the scale of the gap without pretending that every distribution has the same rate, use labels independent of with probability . Every deterministic rule has risk , but ERM selects favorable fluctuations. The estimated log-log slope from one run is descriptive, not a universal theorem for every distribution.
import matplotlib.pyplot as plt
rng = np.random.default_rng(1302)
sizes = np.array([20, 40, 80, 160, 320, 640])
gaps, interval_gaps = [], []
for n in sizes:
values, interval_values = [], []
for _ in range(120):
x = rng.uniform(size=n)
y = rng.integers(0, 2, size=n)
_, _, errors = erm_thresholds(x, y)
_, interval_errors = erm_interval(x, y)
values.append(0.5 - errors / n)
interval_values.append(0.5 - interval_errors / n)
gaps.append(np.mean(values))
interval_gaps.append(np.mean(interval_values))
print('n:', sizes)
print('brechas medias, umbrales:', np.round(gaps, 4))
print('brechas medias, intervalos:', np.round(interval_gaps, 4))
print('pendiente log-log, umbrales:', round(np.polyfit(np.log(sizes), np.log(gaps), 1)[0], 3))
print('pendiente log-log, intervalos:', round(np.polyfit(np.log(sizes), np.log(interval_gaps), 1)[0], 3))
plt.loglog(sizes, gaps, 'o-', label='umbrales')
plt.loglog(sizes, interval_gaps, 's-', label='intervalos')
plt.loglog(sizes, gaps[0] * np.sqrt(sizes[0] / sizes), '--', label='referencia n^(-1/2)')
plt.xlabel('tamaño de muestra n')
plt.ylabel('brecha media')
plt.legend()
plt.show()Gaussians: Bayes, simulation and classifiers
The formula provides a reference. In the next experiment, linear and quadratic discriminant analysis are fitted to increasing sample sizes and evaluated on an independent test set. The numbers correspond to this seed and test size. LDA matches the shape of the population boundary when covariances are equal; QDA estimates more parameters and its advantage is not guaranteed on small samples.
The Monte Carlo error of the Bayes rule is a proportion of independent errors. Its theoretical standard deviation over test observations is ; with it is approximately . A difference of a few thousandths between simulation and formula is consistent with that variation. LDA and QDA share this test set, so their errors are correlated. To compare methods precisely, repeat training and evaluation sets rather than declaring the smallest value in one table the winner.
from scipy.stats import norm
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis, QuadraticDiscriminantAnalysis
rng = np.random.default_rng(1303)
def gaussian_sample(n):
labels = rng.integers(0, 2, size=n)
x = rng.normal(loc=2 * labels - 1, scale=1, size=n)
return x[:, None], labels
test_x, test_y = gaussian_sample(20000)
bayes_mc = np.mean((test_x[:, 0] >= 0) != test_y)
print('Bayes exacto:', round(norm.cdf(-1), 4), 'Monte Carlo:', round(bayes_mc, 4))
for n in (50, 200, 1000):
train_x, train_y = gaussian_sample(n)
lda = LinearDiscriminantAnalysis().fit(train_x, train_y)
qda = QuadraticDiscriminantAnalysis().fit(train_x, train_y)
print('n', n, 'LDA', round(1 - lda.score(test_x, test_y), 4), 'QDA', round(1 - qda.score(test_x, test_y), 4))Exercises
Step 1 of 2. What happens to the cross term when conditioning on X?
Step 1 of 2. What is the cost of predicting 0?
def erm_thresholds(x, y):
pass