Empirical risk: winning on the sample is not winning in the population
经验风险最小化
Compute finite-class ERM exactly, preserve ties, and derive a uniform-convergence excess-risk bound with its assumptions.
empirical-riskThe optimizer can be right about the sample and wrong about the world
Imagine a deliberately small classification task with three input bins: low, middle and high, encoded as 0, 1 and 2. Before seeing any observations, we allow four prediction rules. Each rule returns a binary label; the label has no additional physical meaning in this synthetic example.
| Rule | Low | Middle | High |
|---|---|---|---|
| none | 0 | 0 | 0 |
| high-only | 0 | 0 | 1 |
| from-middle | 0 | 1 | 1 |
| all | 1 | 1 | 1 |
The observed sample is (low,0), (low,0), (low,0), (high,0). The rule none makes no mistakes. Every other allowed rule makes at least one. An exact optimizer should therefore select none.
For this teaching example, we also know the population: low with label 0 has probability 1/2, middle with label 1 has probability 1/3, and high with label 0 has probability 1/6. The selected rule then has population error 1/3. from-middle has error 1/6. The optimizer did its assigned job correctly, but the sample omitted the middle bin.
Empirical risk minimization, or ERM, names that assigned job: choose a predictor with the lowest average loss on the observed sample. It does not mean that the population loss has been directly minimized. Shalev-Shwartz and Ben-David introduce this distinction before restricting the learner to a hypothesis class. Understanding Machine Learning, §§2.2–2.3.
Two risks and a set of minimizers
Let follow a population distribution . Fix a loss function . For this chapter’s binary classifiers, the loss is 1 for a wrong prediction and 0 otherwise. Given a sample sequence with , define:
Population risk is an expectation over new draws from . Empirical risk is an observed average. Repeated examples count as repeated observations; turning the sample into a set would change the objective. The arithmetic average can be computed without an IID assumption. IID becomes important when relating that average to the population.
Let be a finite, nonempty set of predictors fixed before inspecting this sample. ERM is a selection from the set of empirical minimizers:
The first minimization is computable from observations. The second is a benchmark, usually unavailable because is unknown. Ties are possible: with only (low,0), the first three rules all have empirical risk zero. They need not have equal population risk. A deterministic implementation can choose the first listed minimizer while returning every tie. The textbook explicitly treats argmin as a set, rather than assuming uniqueness. §2.3.
Why a guarantee must cover the whole class
Assume the sample consists of independent draws from the same used for evaluation; and the loss were fixed beforehand. Here the loss is bounded in [0,1] because it is binary. For one fixed , its losses are IID Bernoulli variables with mean . Hoeffding’s inequality bounds its empirical deviation. The union bound then covers all candidates:
The events for different hypotheses can be dependent; the union bound does not require independence between them. Its justification is that the indicator of a union is at most the sum of the event indicators. Independence is instead used for the observations in the fixed-hypothesis concentration bound.
Why not apply the fixed-hypothesis bound directly to the winner? The winner was chosen using this very sample. Uniform convergence handles that dependence by making the deviation statement true for every candidate simultaneously. For a chosen confidence parameter , set:
The logarithm is natural. Probability here is over repeated IID training samples, not a posterior probability assigned to a particular trained model. This is the finite-class argument in Stanford’s learning-theory notes. CS229, §§2–3, PDF pages 3–7.
Optimization error enters at a different step
Suppose a procedure returns whose empirical risk is at most above the empirical minimum. On the uniform-convergence event:
The first and last steps use uniform convergence; the middle step uses the optimizer’s guarantee. Exact ERM has , giving excess population risk at most relative to the best member of . The conclusion holds for any empirical tie. It does not require that some member of predicts perfectly.
In our example, optimization error is zero, the selected model’s population-minus-empirical gap is 1/3, and its population excess over the best member of is 1/6. These are different quantities. The best member itself has risk 1/6, while the excluded rule (0,1,0) would have risk zero. That remaining limitation belongs to the chosen class, not the search procedure.
Enumerate a fixed class and keep ties exact
The complete standard-library program uses one prediction vector per hypothesis. Vector position is the input index. The class must be nonempty, all vectors must have the same positive length, and names and prediction functions must be distinct. Input containers are lists or tuples; predictions and labels are integer 0 or 1, with Booleans rejected.
erm accepts only hypotheses and observations. It returns each empirical risk, the minimum, all minimizers in input order, and the first chosen one. Fraction keeps comparisons and ties exact. An empty sample is rejected because the average would be undefined.
population_risks is a separate teaching audit. A distribution row is (input_index, label, numerator, denominator). Nonnegative rational masses must sum exactly to one. Repeated rows contribute additional mass; zero-mass rows are permitted but still validated. This routine does not estimate an unknown distribution. We supply the population solely to inspect what the learner cannot normally see.
from fractions import Fraction
from math import log, sqrt
def sequence(value):
if type(value) not in (list, tuple):
raise ValueError('Expected a list or tuple')
return tuple(value)
def binary(value):
if type(value) is not int or value not in (0, 1):
raise ValueError('Labels and predictions must be integer 0 or 1')
return value
def hypotheses(raw):
table, names, functions = [], set(), set()
width = None
for row in sequence(raw):
row = sequence(row)
if len(row) != 2:
raise ValueError('Hypothesis: (name, predictions)')
name, predictions = row[0], tuple(binary(y) for y in sequence(row[1]))
if type(name) is not str or not name or name in names:
raise ValueError('Hypothesis names must be unique nonempty strings')
if not predictions or (width is not None and len(predictions) != width):
raise ValueError('Prediction vectors must have the same positive length')
if predictions in functions:
raise ValueError('Repeated hypothesis functions are not distinct members of H')
width = len(predictions)
names.add(name)
functions.add(predictions)
table.append((name, predictions))
if not table:
raise ValueError('H must be nonempty')
return width, tuple(table)
def example(row, width):
row = sequence(row)
if len(row) != 2 or type(row[0]) is not int or not 0 <= row[0] < width:
raise ValueError('Example: (declared input index, binary label)')
return row[0], binary(row[1])
def erm(raw_hypotheses, raw_sample):
width, table = hypotheses(raw_hypotheses)
sample = tuple(example(row, width) for row in sequence(raw_sample))
if not sample:
raise ValueError('The training sample must be nonempty')
risks = tuple((name, Fraction(sum(pred[x] != y for x, y in sample), len(sample)))
for name, pred in table)
minimum = min(risk for _, risk in risks)
minimizers = tuple(name for name, risk in risks if risk == minimum)
return {'risks': risks, 'minimum': minimum,
'minimizers': minimizers, 'chosen': minimizers[0]}
def population_risks(raw_hypotheses, raw_distribution):
# A separate teaching audit: erm never receives the population distribution.
width, table = hypotheses(raw_hypotheses)
distribution = []
for row in sequence(raw_distribution):
row = sequence(row)
if len(row) != 4:
raise ValueError('Distribution row: (input, label, numerator, denominator)')
x, y = example(row[:2], width)
numerator, denominator = row[2:]
if (type(numerator) is not int or type(denominator) is not int
or numerator < 0 or denominator <= 0):
raise ValueError('Probability needs nonnegative numerator and positive denominator')
distribution.append((x, y, Fraction(numerator, denominator)))
if sum((p for _, _, p in distribution), Fraction()) != 1:
raise ValueError('Probability masses must sum exactly to one')
return tuple((name, sum((p for x, y, p in distribution if pred[x] != y), Fraction()))
for name, pred in table)
H = (('none', (0, 0, 0)), ('high-only', (0, 0, 1)),
('from-middle', (0, 1, 1)), ('all', (1, 1, 1)))
POPULATION = ((0, 0, 1, 2), (1, 1, 1, 3), (2, 0, 1, 6))
SAMPLE = ((0, 0), (0, 0), (0, 0), (2, 0))
if __name__ == '__main__':
result = erm(H, SAMPLE)
print('empirical:', tuple((name, str(risk)) for name, risk in result['risks']))
print('chosen:', result['chosen'])
print('population:', tuple((name, str(risk)) for name, risk in population_risks(H, POPULATION)))
print('one-point ties:', erm(H, ((0, 0),))['minimizers'])
epsilon = sqrt(log(2 * len(H) / 0.05) / (2 * len(SAMPLE)))
print('epsilon, 2 epsilon:', round(epsilon, 6), round(2 * epsilon, 6))
Actual output:
empirical: (('none', '0'), ('high-only', '1/4'), ('from-middle', '1/4'), ('all', '1'))
chosen: none
population: (('none', '1/3'), ('high-only', '1/2'), ('from-middle', '1/6'), ('all', '2/3'))
one-point ties: ('none', 'high-only', 'from-middle')
epsilon, 2 epsilon: 0.79649 1.592981
The four-point sample is hand selected for illustration, not reported as a random experiment. Its exact ordered sequence has probability 1/48 under the stated IID population, so it is a possible draw. Nothing about the ERM code checks how observations were collected or when the candidate class was chosen; those are conditions on the experiment.
With four hypotheses, four observations and , the bound gives , so . A zero-one excess risk cannot exceed one. This bound is therefore uninformative for the tiny sample; reporting it as a useful 95% accuracy guarantee would be misleading. It bounds excess over the best candidate, not absolute classification accuracy.
The tests enumerate all 81 ordered length-four samples drawn from the three support points, with their exact probabilities. At this epsilon, the probability that at least one candidate violates the uniform deviation bound is 1/1296, below 0.05. That is a calculation for this particular finite population, not a proof that every population has that failure probability. The inequality above supplies the distribution-free argument under its assumptions.
The implementation validates the stored class and scans every sample for every hypothesis. If each vector has entries, is the class size, the sample length and the number of supplied population rows, the arithmetic-operation bounds are:
All four sizes are positive for valid inputs. These bounds include copied/normalized inputs and returned risk tables, assume expected hashing and unit-cost keys, and count rational arithmetic as operations. Actual bit cost grows with integer sizes and probability denominators; exact fractions are not constant-time operations on arbitrarily large numbers. Exhaustive enumeration is appropriate for this small explicit class, not a general solver for large or continuously parameterized models.
A statistical claim has conditions that a loss value cannot check
Choosing after examining the same labels does not justify substituting only the final class size into this fixed-class bound. For example, a procedure could inspect many alternatives and retain only its chosen classifier; declaring that singleton in advance would be a false description of the experiment. A valid analysis might cover a prespecified larger class or use separate data for selection and evaluation, but it needs to account for the selection procedure.
Likewise, duplicating a sample does not create independent evidence. Copy one Bernoulli label 100 times: its empirical frequency is still either zero or one. When the true frequency is 1/2, the deviation is 1/2 with probability one. Plugging 100 into an IID concentration bound would produce a false conclusion. The ERM routine correctly counts all rows in its input; it cannot certify their independence.
The training and evaluation distributions must also match for the stated . A changed population, correlated observations or altered label process needs a different argument. The displayed proof uses zero-one loss; it cannot be transferred unchanged to unbounded squared error or log loss. A different bounded range changes the concentration scale, and unbounded losses require additional assumptions.
ERM is an objective-based learning rule, not the name of one optimization method. Gradient descent, dynamic programming or exhaustive search may solve different ERM instances, sometimes only approximately. Regularized objectives add another term and are not identical to minimizing the raw empirical average. Reducing optimization error alone does not repair a poor class, a biased sample or a mismatched loss.
Name the quantity before improving it
- In the four-point example, give the selected model’s empirical risk, population risk, optimization error and excess population risk relative to .
Answer: none has empirical risk 0 and population risk 1/3. Its optimization error is 0 because it is an exact empirical minimizer. The best population risk in is 1/6, so its excess is 1/6. Neither the generalization gap 1/3 nor the excess 1/6 is an optimizer failure.
- With only
(low,0), reverse the hypothesis list. What changes, and what remains true?
Answer: The empirical minimum stays 0 and the same three functions remain tied. The first selected tied rule changes from none to from-middle, whose population risk is 1/6 rather than 1/3. Both outputs satisfy ERM. Input-order tie breaking does not identify which tied rule generalizes best.
- For and , how many IID observations suffice for this bound to give ERM excess at most 0.2? Does that guarantee population risk at most 0.2?
Answer: Require , giving ; rounding up yields 254. This is a sufficient worst-case bound, not a necessary sample count. It guarantees at most with probability at least 0.95 under the assumptions. It gives absolute risk at most 0.2 only if the best class member has zero risk.
- A solver returns a candidate with empirical loss 0.03 above the minimum. On an event where every candidate’s empirical risk differs from its population risk by at most 0.04, what excess-risk bound follows? Would copying the training rows justify reducing the 0.04?
Answer: The bound is above the best population risk in . The 0.03 is optimization error; the two 0.04 terms bridge sample and population comparisons. Copying rows does not create IID draws and therefore does not justify a smaller statistical deviation bound.
Read the assumptions beside the minimization rule
The authors’ 2014 online copy of Understanding Machine Learning: From Theory to Algorithms presents empirical error in §2.2, set-valued ERM and a class chosen before data in §2.3, and explicitly states the IID assumption in §2.3.1. That chapter’s finite-class result also assumes realizability; the agnostic excess-risk argument used here comes from the separate uniform-convergence reasoning. The online copy warns that its page numbers differ from the printed book, so section numbers are the stable locators. The book is linked, not redistributed. Author’s book page.
Andrew Ng’s archived CS229 Learning Theory notes derive the finite-class bound from Hoeffding and the union bound, then compare ERM with the best population-risk member of the class. The file calls itself Part VI despite its notes4 filename; no publication year is inferred from that filename. Notes, §§2–3.
The original code and tests use the three-bin example above. Nine tests include a histogram/bit-vector reference over 81 population sample histories and 36 possibly noisy two-observation samples, exact tie handling, probability-mass checks and the approximate-optimizer inequality. This is an AI technical check of the implementation; the theorem’s proof and assumptions supply its broader mathematical scope.
Continue with generalization, PAC learning and regularization for questions that go beyond this finite-class demonstration.
Make a prediction, then check
ERM attains zero sample error, but another allowed classifier has lower population risk. Has the empirical optimizer necessarily failed?
Learning objectives
- Compute sample risk and population risk separately, including every empirical tie.
- Derive the finite-class uniform-convergence bound with IID, preselected H and bounded binary loss stated explicitly.
- Separate optimization error, a generalization gap and population excess over the best class member.
Prerequisites & connections
Explore related knowledge →References
- Understanding Machine Learning: From Theory to Algorithms — author online copy
Shai Shalev-Shwartz; Shai Ben-David · 2014 - CS229 Lecture Notes — Part VI: Learning Theory
Andrew Ng
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.
- Nine tests passed. Independent histogram/bit-vector loss calculations check all 81 ordered length-four population histories and all 36 possibly noisy two-example samples against eight binary functions. Exact ties, repeated samples, invalid inputs, probability normalization and unchanged inputs are covered.
- Computed main empirical risks 0,1/4,1/4,1 and population risks 1/3,1/2,1/6,2/3. Exact sample-history masses sum to one; uniform-bound failure probability is 1/1296 for this fixture. Checked the deterministic 2-gap-plus-eta inequality for every candidate on all 81 histories and the sufficient sample count 254 for excess 0.2 at delta 0.05.
- Complete bilingual original prose/code, six matching displays, six anchors and four answered exercises. Strict MDX/KaTeX and actual React HTML passed. The finite-class probability theorem is separated from the toy arithmetic and from data-collection assumptions. AI author check only, review written pending independent review.
- Complete bilingual prose, code, metadata and nine author tests reviewed; all nine tests passed. Fixed nonempty H, exact rational risks, input-order ties, repeated observations, separately supplied population audit and full validation agree with the stated interface. No production-scale or empirical collection guarantee is implied.
- Independent sparse multivariate probability-generating polynomials convolve IID loss vectors, using the binary squared-residual identity rather than the author histogram/bit-vector reference or exhaustive ordered histories. Twelve small class/distribution/length cases produce 110 joint error states with 369 convolution products; all 110 complete ERM returns and 426 candidate excess inequalities pass. Main failure mass is exactly 1/1296. Single-function/noisy samples and two invalid zero-mass rows add three boundary checks; actual stdout matches the article.
- Reviewed the general proof independently: preselected H and loss, IID sampling from the evaluation population, union bound not needing independent candidate events, simultaneous validity for a data-selected minimizer and any tie, and 2-epsilon-plus-eta excess over the best class member without realizability. Checked the 254 sufficient count and the vacuous tiny-sample radius. Input-copying is not new evidence. Rational-operation bounds explicitly exclude arbitrary-precision bit costs.
- Final five hashes match. Strict MDX/KaTeX and actual React HTML pass with six displays, six anchors and four answers per locale; the 46 mathematical annotations have identical multisets (prose order differs). Checked the full deviation, excess-risk and cost formulas. No author or repository file changed. This review excludes browser/full-site publication checks.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points existing topics to their complete articles, retaining pending directory entries. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- Understanding Machine Learning: From Theory to Algorithms — author online copy · Actually opened the author-hosted understanding-machine-learning-theory-algorithms.pdf through web. Header confirms 2014 publication, requests linking rather than redistribution, and warns that online page numbers differ from print. PDF page 35 (§2.2) defines sample error and ERM; pages 36–37 (§2.3) require H chosen before data and define argmin as the set of minimizers; page 38 (§2.3.1) states realizability and IID separately. Do not claim that chapter’s realizable finite-class result proves the agnostic example here. No paper/book content copied into distributed assets.
- CS229 Lecture Notes — Part VI: Learning Theory · Actually read official PDF pages 3–7, sections 2–3: union bound and Bernoulli Hoeffding; IID joint (x,y) distribution and matching evaluation population; fixed-hypothesis deviation, union over finite H, solved confidence radius and the three-step 2-epsilon ERM comparison. Header on page 1 identifies Andrew Ng and Part VI. The source’s casual description of the union bound as an axiom is not adopted; the article gives its indicator-inequality justification. The approximate-optimization eta extension is derived explicitly in the article.
- Understanding Machine Learning: From Theory to Algorithms — author online copy · Direct official author-page open returned empty text and two full-PDF opens returned Internal Error. Independently read search-extracted content from that same official PDF URL, not third-party summaries: the cover identifies the authors, 2014 publication and different online pagination; section 2.3 online p37 defines set-valued argmin and prior selection of H; p38 Definition 2.1 and the IID paragraph separately state realizability and independent sampling. This confirms the key boundary. I did not independently open the whole 449-page PDF, visually audit pages or read section 2.2 in full; the author separately reports those reads.
- CS229 Lecture Notes — Part VI: Learning Theory · Independently opened the official 11-page PDF through web. Header identifies Andrew Ng and Part VI, without a publication date. Read PDF pp3–7, extracted lines 107–337: union bound without independence across hypothesis events; Bernoulli Hoeffding; IID joint sampling and matching evaluation distribution; fixed-hypothesis concentration; union over finite H; solved radius and comparison to the best member of H. The agnostic 2-epsilon argument matches the article. The eta term is a valid explicitly derived extension, not attributed as a quotation.
Related topics