Overfitting: when searching improves the score instead of the prediction
过拟合与欠拟合
Calculate training and validation selection optimism in an exact noise experiment, and distinguish it from sampling variation and underfitting.
overfittingA better score can come from searching harder
A laboratory has no signal to learn: each specimen’s label is an independent fair coin, unrelated to its measurements. A team nevertheless tries many prediction rules and keeps the one with the fewest training mistakes. Another round of selection keeps whichever fitted rule scores best on a small validation set. Both reported scores can look impressive. A genuinely new label is still a coin flip.
Overfitting means adapting to sample-specific detail that does not support the intended prediction task. Training can fit accidental patterns; model selection can fit accidental differences in validation scores. A low training error alone neither establishes useful learning nor proves overfitting. The comparison needs an appropriate target, an evaluation design and some allowance for sampling variation. The official cross-validation guide illustrates why memorizing observed labels can produce a perfect training score without useful prediction. scikit-learn 1.7, introduction.
This chapter makes those mechanisms visible with exact arithmetic. The candidates are deliberately uninformative random prediction sheets, not polynomial curves or neural networks. Two knobs control the experiment: B candidates searched during fitting, and C fitted candidates compared on the same validation set. There is no distribution shift here. The generalization topic examines that broader question; empirical risk defines the sample objective.
Separate ordinary variation from selection
For a fixed predictor, independent binary mistakes with probability r produce an error fraction with expectation r and variance r(1−r)/n. In this experiment r is one-half:
A single fixed predictor can therefore get an unusually good score without any selection. With four observations, it makes no mistakes with probability 1/16. Calling every such event overfitting would confuse ordinary sampling variation with adaptation to a sample.
Selection changes what is reported. Let Vⱼ be an unbiased validation error estimate for candidate j, where the candidate was fixed without that validation data. Even though each score is unbiased, their minimum need not be:
The inequality needs no independence: the minimum is at most every component on every outcome, so take expectations. It can be strict. Identical duplicated candidates give equality, so the number of runs alone does not determine the bias. Cawley and Talbot analyze how variance in a model-selection criterion allows selection to exploit sample peculiarities, and distinguish that process from evaluating the selected procedure. 2010 paper, §§4–4.1.
An exact experiment with independent candidate errors
Imagine each candidate supplies an independent fair guess for each distinct observation. Labels are also independent fair coins. Conditional on any realized labels, the mistake bits are independent fair coins across candidates and observations; their distribution does not depend on those labels. Training, validation and test observations are separate. Each candidate remains fixed when its sheet is scored. Re-evaluating the same candidate does not generate another independent sheet.
The number X of mistakes by one candidate on n observations has distribution:
For M independent candidates, let Z be the smallest mistake count. Having at least k mistakes in the winning sheet requires every candidate to have at least k mistakes:
The expected winning error follows by writing an integer count as the sum of indicators that it exceeds successive thresholds. The chance of a perfect winning score is the complement of every candidate making at least one mistake:
For fixed positive n, more independent candidates reduce the expected winning score, eventually toward zero. That statement concerns this noise experiment. It does not say that adding capacity to a useful learner must worsen prediction, or that candidate count measures neural-network capacity.
Now arrange B candidates in each of C independent groups. Within each group, choose the smallest training error, breaking ties by the first index. Compare those C winners on one shared validation set, again choosing the first minimum. Only then inspect the chosen candidate’s test score. With training, validation and test sizes nₜ, nᵥ and nₑ:
Why does selecting on validation not lower the training expectation again? The within-group training winners have identically distributed training minima. Their validation sheets are independent of those minima, including the tie-breaking decisions. The second-stage index therefore does not preferentially select a smaller training minimum. Its test sheet is independent of both selections. Conditional on either selection history, its test mistake count remains Binomial(nₑ,1/2), with error-fraction variance 1/(4nₑ).
All expectations average over fresh complete experiments. One chosen test sheet can be much better or worse than one-half. This example shows increasingly optimistic training and validation scores while true risk stays constant; it does not manufacture a rising test-error curve or an improvement in generalization.
Compute the distribution and audit the selected sheet
The complete Python 3 program has two parts. minimum_noise computes the exact probability mass of the smallest count using integers and Fraction. expected_errors applies the two-stage assumptions above. It does not infer independence from data or estimate the performance of an arbitrary classifier.
select instead operates on one supplied count table. Each group contains B rows, each row holding (training mistakes, validation mistakes, test mistakes). It returns every training-stage winner, the final pair of indices and the selected error fractions. Its deterministic selection is valid even for correlated tables; the distribution formulas require the stronger independent-noise model. Test counts are validated as input but never used to choose either winner. Changing valid test counts cannot change the chosen indices.
All sizes and candidate counts must be positive integers, with Booleans rejected. Groups must be nonempty and equally sized; each row needs three integer counts within the corresponding sample sizes. Empty sets have no error fraction here and raise ValueError. There is no sampling seed, optimization tolerance or partial-result budget: each successful call completes the stated calculation.
from fractions import Fraction
def positive(value):
if type(value) is not int or value < 1:
raise ValueError('expected a positive integer, not Boolean')
return value
def sequence(value):
if type(value) not in (list, tuple):
raise ValueError('expected list or tuple')
return value
def minimum_noise(n, trials):
"""Exact distribution of the minimum of independent Binomial(n, 1/2) counts."""
n, trials = positive(n), positive(trials)
counts = [1]
for k in range(n):
counts.append(counts[-1] * (n - k) // (k + 1))
tails = [0] * (n + 2)
for k in range(n, -1, -1):
tails[k] = tails[k + 1] + counts[k]
denominator = 1 << (n * trials)
mass = tuple(Fraction(tails[k] ** trials - tails[k + 1] ** trials,
denominator) for k in range(n + 1))
mean = sum((k * p for k, p in enumerate(mass)), Fraction()) / n
return {'mass': mass, 'mean_error': mean}
def expected_errors(train_n, valid_n, test_n, fit_trials, model_trials):
"""Two-stage independent-noise model; not an estimate for arbitrary classifiers."""
train_n, valid_n, test_n = map(positive, (train_n, valid_n, test_n))
train = minimum_noise(train_n, fit_trials)
valid = minimum_noise(valid_n, model_trials)
return {'train': train['mean_error'], 'validation': valid['mean_error'],
'test': Fraction(1, 2), 'perfect_validation': valid['mass'][0],
'test_variance': Fraction(1, 4 * test_n)}
def select(count_groups, sizes):
"""Select by training within groups, then validation across winners; audit test last."""
sizes = tuple(positive(v) for v in sequence(sizes))
if len(sizes) != 3:
raise ValueError('provide train, validation and test sizes')
groups = []
for group in sequence(count_groups):
rows = []
for row in sequence(group):
row = tuple(sequence(row))
if len(row) != 3 or any(type(v) is not int or not 0 <= v <= n
for v, n in zip(row, sizes)):
raise ValueError('each row needs three valid integer error counts')
rows.append(row)
if not rows:
raise ValueError('each group needs a candidate')
groups.append(tuple(rows))
if not groups or any(len(g) != len(groups[0]) for g in groups):
raise ValueError('nonempty equally sized candidate groups required')
winners = tuple(min(range(len(g)), key=lambda j: g[j][0]) for g in groups)
group_id = min(range(len(groups)), key=lambda i: groups[i][winners[i]][1])
candidate_id = winners[group_id]
row = groups[group_id][candidate_id]
return {'within_group': winners, 'selected': (group_id, candidate_id),
'errors': tuple(Fraction(v, n) for v, n in zip(row, sizes))}
if __name__ == '__main__':
print('B C | expected train validation test | P(perfect validation)')
for B, C in ((1, 1), (4, 1), (4, 4), (4, 16)):
result = expected_errors(4, 4, 8, B, C)
values = tuple(round(float(result[k]), 6) for k in ('train', 'validation', 'test'))
print(B, C, values, round(float(result['perfect_validation']), 6))
groups = (((0, 2, 4), (1, 0, 0)), ((0, 0, 4), (1, 1, 0)))
result = select(groups, (2, 2, 4))
print('selected:', result['selected'], 'errors:', tuple(str(x) for x in result['errors']))
print('test variance:', expected_errors(4, 4, 8, 4, 4)['test_variance'])
Actual output:
B C | expected train validation test | P(perfect validation)
1 1 (0.5, 0.5, 0.5) 0.0625
4 1 (0.251358, 0.5, 0.5) 0.0625
4 4 (0.251358, 0.251358, 0.5) 0.227524
4 16 (0.251358, 0.089641, 0.5) 0.643926
selected: (1, 0) errors: ('0', '0', '1')
test variance: 1/32
With B=4 and C=16, average validation error is about 8.96%, and the probability of finding a perfect four-item validation score is about 64.39%. The fresh-test expectation remains 50%. Those percentages are consequences of the invented probability model, not measured performance on laboratory data.
The explicit count table is a possible handpicked outcome. Each group’s second candidate loses on training even if its validation or test count looks attractive. The final winner is group 1, candidate 0: zero training errors, zero validation errors and four out of four test errors. Selecting by the smallest test count would silently change the experiment into another selection stage.
For sample size n and M candidates, minimum_noise builds n+1 binomial counts by an integer recurrence, forms n+2 tails, evaluates 2(n+1) integer powers with exponent M, and reduces n+1 rational probabilities. Integer exponentiation by squaring uses O(log(M+1)) multiplications per power; these are not constant-cost machine operations. Numerators and denominators have O(nM+1) bits, and rational reduction and the final expectation also incur big-integer costs. Retained storage is O(n) integer/rational slots, or O(n²M) bits as a coarse bound. No claim of polynomial cost in the bit-length of M is intended.
For C groups of B three-count rows, select takes O(BC) count operations and O(BC) copied storage, plus exact-rational conversion of the three returned fractions. B and C are positive, so these bounds include constant overhead. It does not enumerate the exponentially many prediction sheets. Larger sizes can still make the exact distribution calculation expensive.
Diagnose the failure before choosing a remedy
Several different situations can produce disappointing evaluation results:
| Observation | What it can mean | A useful next check |
|---|---|---|
| Training error is high and held-out error is high | Inadequate features or model restrictions, incomplete optimization, or an intrinsically noisy task | Check a justified baseline, the optimization objective and whether predictive information is available |
| Training error improves while properly measured held-out performance degrades | Fitting sample-specific patterns is a plausible explanation | Compare training sizes, regularization or stopping choices within the selection protocol |
| One small held-out set gives a surprising score | Ordinary sampling variation may explain it | Report sample size and uncertainty; avoid choosing a favorable repeat |
| The best validation score improves after many trials but a fresh evaluation does not | Selection may be exploiting validation noise | Evaluate the whole selection procedure on untouched outer data |
Underfitting means the fitted procedure fails to capture available predictive structure. High error is not enough to diagnose it. In the fair-label experiment no classifier can exploit the measurements to beat one-half population error, so a 50% predictor is not thereby underfitting. On a separate deterministic XOR task over all four equally likely binary input pairs, a constant predictor has error one-half while the XOR rule has error zero. There, restricting the class to constants demonstrably excludes useful structure. A failed optimizer can also leave a capable class poorly fitted; that is a different cause.
Regularization, fewer candidate choices, better features, more appropriate data and early stopping address different parts of this process. Their settings themselves require selection. Increasing validation size reduces the variance of a fixed predictor’s score, but does not make unlimited reuse free. In this experiment, increasing only the untouched test size narrows its error distribution without changing the expected validation winner.
The program’s candidates have independent errors and equal true risk. Real models often share features, errors and training data; an adaptive search may use validation feedback to construct its next candidate. Neither case generally follows the independent-minimum formula. Re-running an identical deterministic predictor on the same labels gives the same score. Treating those runs as independent candidates exaggerates the effect.
Keep a final test set outside choices of parameters, features, thresholds and stopping points. If data are limited, nested cross-validation can place the entire selection procedure inside each outer training fold. It does not make a repeatedly consulted outer score untouched again, and it cannot repair invalid group or time splits. These are evaluation-design claims, not an implementation of nested cross-validation here. Cawley and Talbot, §5.3; official cross-validation guide.
Predict what a new comparison will change
-
A fixed random candidate makes no mistakes on four validation items. What is the probability of that event? What if you choose the best of 16 independent candidates? Does a perfect score imply a useful predictor?
Answer: The probabilities are 1/16 and 1−(15/16)¹⁶, approximately 0.643926. Under the stated noise model every selected candidate still has fresh-label error one-half. The second event benefits from selection; the first can occur through ordinary variation.
-
Use one training, one validation and one test item, with B=C=2. What are the three expected selected errors? What would happen if all four candidate sheets were identical copies?
Answer: The independent case gives (1/4,1/4,1/2). A minimum of two fair mistake bits is one only when both are one. With four identical copies, selection cannot change any score, so each expectation is one-half. Duplicated runs do not satisfy the independence premise.
-
In the count-table example, replace every test count by zero while leaving training and validation counts intact. Which model is selected? Does using a larger independent test set improve the chosen model?
Answer: The indices stay (1,0); only the reported test error changes. A larger independent test set measures the selected procedure more precisely in this model: variance is 1/(4nₑ). It neither changes selection nor improves its one-half risk. Selecting again after inspecting test results would remove that independence.
-
Why is 50% error not proof of underfitting? Give a case where the same error does reveal a model-class restriction.
Answer: With independent fair labels, one-half is the best achievable population error, regardless of how expressive the predictor is. For noiseless XOR on uniformly distributed binary pairs, constants have error one-half but XOR has zero error. The restriction to constants excludes a useful rule; an error percentage needs a task and comparator before it becomes a diagnosis.
Evaluate the search procedure as well as the final model
Cawley and Talbot’s 2010 paper studies overfitting during model selection and resulting evaluation bias. Its experiments use kernel ridge classifiers and finite-sample selection criteria. The random-sheet experiment here is original and has no fitted signal: it isolates selection optimism rather than reproducing their benchmark or their test-error curves. Their paper explicitly treats model selection as part of the procedure to be evaluated. JMLR article record.
The scikit-learn source was read at the versioned 1.7 path, which displays 1.7.2. Its introduction separates fitting, hyperparameter choice and final testing, and its preprocessing section explains why learned transforms belong inside training. No library implementation, dataset or figure is copied. The train/test splits and model evaluation chapters develop those workflow details.
The accompanying tests count raw binary mistake sheets and small two-stage tables independently of the survival-power formula. They check ties, perfect-score probabilities, exact expected errors, test independence and the failure of the independence formula for duplicated candidates. Results remain arithmetic for a specified teaching model; they are not a detector that labels an arbitrary trained model as overfit.
Make a prediction, then check
Sixteen random candidates are compared on the same four validation items. A winner is perfect. What follows under this chapter’s noise model?
Learning objectives
- Distinguish sample-specific fitting, ordinary score variation, selection optimism and underfitting.
- Derive and calculate the exact minimum-error distribution under independent fair candidate mistakes.
- Audit a two-stage choice without using test errors to select, and explain why repeated validation selection changes reported scores.
Prerequisites & connections
Explore related knowledge →References
- On Over-fitting in Model Selection and Subsequent Selection Bias in Performance Evaluation
Gavin C. Cawley; Nicola L. C. Talbot · 2010 - Cross-validation: evaluating estimator performance
scikit-learn developers
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. Direct raw-bit enumeration checks six minimum-distribution cases using 674 complete sheets, separately from the survival-power implementation. All 4,096 small two-stage tables agree on selected indices, exact expected errors (1/4,1/4,1/2) and test variance.
- Checked stable ties, changing test counts without changing selection, duplicated-candidate dependence, the XOR underfitting counterexample, invalid/empty inputs and the seven actual output lines. Increasing only test size changes its variance, not selection expectations.
- Complete original bilingual prose and identical Python/output, six displays, six anchors and four answered exercises. Strict MDX/KaTeX and actual React HTML passed. Humanizer prose reread; AI author check only, review written pending independent review. No data-collection experiment, nested-CV implementation, library execution or whole-site build.
- Ran all nine author tests using Python 3.12.4. Confirmed complete bilingual Python and seven-line stdout agree with the standalone example; final five SHA-256 values match the author manifest.
- Independent probability reference multiplies the single-count polynomial by (1+z)/2 and feeds independent candidates through a minimum-state Markov transition. It uses neither binomial coefficient recurrence, survival powers, nor enumeration of complete raw-bit sheets. Thirty complete minimum distributions and means match.
- Twenty-seven joint selected-count laws verify both selection stages, all five expected_errors fields and factorization of the selected test count from the training-validation pair. Twenty-seven supplied-table reports agree with pairwise dominance certificates; mutable inputs remain unchanged and changing only valid test counts preserves indices. A 101-digit integer case retains exact rational output.
- Read both full articles. Checked minimum-expectation inequality without independence, stronger independence needed for survival powers, stable ties, first-stage minima unaffected in expectation by independent second-stage selection, and conditional test variance. No-signal risk versus XOR underfitting, duplicate candidates, adaptive validation reuse, positive sample sizes and bit-cost qualifications are stated correctly.
- Strict MDX and KaTeX followed by actual React HTML rendering passed in both languages: six matching displayed TeX annotations, six required anchors and four answered exercises. Compared decoded MathML annotations with source formulas; no KaTeX error or stray Markdown emphasis outside code.
- 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:
- On Over-fitting in Model Selection and Subsequent Selection Bias in Performance Evaluation · Actually opened https://jmlr.org/papers/volume11/cawley10a/cawley10a.pdf (29 pages) and its JMLR record. Header confirms 2010, volume 11, pp. 2079–2107. Read introduction printed 2080, lines 37–61: nested fitting/selection and evaluation of the whole procedure. Read §§4–4.1, printed 2084–2087, lines 315–445: finite-sample criterion variance, the experimental test-error upturn and estimator versus selected-minimum distinction. Read §5.3, printed 2102, lines 1244–1261: selection before outer splitting contaminates evaluation. No source figure, benchmark result or code is reused; text reading, not full-paper visual audit.
- Cross-validation: evaluating estimator performance · Actually read https://scikit-learn.org/1.7/modules/cross_validation.html, displaying 1.7.2: introduction lines 69–102 for memorization, tuning on held-out scores and train/validation/test roles; lines 147–164 for fitting transformations within training; lines 240–247 for IID versus group/time assumptions. The existing shared source card uses the stable URL; body links and this check identify the version actually read.
- On Over-fitting in Model Selection and Subsequent Selection Bias in Performance Evaluation · Independently opened the 29-page original and JMLR article record. Read header and introduction (printed 2079–2080), sections 4–4.1 (2084–2086; extracted lines 315–434), and section 5.3 (2102; lines 1244–1261). Confirms paper identity, model-selection criterion variance, whole-procedure evaluation and selection before evaluation splitting. Text extraction only, no full-paper visual audit. Chapter correctly distinguishes its original constant-risk noise experiment from the paper’s kernel experiments and rising test-error curves.
- Cross-validation: evaluating estimator performance · Independently opened official versioned guide, displaying 1.7.2. Read lines 69–100 (memorization and split roles), 147–164 (training-only transformations), and 240–247 (IID, time and group assumptions). Shared stable source URL is explicitly qualified by versioned body links and metadata. No scikit-learn execution.
Related topics