Module contents
Lesson 1 of 20Core 90 min

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

R(h)=EZ∼D[ℓ(h,Z)],R^S(h)=1n∑i=1nℓ(h,Zi).R(h)=\E_{Z\sim\mathcal D}[\ell(h,Z)],\qquad \widehat R_S(h)=\frac1n\sum_{i=1}^n\ell(h,Z_i).

In binary classification, the 0-1 loss is ℓ(h,(x,y))=1{h(x)≠y}\ell(h,(x,y))=\mathbf1\{h(x)\ne y\}. In squared-error regression, ℓ(f,(x,y))=(f(x)−y)2\ell(f,(x,y))=(f(x)-y)^2. Risk is a property of the rule and distribution, whereas empirical risk varies with the sample. For an hh fixed before observing SS, linearity of expectation gives ESR^S(h)=R(h)\E_S\widehat R_S(h)=R(h). 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 Var⁡S(R^S(h))=Var⁡(ℓ(h,Z))/n\Var_S(\widehat R_S(h))=\Var(\ell(h,Z))/n. For 0-1 loss with risk rr, the standard deviation of the empirical error is r(1−r)/n\sqrt{r(1-r)/n}. For example, with r=0.3r=0.3 and n=100n=100 it is approximately 0.04580.0458. Unbiased does not mean exact: on a particular sample the estimate may fall on either side of 0.30.3. The n−1/2n^{-1/2} 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 hh on SS.

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: ZZ 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 E[Y2]<∞\E[Y^2]<\infty and ff is measurable with finite second moment, the Bayes predictor is f∗(x)=E[Y∣X=x]f^*(x)=\E[Y\mid X=x]. Conditioning on XX, conditional expectation makes the cross term vanish:

R(f)=E[(f(X)−f∗(X)+f∗(X)−Y)2]=E[(f(X)−f∗(X))2]+E[Var⁡(Y∣X)].\begin{aligned} R(f)&=\E\big[(f(X)-f^*(X)+f^*(X)-Y)^2\big]\\ &=\E[(f(X)-f^*(X))^2]+\E[\Var(Y\mid X)]. \end{aligned}

Thus R(f)−R(f∗)=E[(f(X)−f∗(X))2]R(f)-R(f^*)=\E[(f(X)-f^*(X))^2]. The second term is irreducible risk under this loss: a more flexible function cannot remove the conditional variability of YY. 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 XX. They may differ outside the support without changing that risk. This matters for extrapolation: a guarantee under D\mathcal D says nothing about how the model should behave on inputs that D\mathcal D never presents.

For binary classification, define η(x)=P(Y=1∣X=x)\eta(x)=\Pr(Y=1\mid X=x). The conditional cost of predicting 0 is η(x)\eta(x); that of predicting 1 is 1−η(x)1-\eta(x). A Bayes rule is h∗(x)=1{η(x)≥1/2}h^*(x)=\mathbf1\{\eta(x)\ge 1/2\} and

R∗=E[min⁡{η(X),1−η(X)}],R(h)−R∗=E ⁣[∣2η(X)−1∣ 1{h(X)≠h∗(X)}].R^*=\E[\min\{\eta(X),1-\eta(X)\}],\qquad R(h)-R^*=\E\!\left[|2\eta(X)-1|\,\mathbf1\{h(X)\ne h^*(X)\}\right].

The proof is pointwise: if h=h∗h=h^*, the extra conditional cost is zero; otherwise it is the difference between the larger and smaller costs, ∣2η−1∣|2\eta-1|. Integrating with respect to XX gives the identity. If η=1/2\eta=1/2, 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 ∣2η−1∣|2\eta-1| where it disagrees with Bayes. Risks are approximated by quadrature on a finite square, so they are not exact integrals over the whole plane.

InteractiveThe Bayes boundary and excess risk
  • Bayes boundary
  • your boundary
  • weighted disagreement
Shading
1.0
1.0
0.50
0.7
0.00
Bayes risk (approximate quadrature)0.159
Risk of your rule0.213
Excess risk0.055
Drag the means. Change the second class standard deviations and its prior, and move your threshold. Switch between conditional Bayes error and the region where your rule disagrees: errors away from uncertainty cost more.

