Training Error vs Test Error

Imagine tuning a polynomial to fit fifteen noisy temperature readings. A degree-14 polynomial passes through every point exactly. This achieves zero training error. Yet asked to predict the sixteenth reading, it swings wildly. It fails badly. This gap between fitting the data we have and predicting data we haven't seen is the central drama of supervised learning. Every practical machine learning system — a spam filter, a fraud detector, a medical diagnosis model — is judged differently than by explanatory fit. It is judged by how well it behaves on new, unseen cases. Training error is cheap and always computable. But it is a biased, often deceptive estimate of what actually matters. Test error is computed on data the model never touched during fitting. It is the honest proxy for real-world performance. Confusing the two is perhaps the single most common conceptual error made by newcomers to the field. Understanding why they diverge is the gateway to understanding Generalization, Overfitting and Underfitting, and the entire enterprise of statistical learning theory. This article builds the concept from first principles established in The Formal Learning Problem: a data-generating distribution, a loss function, and a hypothesis chosen from a Hypothesis Space. We define empirical risk (training error) and expected risk (true error). We show precisely why the empirical risk of the selected hypothesis is an optimistically biased estimate of true risk. We explain why a held-out test set fixes this bias. We derive the mechanics of measuring both quantities, and trace a concrete worked numerical example. We also catalog the pitfalls — data leakage, test-set reuse, distribution shift — that silently invalidate the whole exercise. By the end you will be able to state precisely what training and test error measure. You will be able to prove why training error systematically underestimates true error. You will also be able to describe the experimental discipline (train/validation/test splits, cross-validation) that keeps evaluation honest. This groundwork is what makes the later diagnosis of overfitting and underfitting a matter of measurement rather than guesswork.

Key takeaways
  • Training error is the average loss of a hypothesis on the exact data used to fit it; it is called the empirical risk.
  • Test error is the average loss on fresh data drawn from the same distribution but excluded from fitting; it estimates the expected (true) risk.
  • Training error is a biased, optimistic estimate of true risk because the hypothesis was chosen specifically to fit that data.
  • The gap between training and test error grows with hypothesis space complexity and shrinks with more training data.
  • A held-out test set gives an unbiased estimate of true risk only if it is used exactly once, never touched during model selection.
  • Reusing, peeking at, or tuning on the test set silently converts it into training data — a subtle and dangerous failure mode.
The core insight

Training error measures how well a model memorizes the data it saw; test error measures how well it generalizes to data it did not — and only the second one matters.

The idea

Fix a loss function ℓ(y,y^)\ell(y, \hat y) that penalizes a prediction y^\hat y against a true label yy — squared error for regression, 0/1 loss for classification. The learning problem assumes an unknown data-generating distribution D\mathcal D over pairs (x,y)(x, y), from which we observe a finite training set S={(x1,y1),…,(xn,yn)}S = \{(x_1,y_1), \dots, (x_n,y_n)\} drawn i.i.d. from D\mathcal D. For a hypothesis hh drawn from a hypothesis space H\mathcal H, define two risks. The true risk (also called expected risk or generalization error) is the quantity we actually care about:

R(h)=E(x,y)∼D[ℓ(y,h(x))].R(h) = \mathbb{E}_{(x,y)\sim \mathcal D}\big[\ell(y, h(x))\big].

This is an expectation over the entire population, most of which we will never see. It cannot be computed exactly because D\mathcal D is unknown. The empirical risk on a sample SS is the quantity we can compute:

R^S(h)=1n∑i=1nℓ(yi,h(xi)).\hat R_S(h) = \frac{1}{n}\sum_{i=1}^{n} \ell(y_i, h(x_i)).

When SS is the training set used to select hh, R^S(h)\hat R_S(h) is called the training error. Learning algorithms typically work by empirical risk minimization (ERM): choose h^=arg⁡min⁡h∈HR^S(h)\hat h = \arg\min_{h \in \mathcal H} \hat R_S(h). This is the natural strategy since R(h)R(h) itself is inaccessible — but it has a subtle consequence. Because h^\hat h was selected to minimize error on SS, the training error R^S(h^)\hat R_S(\hat h) is a biased estimator of R(h^)R(\hat h): in expectation, R^S(h^)≤R(h^)\hat R_S(\hat h) \le R(\hat h). The hypothesis is fit to the noise and idiosyncrasies of the particular sample, not just the underlying signal. Test error solves this by evaluating h^\hat h on a second sample S′S', drawn from the same D\mathcal D but disjoint from and untouched during the fitting of h^\hat h:

