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.
- 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.
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 that penalizes a prediction against a true label — squared error for regression, 0/1 loss for classification. The learning problem assumes an unknown data-generating distribution over pairs , from which we observe a finite training set drawn i.i.d. from . For a hypothesis drawn from a hypothesis space , define two risks. The true risk (also called expected risk or generalization error) is the quantity we actually care about:
This is an expectation over the entire population, most of which we will never see. It cannot be computed exactly because is unknown. The empirical risk on a sample is the quantity we can compute:
When is the training set used to select , is called the training error. Learning algorithms typically work by empirical risk minimization (ERM): choose . This is the natural strategy since itself is inaccessible — but it has a subtle consequence. Because was selected to minimize error on , the training error is a biased estimator of : in expectation, . The hypothesis is fit to the noise and idiosyncrasies of the particular sample, not just the underlying signal. Test error solves this by evaluating on a second sample , drawn from the same but disjoint from and untouched during the fitting of :
Because played no role in choosing , this is an unbiased estimate of : , treating 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 and a test set , drawn (or assumed) i.i.d. from the same distribution . 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 to produce .
Step 3 — Compute training error. Evaluate on itself: . This tells you how well the model fits the data it was optimized against.
Step 4 — Compute test error. Evaluate the same, frozen on , which it has never seen: . This is your estimate of true risk .
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 (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.
Complexity & correctness
Time complexity. Computing either error requires one pass over the relevant set, evaluating at each point: time for and for , each multiplied by the (model-dependent) cost of a single prediction, . So training-error computation is and test-error computation is — linear in the size of the evaluated set, entirely separate from the (typically much larger) cost of fitting in the first place. -fold cross-validation multiplies the fitting cost by , since a fresh hypothesis is trained on each of the training-fold combinations; this is the classic accuracy/compute tradeoff of resampling-based model selection.
Space complexity. to hold both splits, plus whatever space the fitted hypothesis itself occupies (e.g., for a -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 be the ERM hypothesis fit on sample . For any fixed hypothesis (chosen independently of ), linearity of expectation gives
i.e., the empirical risk of a fixed hypothesis is unbiased. But is not fixed — it is chosen adaptively, as the specific minimizer over . The key inequality is
for any fixed reference hypothesis (e.g., the truly-best hypothesis in ), simply because was defined as the minimizer. Taking expectations and using the unbiasedness of :
More directly: one can show , with equality only in degenerate cases (e.g. ). Intuitively, ERM exploits sampling noise in — it can find a hypothesis that fits the particular realized noise in the training sample, which will not reproduce on fresh data. The richer is (the more hypotheses ERM can search over), the more opportunity it has to fit noise, and the larger this generalization gap
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 — vanishing as for hypothesis spaces of fixed complexity, and growing when complexity scales with (as in memorizing models). This machinery formalizes the intuition behind Overfitting and Underfitting.
Why test error is unbiased. is independent of by construction (it is disjoint from and never used in fitting or model selection). Treat as a fixed function once it emerges from training; then is a fresh i.i.d. sample with respect to that fixed function, so
exactly, by linearity of expectation over i.i.d. draws. The price is variance: is a Monte Carlo average of i.i.d. loss values, so by the standard variance-of-mean formula its standard error is . 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 is one fewer example available to fit , which can hurt performance for small datasets. Cross-validation mitigates this by rotating the held-out role across folds, trading a 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 to noisy samples of , , then evaluate on a held-out test set of fresh samples from the same generator. Mean squared error is the loss.
| Degree | Training MSE | Test MSE | Gap (Test − Train) |
|---|---|---|---|
| 1 (linear) | 0.183 | 0.191 | 0.008 |
| 3 | 0.041 | 0.049 | 0.008 |
| 5 | 0.021 | 0.028 | 0.007 |
| 9 | 0.009 | 0.052 | 0.043 |
| 14 | 0.0002 | 0.71 | 0.710 |
| 19 (interpolates all 20 points) | ≈0.000 | 4.8 | 4.800 |
Reading the table: as grows, the hypothesis space (degree- 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 to around as the model captures genuine curvature in , reaches a minimum near the true model complexity, then increases sharply as continues to grow — the polynomial starts fitting the specific noise draws in the 20 training points rather than the underlying sine curve. At 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
| Pitfall | Why it happens | Consequence |
|---|---|---|
| Reporting training error as the model's performance | Training error is easy to compute and always looks good | Wildly overestimates real-world accuracy; model fails in deployment |
| Tuning hyperparameters using the test set | Convenient — "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 splitting | Normalizing "the data" before thinking about splits | Test 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 structure | Test set is not a valid sample from the deployment distribution; error estimate is meaningless |
| Too-small test set | Limited data, desire to keep more for training | High-variance test error estimate; apparent model differences may be noise |
| Comparing many models on one test set and picking the best | Natural workflow when experimenting | Multiple-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
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 , 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 folds, iteratively holding out one fold as validation while fitting on the rest, and averages the 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 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 is an expectation over the entire population distribution , 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 for a good hypothesis, and a disjoint sample lets us honestly estimate how that hypothesis performs on the population it was drawn from.