A one-dimensional example allows a closed-form risk calculation. With equally likely classes X∣Y=0∼N(−1,1)X\mid Y=0\sim\Normal(-1,1) and X∣Y=1∼N(1,1)X\mid Y=1\sim\Normal(1,1), the boundary is 0. Each class has conditional error Φ(−1)\Phi(-1), giving R∗=Φ(−1)≈0.1587R^*=\Phi(-1)\approx0.1587. The classes overlap, so no classifier based only on XX can go below that value under this distribution.

The derivation uses the likelihood ratio: the logarithm of p(x∣Y=1)/p(x∣Y=0)p(x\mid Y=1)/p(x\mid Y=0) is 2x2x because both variances equal 1. Equal priors do not shift the threshold. For class 0, P(X≥0∣Y=0)=1−Φ(1)=Φ(−1)\Pr(X\ge0\mid Y=0)=1-\Phi(1)=\Phi(-1); for class 1, P(X<0∣Y=1)=Φ(−1)\Pr(X<0\mid Y=1)=\Phi(-1). If you change the priors or variances, recalculate the rule; a boundary at 0 is no longer guaranteed. R∗R^* 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 h^S∈arg min⁡h∈HR^S(h)\hat h_S\in\argmin_{h\in\mathcal H}\widehat R_S(h) when the minimum exists. The class H\mathcal H matters: when h∘∈arg min⁡h∈HR(h)h^\circ\in\argmin_{h\in\mathcal H}R(h) is attained, excess risk decomposes as

R(h^S)−R∗=[R(h^S)−R(h∘)]+[R(h∘)−R∗].R(\hat h_S)-R^*=\big[R(\hat h_S)-R(h^\circ)\big]+\big[R(h^\circ)-R^*\big].

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 R(h^S)−R^S(h^S)R(\hat h_S)-\widehat R_S(\hat h_S): 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 R^S(h^S)≤R^S(h∘)\widehat R_S(\hat h_S)\le\widehat R_S(h^\circ) sample by sample, that h∘h^\circ is fixed, and that R(h^S)≥R(h∘)R(\hat h_S)\ge R(h^\circ) sample by sample. Taking expectations,

ESR^S(h^S)≤R(h∘)≤ESR(h^S).\E_S\widehat R_S(\hat h_S)\le R(h^\circ)\le\E_S R(\hat h_S).

The first step uses the fact that selection saw SS; the second uses the population optimality of h∘h^\circ 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 YY is a fair coin and H\mathcal H 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 RR and R∗R^*.

One way to control selection is to require a simultaneous guarantee for the whole class. If, for a particular sample, sup⁡h∈H∣R(h)−R^S(h)∣≤ϵ\sup_{h\in\mathcal H}|R(h)-\widehat R_S(h)|\le\epsilon, then

R(h^S)≤R^S(h^S)+ϵ≤R^S(h∘)+ϵ≤R(h∘)+2ϵ.R(\hat h_S)\le \widehat R_S(\hat h_S)+\epsilon \le \widehat R_S(h^\circ)+\epsilon \le R(h^\circ)+2\epsilon.

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 2ϵ2\epsilon. This is a deterministic consequence once the event holds, not a claim that a small ϵ\epsilon always exists. For a finite class of size MM, losses in [0,1][0,1] and i.i.d. samples, Hoeffding combined with a union bound over hypotheses yields that event with probability at least 1−δ1-\delta for ϵ=log⁡(2M/δ)/(2n)\epsilon=\sqrt{\log(2M/\delta)/(2n)}. Later lessons replace MM with suitable complexity measures for infinite classes.

