Generalization: specify which new examples matter
泛化
Separate training scores, fresh-sample risk and group-mixture shift with exact finite-distribution calculations.
generalizationA high average can conceal where the mistakes happen
Imagine a fictional character reader with one crude feature: a mark is classified as left or right. Its fixed rule predicts label 0 for left and label 1 for right. Characters come in two styles. We assign their probabilities by hand so every calculation can be checked exactly:
| Style group | Share under P | Error within the group | Accuracy within the group |
|---|---|---|---|
| plain | 95% | 2% | 98% |
| ornate | 5% | 40% | 60% |
The overall error is 3.9%, so accuracy is 96.1%. That average is correct. It simply answers a different question from “how well does the reader handle ornate characters?” If future inputs contain equal numbers of both styles, error becomes 21%, even though the rule and both conditional group errors remain unchanged.
This chapter separates three questions: performance on the examples used to fit or choose a model, risk on fresh examples from the same distribution, and risk when that distribution changes. A single test score cannot answer all three. The table is a probability model, not a measurement of a real character-recognition system.
State which population the risk describes
For a binary predictor , use zero-one loss: one for a wrong label and zero otherwise. Let describe the joint distribution of group, feature and label. Population risk is an expectation; empirical risk is an average over a particular nonempty sample:
In learning, the fitted predictor depends on its training sample. Its training error and population risk need not agree. The difference is a generalization gap; some authors report its absolute value or average it over training samples, so the convention matters. A small gap alone is also insufficient: a model can perform equally badly on training and new data.
In practice, the full population distribution is usually unknown. An independent holdout provides an estimate. Once a predictor is fixed, let contain independent observations from , with independent of the fitted predictor. Then:
Each error indicator is Bernoulli with that risk; independence makes variances add. This statement concerns repeated possible test samples, not certainty about one observed score. Selecting the model or its settings using that same test set breaks the independence premise. The textbook’s holdout discussion makes the role of fresh examples explicit. Shalev-Shwartz and Ben-David, §11.2.1.
Training, validation for choosing settings, and final testing therefore have distinct roles. Merely placing observations in different rows does not establish independence: multiple versions of one original document can appear on both sides of a split. The appropriate sampling unit depends on what “new” will mean at deployment. This is a statement about the evaluation design, not a property a model can infer from the file names.
Now suppose groups form a partition: each example belongs to exactly one group. For a group with positive probability, define as its conditional error and . The law of total expectation gives:
The sums and maxima here range over groups with positive source mass; a zero-mass source group needs additional information before receiving target weight. The average weights groups by how common they are. It does not give every group equal influence. Overlapping audit categories cannot be inserted into this partition formula without adjusting the representation. A group absent from a finite sample has no sample error estimate; its error is not zero.
Under group-mixture shift, the conditional distribution of features and labels within each group stays fixed, while group weights become . For the same predictor:
Any weighted average is at most the largest group error, and assigning all weight to a maximizing group attains it. This worst-case claim covers mixtures of the specified, known conditional distributions only. It does not cover a new group or changed behavior within a group. Sagawa and colleagues use this group-mixture uncertainty set when defining group DRO; a small worst-group training loss still need not imply a small worst-group population loss. Original paper, §2.
Group-mixture shift is a particular distribution change. It need not leave unchanged when the predictor does not observe the group. New label rules, measurement failures or new feature values may require a different target distribution altogether. Reweighting old group errors cannot repair an assumption that the conditional errors themselves remain valid.
Compute the population, then audit a sample
The program accepts a finite table of (group, feature, label, probability) cells. Probabilities are exact Fraction values or integers, must be nonnegative, and must sum to one. Repeated cells have their probability masses combined. Labels are integer 0 or 1; booleans and float probabilities are rejected. The prediction dictionary contains exactly one fixed label for each declared feature. Group membership is used for auditing, not as an input to this prediction rule.
The optional sample is an ordered list or tuple of observed cells without probabilities. Repeated observations count repeatedly. Each event must lie in the table’s positive support. Passing that check does not prove it was sampled independently or without selection. The program trains no model and offers no confidence interval. Its gap field is population risk minus this supplied sample’s error; interpreting the sample as training data requires information about how the predictor was obtained.
remix changes group weights and retains each existing conditional distribution. It rejects a positive target weight for a source group of zero mass: those rows do not identify a conditional distribution to transport. Zero-mass group risk and empty-sample error are returned as None, not a fabricated zero. The reported worst group considers groups with defined positive-mass conditional risks.
# Python 3.10+; a known finite distribution and a fixed binary predictor.
from collections import Counter
from fractions import Fraction as F
def name(value):
if type(value) is not str or not value:
raise ValueError('group and feature names must be nonempty strings')
return value
def label(value):
if type(value) is not int or value not in (0, 1):
raise ValueError('labels must be integer 0 or 1, not booleans')
return value
def probability(value):
if type(value) not in (int, F) or value < 0:
raise ValueError('use a nonnegative exact Fraction or integer')
return F(value)
def distribution(rows):
if type(rows) not in (list, tuple):
raise ValueError('distribution must be a list or tuple')
cells = {}
for row in rows:
if type(row) is not tuple or len(row) != 4:
raise ValueError('cell: (group, feature, label, probability)')
g, x, y = name(row[0]), name(row[1]), label(row[2])
key = (g, x, y)
cells[key] = cells.get(key, F(0)) + probability(row[3])
if sum(cells.values(), F(0)) != 1:
raise ValueError('probabilities must sum exactly to one')
return tuple((*key, mass) for key, mass in sorted(cells.items()))
def assess(rows, predictions, sample=()):
table = distribution(rows)
features = {x for _, x, _, _ in table}
if type(predictions) is not dict or set(predictions) != features:
raise ValueError('supply exactly one prediction for every declared feature')
predictions = {name(x): label(y) for x, y in predictions.items()}
mass, wrong = {}, {}
support = set()
for g, x, y, weight in table:
mass[g] = mass.get(g, F(0)) + weight
wrong[g] = wrong.get(g, F(0)) + weight * (predictions[x] != y)
if weight > 0:
support.add((g, x, y))
if type(sample) not in (list, tuple):
raise ValueError('sample must be a list or tuple')
counts, errors = Counter(), Counter()
for row in sample:
if type(row) is not tuple or len(row) != 3:
raise ValueError('sample row: (group, feature, label)')
g, x, y = name(row[0]), name(row[1]), label(row[2])
if (g, x, y) not in support:
raise ValueError('sample event is outside the positive support')
counts[g] += 1
errors[g] += predictions[x] != y
risk = sum(wrong.values(), F(0))
empirical = F(sum(errors.values()), len(sample)) if sample else None
groups = {g: dict(mass=mass[g], risk=wrong[g] / mass[g] if mass[g] else None,
count=counts[g], empirical_risk=F(errors[g], counts[g])
if counts[g] else None) for g in sorted(mass)}
return dict(risk=risk, worst_group_risk=max(
v['risk'] for v in groups.values() if v['risk'] is not None),
sample_size=len(sample), empirical_risk=empirical,
gap=None if empirical is None else risk - empirical, groups=groups)
def remix(rows, weights):
table = distribution(rows)
mass = {}
for g, _, _, value in table:
mass[g] = mass.get(g, F(0)) + value
if type(weights) is not dict or set(weights) != set(mass):
raise ValueError('supply exactly the declared groups')
weights = {g: probability(value) for g, value in weights.items()}
if sum(weights.values(), F(0)) != 1:
raise ValueError('new group weights must sum to one')
if any(weights[g] > 0 and mass[g] == 0 for g in mass):
raise ValueError('cannot infer a conditional distribution from zero mass')
return tuple((g, x, y, value * weights[g] / mass[g] if mass[g] else F(0))
for g, x, y, value in table)
def font_example():
rows = []
for g, mass, error in [('plain', F(19, 20), F(1, 50)),
('ornate', F(1, 20), F(2, 5))]:
for x, predicted in [('left', 0), ('right', 1)]:
for y in (0, 1):
rows.append((g, x, y, mass * (error if predicted != y else 1-error) / 2))
return tuple(rows), {'left': 0, 'right': 1}
if __name__ == '__main__':
P, h = font_example()
# Constructed sample for inspection; not claimed to be a random draw.
sample = (('plain', 'left', 0), ('plain', 'right', 1)) * 10
report = assess(P, h, sample)
Q = remix(P, {'plain': F(1, 2), 'ornate': F(1, 2)})
print('P error:', report['risk'])
print('group errors:', tuple((g, v['risk']) for g, v in report['groups'].items()))
print('sample error:', report['empirical_risk'])
print('ornate sample count/error:', report['groups']['ornate']['count'],
report['groups']['ornate']['empirical_risk'])
print('population minus sample:', report['gap'])
print('Q error:', assess(Q, h)['risk'])
print('worst group:', report['worst_group_risk'])
print('IID chance of no ornate examples in 20:', round(float(F(19, 20)**20), 6))
The complete program prints:
P error: 39/1000
group errors: (('ornate', Fraction(2, 5)), ('plain', Fraction(1, 50)))
sample error: 0
ornate sample count/error: 0 None
population minus sample: 39/1000
Q error: 21/100
worst group: 2/5
IID chance of no ornate examples in 20: 0.358486
The displayed sample was constructed to contain 20 correctly predicted plain characters. Its zero sample error does not erase the ornate group’s 40% population error. The ornate sample count is zero, so its sample risk is None. An independently drawn size-20 sample from has probability of containing no ornate examples at all. That is the probability of absence, not the probability that all predictions are correct. The constructed sample is not represented as a random draw.
The positive sample gap of 3.9 percentage points does not diagnose overfitting here: the predictor was fixed and no training procedure ran. The equal-weight target has risk , or 79% accuracy. Its error increase of 17.1 percentage points is entirely attributable to group weights in this example.
The assigned feature is imperfect in both groups. In fact, the rule selects the more likely label within each feature/group pair here. A high group error does not, by itself, show that another classifier using the same limited information can remove those errors. Better information and a different model are separate questions from correct evaluation.
For supplied distribution rows and sample observations, assessment uses dictionary/comparison steps and rational arithmetic operations, and auxiliary records. The sample is counted without retaining its history. Reweighting has the same sorting order without the sample term. These bounds assume ordinary expected hash-table behavior and count rational operations, not bit operations: large denominators and long names add costs. The illustrative decimal probability is rounded only for printing; risk calculations remain exact.
The independent tests expand small rational distributions into equiprobable tickets and count mistakes, rather than reuse weighted probability sums. They check complete reports, changed mixtures, absent groups and malformed inputs. This exhaustive reference is intentionally confined to tiny distributions.
A group table cannot stand in for the whole deployment
A high overall score can coexist with a poor group score. A high worst-group score across the groups you chose can still conceal a subgroup you did not define. The partition and the loss measure must match the question being asked; they are part of the specification.
If an audit deliberately samples equal numbers from each group, its unweighted mean estimates that sampling mixture. Estimating a different population average requires the intended group weights and suitable conditional estimates. Oversampling a small group can provide more information about it, but does not turn those extra observations into its real population frequency.
Sampling uncertainty and distribution shift are different. A larger independent test set can sharpen an estimate under its sampling distribution; it cannot establish that next year’s distribution will be the same. Reusing a test set for repeated decisions can also make its final score less informative about a fresh population. Report the sampling unit, target distribution, group counts, prediction rule and decision history alongside the score.
Our finite table supplies the true probabilities by construction. Real applications rarely provide that convenience, and membership in the observed support is not a proof of representativeness. The code neither detects all shifts nor learns a robust predictor. See empirical risk minimization for the training objective and cross-validation for repeated data splitting.
Change the question before changing the number
Exercise 1: calculate both population errors
Answer: Under , error is . Under equal group weights it is . Accuracy is one minus error, giving 96.1% and 79%. No parameter of the predictor changed.
Exercise 2: no ornate examples means what?
Answer: There is no sample estimate of ornate error. Return None with a count of zero; do not report 0% error or 100% accuracy. Under an independent size-20 sample from , absence has probability , about 35.8%. A deliberately plain-only sample does not have that random-sampling interpretation.
Exercise 3: can reweighting predict every future risk?
Answer: No. It works here only because each group’s conditional distribution stays fixed. If ornate error rises from 40% to 80% while its share remains 5%, total error becomes . Reusing the old conditional error would still give 0.039 and be wrong.
Exercise 4: what does the worst-group bound cover?
Answer: Any mixture of the two stated conditional distributions has error at most 40%; placing all mass on ornate attains that value. This is not a bound on a new third style or altered within-style data. Nor does replacing population group errors with noisy training estimates preserve the population guarantee automatically.
Population risk is the target; datasets provide evidence
Shalev-Shwartz and Ben-David, Understanding Machine Learning: From Theory to Algorithms (2014), author’s book page, §11.2.1, explains estimating risk with examples independent of training. The finite-hypothesis concentration proof belongs to the separate empirical-risk chapter; this article uses elementary conditional expectations and group decomposition.
Sagawa, Koh, Hashimoto and Liang, Distributionally Robust Neural Networks for Group Shifts, ICLR 2020 paper, arXiv version 2, distinguishes population group risk from the corresponding training objective. Its empirical findings depend on its datasets, models and regularization conditions. The font probabilities, fixed predictor, program and exercises here are original and do not reproduce those neural-network experiments.
Make a prediction, then check
Plain-group error is 2% and ornate-group error is 40%. Ornate prevalence rises from 5% to 50%, with unchanged group conditionals and predictor. What is the new error?
Learning objectives
- Distinguish training error, same-distribution population risk and one test estimate, including independence and the sampling unit.
- Decompose population and group risks exactly and explain why an absent group cannot be assigned zero empirical error.
- Compute reweighted risk under fixed group conditionals and identify new groups or within-group changes outside that guarantee.
Prerequisites & connections
Explore related knowledge →References
- Understanding Machine Learning: From Theory to Algorithms — author online copy
Shai Shalev-Shwartz; Shai Ben-David · 2014 - Distributionally Robust Neural Networks for Group Shifts: On the Importance of Regularization for Worst-Case Generalization
Shiori Sagawa; Pang Wei Koh; Tatsunori B. Hashimoto; Percy Liang · 2020
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.
- All eight standard-library tests passed. An independent equiprobable-ticket reference checked 43 complete reports over 14,880 tickets, including four binary rules and five group mixtures, without reusing production weighted sums. Exact results include P risk 39/1000, equal-weight Q risk 21/100, worst group 2/5 and changed-conditional risk 59/1000.
- Checked undefined zero-mass conditional risks, refusal to recover an unknown conditional, None for empty or missing-group sample estimates, repeated observations, negative sample gaps, merged duplicate cells, input preservation and 21 invalid inputs. All eight stdout lines match. The 35.8% figure is absence of ornate examples under IID sampling, not zero prediction errors.
- Reviewed the independent-test mean/variance and conditional-risk decomposition. Worst-mixture risk covers only fixed known conditionals of positive-mass groups. The constructed sample is not a random draw, the program trains no model, and true probabilities are known only by construction; one score is not treated as proof of generalization.
- Both languages have six anchors, four identical display equations, identical complete code/output and four answered exercises. Strict MDX/KaTeX/React HTML and MathML correspondence pass. Tests obtain code and output through article_text, requiring only its path to change for publication. Targeted Humanizer scanning and paragraph-level AI rereading completed; remains written. No whole-site build, browser acceptance, human review or real OCR experiment.
- Complete bilingual prose, program, eight author tests and metadata reviewed. All eight tests passed. Fixed predictor rather than training, population-versus-sample gap, missing-group None, zero-mass conditionals, positive-support validation and restricted group-mixture shift are accurately distinguished.
- Independent binary-loss moment calculations and error-count probability-generating polynomials avoid author equiprobable tickets. Three target mixtures and four predictors give 36 population/group-risk checks and 36 exact IID holdout mean/variance checks. Twelve label-complement transformations preserve full reports; identical-conditional group splitting and zero-mass-only feature validation add three edges. All pass.
- Reviewed the general expectation/variance argument, group partition requirement and simplex worst-risk proof. Same-conditional reweighting is not unrestricted distribution shift, and sample support membership is not IID certification. The constructed gap does not demonstrate overfitting without a learning procedure. P risk 39/1000, equal-mixture risk 21/100 and absent-ornate probability (19/20)^20 have the stated distinct meanings.
- Final five hashes match. Strict MDX/KaTeX and actual React HTML passed with four matching displays, six anchors and four answers per locale; complete code/output are aligned. Costs account for canonicalization sorting and streamed sample counters under the explicitly stated hash/bit-cost assumptions. No original or repository file edited, and no browser/full-site or real OCR audit claimed.
- 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 read the full primary-PDF text excerpt returned by targeted web search for §11.2 Validation and §11.2.1 Hold Out Set, printed p. 146: fresh examples drawn from D independently of training, and independence from the way h was generated. Also read the returned §11.3 passage, p. 151, on training, parameter selection and testing. Direct open/find attempts on the PDF failed or returned no usable text, so no full PDF or visual inspection is claimed. The article does not reproduce the excerpt’s Hoeffding theorem; its Bernoulli expectation/variance calculation is derived separately. The book card is shared with the independently sourced empirical-risk chapter.
- Distributionally Robust Neural Networks for Group Shifts: On the Importance of Regularization for Worst-Case Generalization · Actually opened and read arXiv:1911.08731v2: cover/abstract and introduction, web lines 0–110; §2, lines 111–161, defines expected population loss, empirical training loss, mixtures of fixed group distributions, maximum conditional risk, and the distinction between worst-group empirical and population risks. The header gives ICLR 2020, while line 50 records v2 on 2 April 2020. No claim to audit all 19 pages, reproduce reported percentage improvements, or execute group-DRO training.
- Understanding Machine Learning: From Theory to Algorithms — author online copy · Independently read the full targeted-search excerpt of the original author-hosted PDF, online p146, §11.2 and §11.2.1: fresh holdout observations independent of training and of how the predictor was generated. It states the bounded-loss Hoeffding result; the article’s Bernoulli mean/variance is a separate valid derivation. Direct PDF reads failed earlier in the ERM review; no full-PDF or visual inspection claimed.
- Distributionally Robust Neural Networks for Group Shifts: On the Importance of Regularization for Worst-Case Generalization · Independently opened the original 19-page arXiv PDF. Header identifies ICLR 2020 and v2 dated 2 April 2020. Read abstract/introduction for empirical-versus-population worst-group distinction and §2, lines 111–152, for mixtures of fixed conditional distributions, simplex maximization and unobserved group at prediction time. No neural-network experiments, empirical improvement figures or full optimizer audit reproduced.
Related topics