R^S′(h^)=1∣S′∣∑(x,y)∈S′ℓ(y,h^(x)).\hat R_{S'}(\hat h) = \frac{1}{|S'|}\sum_{(x,y)\in S'} \ell(y, \hat h(x)).

Because S′S' played no role in choosing h^\hat h, this is an unbiased estimate of R(h^)R(\hat h): ES′[R^S′(h^)]=R(h^)\mathbb{E}_{S'}[\hat R_{S'}(\hat h)] = R(\hat h), treating h^\hat h as fixed. This single distinction — was the data used to choose the hypothesis, or only to evaluate it — is the entire content of the training/test error dichotomy.

How it works

Measuring training and test error is procedurally simple, but the discipline lies in never letting information flow the wrong direction — from the test set into model fitting or model selection.

Step 1 — Split the data. Partition the available labeled data into a training set StrainS_{\text{train}} and a test set StestS_{\text{test}}, drawn (or assumed) i.i.d. from the same distribution D\mathcal D. A common split is 70–90% train, 10–30% test; the test set must be large enough that its own sampling noise doesn't swamp the signal you're trying to measure.

Step 2 — Fit on training data only. Run the learning algorithm (ERM, gradient descent, decision tree induction, whatever the model class calls for) using only StrainS_{\text{train}} to produce h^\hat h.

Step 3 — Compute training error. Evaluate h^\hat h on StrainS_{\text{train}} itself: R^Strain(h^)\hat R_{S_{\text{train}}}(\hat h). This tells you how well the model fits the data it was optimized against.

Step 4 — Compute test error. Evaluate the same, frozen h^\hat h on StestS_{\text{test}}, which it has never seen: R^Stest(h^)\hat R_{S_{\text{test}}}(\hat h). This is your estimate of true risk R(h^)R(\hat h).

Step 5 (if tuning hyperparameters) — use a validation set, not the test set. If you need to choose among several models or hyperparameters (polynomial degree, regularization strength, tree depth), do so using a third split — a validation set — or via k-fold cross-validation on the training data. The test set is touched exactly once, at the very end, to report a final unbiased number. ``` ALGORITHM TrainTestEvaluate(D, learner, loss, split_ratio):

# D: full labeled dataset drawn i.i.d. from distribution

# learner: algorithm that fits a hypothesis given data

# loss: pointwise loss function ℓ(y, ŷ) Shuffle D uniformly at random # break any ordering artifacts (S_train, S_test) ← Split(D, split_ratio) h_hat ← learner.fit(S_train) # ERM: minimize empirical risk on train ONLY train_error ← Mean( loss(y_i, h_hat(x_i)) for (x_i, y_i) in S_train ) test_error ← Mean( loss(y_i, h_hat(x_i)) for (x_i, y_i) in S_test ) return train_error, test_error

ALGORITHM KFoldCrossValidate(D_train, learner, loss, k):

# Used for model/hyperparameter SELECTION, never for the final reported number folds ← PartitionIntoKEqualParts(Shuffle(D_train), k) scores ← [] for i in 1..k: val_fold ← folds[i] train_folds ← Concatenate(folds[1..k] minus folds[i]) h_i ← learner.fit(train_folds) scores.append( Mean( loss(y, h_i(x)) for (x,y) in val_fold ) ) return Mean(scores) # cross-validation estimate of test error ``` The crucial invariant, enforced in both procedures, is: any data point used to fit h^\hat h (directly, or indirectly through hyperparameter choice) must never be used to report its final error. Violating this — even by something as innocuous as normalizing features using statistics computed over the whole dataset before splitting — leaks test information into training and biases the reported error downward.

Figure
Data flow: what touches the hypothesis vs. what only evaluates it
Full labeled dataset D ~ 𝒟 (i.i.d.) S_train (e.g. 80%) S_test (e.g. 20%) — locked away learner.fit(S_train) ERM chooses ĥ ∈ ℋ ĥ (frozen) eval on train eval on test (once!) training error (biased, optimistic) test error (unbiased estimate of R(ĥ))

Complexity & correctness

Time complexity. Computing either error requires one pass over the relevant set, evaluating hh at each point: O(n)O(n) time for ∣Strain∣=n|S_{\text{train}}| = n and O(m)O(m) for ∣Stest∣=m|S_{\text{test}}| = m, each multiplied by the (model-dependent) cost of a single prediction, c(h)c(h). So training-error computation is O(n⋅c(h))O(n \cdot c(h)) and test-error computation is O(m⋅c(h))O(m \cdot c(h)) — linear in the size of the evaluated set, entirely separate from the (typically much larger) cost of fitting h^\hat h in the first place. kk-fold cross-validation multiplies the fitting cost by kk, since a fresh hypothesis is trained on each of the kk training-fold combinations; this is the classic accuracy/compute tradeoff of resampling-based model selection.

Space complexity. O(n+m)O(n + m) to hold both splits, plus whatever space the fitted hypothesis h^\hat h itself occupies (e.g., O(d)O(d) for a dd-dimensional linear model, or the size of a tree/network). No additional asymptotic overhead is introduced by the train/test split itself, only a constant-factor duplication consideration if both sets must be memory-resident simultaneously.

Correctness — why training error is optimistically biased. Let h^S=arg⁡min⁡h∈HR^S(h)\hat h_S = \arg\min_{h \in \mathcal H} \hat R_S(h) be the ERM hypothesis fit on sample SS. For any fixed hypothesis hh (chosen independently of SS), linearity of expectation gives

ES[R^S(h)]=R(h),\mathbb{E}_S\big[\hat R_S(h)\big] = R(h),

i.e., the empirical risk of a fixed hypothesis is unbiased. But h^S\hat h_S is not fixed — it is chosen adaptively, as the specific minimizer over SS. The key inequality is

R^S(h^S)=min⁡h∈HR^S(h)  ≤  R^S(h⋆),\hat R_S(\hat h_S) = \min_{h \in \mathcal H} \hat R_S(h) \;\le\; \hat R_S(h^\star),

for any fixed reference hypothesis h⋆h^\star (e.g., the truly-best hypothesis in H\mathcal H), simply because h^S\hat h_S was defined as the minimizer. Taking expectations and using the unbiasedness of R^S(h⋆)\hat R_S(h^\star):

ES[R^S(h^S)]≤ES[R^S(h⋆)]=R(h⋆)≤R(h^S)’s expected value is generally≥ES[R^S(h^S)].\mathbb{E}_S[\hat R_S(\hat h_S)] \le \mathbb{E}_S[\hat R_S(h^\star)] = R(h^\star) \le R(\hat h_S)\text{'s expected value is generally} \ge \mathbb{E}_S[\hat R_S(\hat h_S)].

More directly: one can show ES[R(h^S)−R^S(h^S)]≥0\mathbb{E}_S[R(\hat h_S) - \hat R_S(\hat h_S)] \ge 0, with equality only in degenerate cases (e.g. ∣H∣=1|\mathcal H|=1). Intuitively, ERM exploits sampling noise in SS — it can find a hypothesis that fits the particular realized noise in the training sample, which will not reproduce on fresh data. The richer H\mathcal H is (the more hypotheses ERM can search over), the more opportunity it has to fit noise, and the larger this generalization gap

gap=R(h^S)−R^S(h^S)≥0(in expectation)\text{gap} = R(\hat h_S) - \hat R_S(\hat h_S) \ge 0 \quad(\text{in expectation})

becomes. This gap is exactly bounded by the uniform-convergence tools of statistical learning theory (VC dimension, Rademacher complexity), which show the gap shrinks at a rate like O(complexity(H)/n)O(\sqrt{\text{complexity}(\mathcal H)/n}) — vanishing as n→∞n \to \infty for hypothesis spaces of fixed complexity, and growing when complexity scales with nn (as in memorizing models). This machinery formalizes the intuition behind Overfitting and Underfitting.

Why test error is unbiased. StestS_{\text{test}} is independent of h^S\hat h_S by construction (it is disjoint from StrainS_{\text{train}} and never used in fitting or model selection). Treat h^S\hat h_S as a fixed function once it emerges from training; then StestS_{\text{test}} is a fresh i.i.d. sample with respect to that fixed function, so

EStest[R^Stest(h^S)]=R(h^S)\mathbb{E}_{S_{\text{test}}}\big[\hat R_{S_{\text{test}}}(\hat h_S)\big] = R(\hat h_S)

exactly, by linearity of expectation over i.i.d. draws. The price is variance: R^Stest\hat R_{S_{\text{test}}} is a Monte Carlo average of mm i.i.d. loss values, so by the standard variance-of-mean formula its standard error is O(1/m)O(1/\sqrt m). Larger test sets give tighter, but still unbiased, estimates; smaller test sets are noisier but remain unbiased in expectation. This unbiasedness is contingent entirely on the no-peeking discipline — the moment the test set influences any modeling decision, this guarantee breaks.

Honest tradeoff. Held-out evaluation costs you data: every example spent on StestS_{\text{test}} is one fewer example available to fit h^\hat h, which can hurt performance for small datasets. Cross-validation mitigates this by rotating the held-out role across kk folds, trading a k×k\times increase in fitting compute for a training-set-sized evaluation budget — a classic statistical-efficiency-versus-computational-cost tradeoff.

Worked example

Suppose we fit polynomial regression models of increasing degree dd to n=20n = 20 noisy samples of y=sin⁡(x)+εy = \sin(x) + \varepsilon, ε∼N(0,0.12)\varepsilon \sim \mathcal N(0, 0.1^2), then evaluate on a held-out test set of m=200m = 200 fresh samples from the same generator. Mean squared error is the loss.

Degree ddTraining MSETest MSEGap (Test − Train)
1 (linear)0.1830.1910.008
30.0410.0490.008
50.0210.0280.007
90.0090.0520.043
140.00020.710.710
19 (interpolates all 20 points)≈0.0004.84.800

Reading the table: as dd grows, the hypothesis space Hd\mathcal H_d (degree-≤d\le d polynomials) becomes richer, and ERM drives training error monotonically toward zero — with 20 points and a degree-19 polynomial, the fit can pass through every point exactly, giving training error indistinguishable from zero. But test error is not monotonic. It decreases from d=1d=1 to around d=5d=5 as the model captures genuine curvature in sin⁡(x)\sin(x), reaches a minimum near the true model complexity, then increases sharply as dd continues to grow — the polynomial starts fitting the specific noise draws in the 20 training points rather than the underlying sine curve. At d=19d=19 the training error is essentially zero while the test error is enormous: a textbook case of the generalization gap predicted above, driven to its extreme. This single table is the empirical signature that later motivates the bias–variance framing of Overfitting and Underfitting: low-degree models underfit (both errors are high and close together), very high-degree models overfit (training error near zero, test error large), and the sweet spot minimizes test error, not training error. Crucially, if we had only looked at training error, we would have wrongly concluded degree 19 is the best model.

Common pitfalls & traps

PitfallWhy it happensConsequence
Reporting training error as the model's performanceTraining error is easy to compute and always looks goodWildly overestimates real-world accuracy; model fails in deployment
Tuning hyperparameters using the test setConvenient — "just check test accuracy while adjusting knobs"Test set becomes a de facto training signal; reported number is biased optimistic
Feature scaling / imputation computed on the full dataset before splittingNormalizing "the data" before thinking about splitsTest statistics leak into training features — a subtle form of data leakage
Non-i.i.d. splits (e.g., time series shuffled randomly)Assuming exchangeability when data has temporal/spatial structureTest set is not a valid sample from the deployment distribution; error estimate is meaningless
Too-small test setLimited data, desire to keep more for trainingHigh-variance test error estimate; apparent model differences may be noise
Comparing many models on one test set and picking the bestNatural workflow when experimentingMultiple-comparisons bias — the "winning" model's test error is optimistically selected, just like training error

Pioneers & history

The training/test distinction is not attributable to a single inventor; it crystallized from statistics and pattern recognition as machine learning became an empirical discipline demanding honest evaluation protocols.

Origins · 1 minVladimir Vapnik and how this was discovered
VV
Vladimir Vapnik
1936–present · Co-developer of statistical learning theory and VC theory, which formalizes why training error underestimates true risk

History
1901
— Karl Pearson develops early goodness-of-fit and regression diagnostics, precursors to out-of-sample thinking in statistics.
1968
— Vapnik and Chervonenkis introduce VC dimension, giving the first rigorous bounds on the gap between empirical and true risk.
1974
— Seymour Geisser formalizes cross-validation and predictive sample reuse for honest model assessment.
1979
— Bradley Efron introduces the bootstrap, a resampling alternative for estimating generalization performance.
1995
— Vapnik's "The Nature of Statistical Learning Theory" popularizes the empirical-risk-minimization framework across machine learning.

Where this matters

Every deployed machine learning system relies on the training/test distinction to decide whether it is safe to ship. Competition platforms like Kaggle enforce strict train/public-test/private-test splits precisely to prevent leaderboard overfitting — the public leaderboard behaves like a semi-repeated test set, and competitors who over-tune to it often collapse on the private leaderboard, a real-world demonstration of test-set reuse bias. Production ML pipelines at large tech companies use time-based train/validation/test splits (train on past data, test on future data) to simulate genuine deployment conditions, since randomly shuffled splits would leak future information backward in time. Regulatory and safety-critical domains — clinical diagnosis models, credit scoring, autonomous driving perception — require reported performance metrics to come from held-out data never touched during development, often with external, independently-collected test sets to guard against subtler forms of the same bias (e.g., dataset-specific artifacts). Benchmark suites in computer vision and NLP (ImageNet, GLUE, SQuAD) maintain hidden test sets with restricted submission counts, directly enforcing the "use it once" discipline this article derives from first principles. Understanding training versus test error is the prerequisite for every downstream diagnostic tool — learning curves, validation curves, early stopping — that practitioners use to detect and correct Overfitting and Underfitting before a model ever reaches production.

Ask the tutor: How does the size of the hypothesis space quantitatively control the size of the generalization gap, via VC dimension or Rademacher complexity bounds?

Is training error ever a useful number to look at?

Yes — not as a performance report, but as a diagnostic. Comparing training error to test error tells you where a model sits on the underfitting-overfitting spectrum. If both are high and similar, the model is likely underfitting (too simple, or hypothesis space too restrictive). If training error is very low but test error is high, the model is overfitting. Tracking training error alongside a validation error across training iterations (a learning curve) is a standard diagnostic tool. The mistake is not looking at training error — it's treating it as an estimate of real-world performance.

How large should the test set be?

Large enough that its sampling variance doesn't drown the signal you're trying to measure. As a rough guide, the standard error of a mean-based test error estimate shrinks as O(1/m)O(1/\sqrt m), so quadrupling test-set size halves the noise. For small datasets (hundreds of examples), k-fold cross-validation is often preferred over a single held-out split, since it uses all data for both training and evaluation across folds, trading extra compute for reduced variance in the estimate. For very large datasets (millions of examples), even a 1% test split can contain enough examples for a tight estimate.

What's the difference between a validation set and a test set?

A validation set is used during model development — to select hyperparameters, compare architectures, or decide when to stop training — and can be consulted repeatedly. A test set is reserved exclusively for final, one-time evaluation after all decisions are locked in. If you use your "test set" more than once to make decisions, it has functionally become a validation set, and you no longer have an honest estimate of true risk; you need a fresh, never-touched set for that final number.

Does a small training-test gap always mean the model is good?

Not necessarily. A small gap means the model generalizes consistently, but consistently bad is still bad — a model with 40% training error and 41% test error has a tiny gap but poor absolute performance, likely underfitting. You need to examine both the absolute level of test error (is it good enough for the task?) and the gap (is the model overfitting?) — they answer different questions.

How does cross-validation relate to the training/test split?

K-fold cross-validation partitions the training data into kk folds, iteratively holding out one fold as validation while fitting on the rest, and averages the kk resulting validation errors. It is a resampling technique for model selection and error estimation that makes more efficient use of limited data than a single fixed split, at the cost of training kk separate models. It is typically used within the training set (for hyperparameter tuning), while a separate, untouched test set is still reserved for the final unbiased report.

Can training error ever exceed test error?

Yes, though it's atypical. It can happen with small samples, high-variance estimators, or noisy test sets — pure sampling luck can make a particular test draw easier than the training draw. It's also expected under heavy regularization or when using techniques like dropout that are active only during training (inflating training loss) but turned off at test time. In expectation over repeated experiments, however, training error is systematically less than or equal to true risk, which test error estimates unbiasedly.

Why can't we just use the true risk formula directly instead of splitting data?

Because true risk R(h)=E(x,y)∼D[ℓ(y,h(x))]R(h) = \mathbb{E}_{(x,y)\sim\mathcal D}[\ell(y,h(x))] is an expectation over the entire population distribution D\mathcal D, which is unknown — we only ever observe a finite sample from it. The train/test split is a practical device for estimating this unobservable quantity: the training sample lets us search H\mathcal H for a good hypothesis, and a disjoint sample lets us honestly estimate how that hypothesis performs on the population it was drawn from.

Before this

Where this leads