The distinction is clear even numerically. If a rule has risk 0.40.4 and observed error 0.30.3, its gap is 0.10.1. If Bayes risk is 0.350.35, its excess is 0.050.05. 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 X∼Unif⁡(0,1)X\sim\Unif(0,1) and η(x)=0.15+0.7x\eta(x)=0.15+0.7x. For ht(x)=1{x≥t}h_t(x)=\mathbf1\{x\ge t\}, integrating the conditional cost to the left and right yields R(t)=0.5−0.7t+0.7t2R(t)=0.5-0.7t+0.7t^2. Its minimum occurs at t=0.5t=0.5 and equals 0.3250.325.

InteractiveEmpirical versus true risk
  • population risk
  • empirical risk
40
ERM threshold0.734
ERM empirical risk0.275
ERM population risk0.363
Gap for this sample0.088
Change the sample size and resample. The curve is the exact risk under the model; the step function counts sample errors. Compare them at the selected threshold.

In the next model each hypothesis has true risk 0.50.5, 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.

InteractiveFixed versus selected hypothesis
  • fixed
  • chosen by ERM
40
10
Mean gap, fixed hypothesis0.006
Mean gap, ERM0.121
Increase the number of candidates and the sample size. The simulation uses independent losses with probability 0.5; frequencies change with selection.
InteractiveThe memorizer trap
  • memorizer, population
  • threshold, population
  • threshold, training
50
Memorizer: training error0
Memorizer: population risk0.500
Threshold: training error0.160
Threshold: population risk0.358
Add examples or change the seed. The memorizer gets every training point right and predicts 0 elsewhere; the threshold uses a restricted class. The population curves are known exactly under the model.

Since XX 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 P(Y=1)=0.5\Pr(Y=1)=0.5, 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.

[ ]Exact ERM using sorting and a sweepBrowser
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, O(nlog⁡n)O(n\log n); 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 nn minus that error count. The two constant rules are included through infinite thresholds.

For intervals, assign group jj the increment Δj=nj,0−nj,1\Delta_j=n_{j,0}-n_{j,1} 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 [a,b][a,b] can be calculated without another sample: begin with the risk of always predicting 0, which is ∫01η(x) dx=0.5\int_0^1\eta(x)\,dx=0.5, and add ∫ab(1−2η(x)) dx\int_a^b(1-2\eta(x))\,dx. The result is 0.5+0.7(b−a)−0.7(b2−a2)0.5+0.7(b-a)-0.7(b^2-a^2). Endpoints do not affect the integral for continuous XX, 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 XX with probability 1/21/2. Every deterministic rule has risk 0.50.5, but ERM selects favorable fluctuations. The estimated log-log slope from one run is descriptive, not a universal theorem for every distribution.

[ ]Mean optimism versus sample sizeBrowser
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 Φ(−1)\Phi(-1) 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 NN test observations is R∗(1−R∗)/N\sqrt{R^*(1-R^*)/N}; with N=20000N=20000 it is approximately 0.00260.0026. 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.

[ ]Bayes error and discriminant probesBrowser
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

Numeric
For equally likely classes N(-1,1) and N(1,1), calculate the Bayes error.
Quiz
If the best fixed rule h° in H exists and h-hat exactly minimizes empirical error, which inequality chain holds in expectation?
Quiz
If η(x)=1/2 on a region of positive probability, what happens when predictions change only there?
Proof
Prove: The conditional mean minimizes squared risk.
0
Assume finite second moments and write Y as its conditional mean plus a residual.

Step 1 of 2. What happens to the cross term when conditioning on X?

Proof
Prove: The 0-1 excess is the expected disagreement weighted by |2η-1|.
0
Condition on X=x and compare the costs of predicting 0 and 1.

Step 1 of 2. What is the cost of predicting 0?

CodeThresholds with ties
Implement erm_thresholds(x, y), returning (t, right), where right=True predicts 1 if x ≥ t and right=False predicts 1 if x < t. Minimize errors over threshold rules in both orientations in O(n log n), grouping equal values. x is nonempty and contains finite real values.
def erm_thresholds(x, y):
  pass
Shift+Enter to run

Summary

Key idea
Risk is an expectation under the distribution; excess risk compares with Bayes; the gap compares population and sample for a rule. ERM selects by looking at the sample, and its training error is optimistic in expectation, although not necessarily in every realization.