Overfitting and Underfitting

A student memorizes last year's exam answers word for word. Then they fail this year's exam because the questions changed slightly. This is overfitting in a nutshell. A model can achieve near-perfect performance on data it has seen. Yet it fails to generalize to new data. The opposite failure is equally damaging. A student who only learns "the capital of France is a city in Europe" struggles too. They answer every geography question the same way. This is too crude to capture what actually matters. Machine learning systems face this tension constantly. Diagnosing which failure mode is occurring is often the single most important skill in applied modeling. This matters because every deployed model faces data it has never seen. A fraud-detection system trained only on historical fraud patterns must catch tomorrow's novel scams. A medical risk model trained on one hospital's patient population must still work at another hospital. If a model overfits, it has essentially memorized noise and idiosyncrasies of the training set. These are spurious correlations that will not recur. If it underfits, it never captured the real signal in the first place. Both lead to poor real-world performance. But the diagnosis, and the fix, are completely different. The big picture is that overfitting and underfitting are two ends of a single spectrum. This spectrum is governed by model complexity relative to the amount and quality of available data. As a hypothesis space grows richer, a learner can fit training data more closely. But at some point it starts fitting noise instead of signal. This article makes that spectrum precise. It defines training and test error curves. It walks through the mechanics of how each failure mode arises. It gives a full worked numerical trace. It catalogs the diagnostic signatures and remedies. It builds directly on Training Error vs Test Error and Hypothesis Spaces. It sets up the more quantitative treatment in The Bias-Variance Tradeoff and the cure via Regularization. By the end, you should be able to look at a plot of training and validation error versus model complexity (or training epochs). You should immediately diagnose which regime you are in. You should explain why it happens mechanically. And you should name the correct next experiment to run — more data, more capacity, regularization, or early stopping.

Key takeaways
  • Overfitting: low training error, high test error — model fits noise in the training set as if it were signal.
  • Underfitting: high training error and high test error — model is too simple to capture real structure.
  • Both are properties of the gap between the chosen hypothesis space and the true data-generating structure, not of the model in isolation.
  • Complexity is controllable via model capacity (features, depth, degree), regularization strength, and effective training time.
  • The training-error-vs-test-error curve as complexity increases is U-shaped for test error, monotonically decreasing for training error.
  • Diagnosis drives the fix: underfitting → increase capacity or reduce bias; overfitting → increase data, add regularization, or reduce capacity.
The core insight

Overfitting and underfitting are the two symptoms of a single underlying cause — a mismatch between model complexity and the amount of true signal extractable from the data — and detecting which one is present is done entirely by comparing training error to held-out error.

The idea

Consider a learning algorithm that selects a hypothesis hh from a hypothesis space H\mathcal{H} by minimizing empirical (training) error on a finite dataset D={(xi,yi)}i=1nD = \{(x_i, y_i)\}_{i=1}^n. Underfitting occurs when H\mathcal{H} is too restrictive to represent the true underlying relationship between xx and yy, so even the best h∈Hh \in \mathcal{H} has high error on both the training set and unseen data. The training error itself is a high number, and this is the tell: the model cannot even fit the data it was shown.

Overfitting occurs when H\mathcal{H} is expressive enough (or the optimization is run long enough) that the selected hh fits not only the true signal but also the sampling noise specific to DD. Training error becomes very low, sometimes zero, while error on a fresh sample drawn from the same distribution remains high or even increases. The hypothesis has effectively partly memorized the training set rather than learning the generating process. Formally, if R(h)R(h) denotes true (population) risk and R^(h)\hat{R}(h) denotes empirical risk on DD, overfitting is the situation where R^(h)\hat{R}(h) is small but R(h)−R^(h)R(h) - \hat{R}(h) is large — the generalization gap is large. The unifying quantity is model capacity: informally, how large and flexible H\mathcal{H} is. Capacity can be measured formally via VC dimension, Rademacher complexity, or number of effective parameters, but the intuition is simpler: a hypothesis space with more capacity can fit more datasets exactly, including datasets that are pure noise. As capacity increases from very low to very high, training error decreases monotonically (a richer space can always fit the training data at least as well), while test error traces a U-shape — first decreasing as real signal is captured, then increasing as the model starts absorbing noise. The minimum of that U is the sweet spot; underfitting lives to its left, overfitting to its right. This single picture is the qualitative core of the The Bias-Variance Tradeoff, where the same phenomenon is decomposed quantitatively into bias and variance terms.

How it works

The mechanism is best understood by tracing exactly what happens as one sweeps a complexity knob — polynomial degree, tree depth, number of hidden units, number of training epochs, or inverse regularization strength — while holding the training set fixed.

Step 1 — Fit at low complexity. The hypothesis space contains only very simple functions (e.g., degree-1 polynomials, a decision stump, a linear model). The best fit in this space cannot bend enough to track the true signal. Both training error and held-out error are high and close to each other, because the model's limitation, not the particular sample, is the bottleneck. This is the underfitting regime.

Step 2 — Increase complexity toward the right amount. As more flexible hypotheses become available (higher-degree polynomials, deeper trees, more hidden units), the model starts capturing genuine structure — curvature, interactions, nonlinearities that really exist in the data-generating process. Training error drops. Crucially, held-out error also drops, because the newly captured structure generalizes: it reflects the true relationship, not sampling noise. This is the productive middle regime, where more capacity is good.

Step 3 — Overshoot into excess complexity. Beyond some point, additional capacity no longer buys genuine structure — there is none left to capture — so the model starts fitting the specific noise realized in this particular training sample. Training error continues to fall, potentially to zero, because a sufficiently flexible model can literally interpolate every training point exactly. But held-out error stops falling and begins to rise, because the noise pattern memorized from the training set does not recur in new data; the model's predictions on new inputs are driven partly by artifacts that have zero correlation with the true target. This is overfitting.

Step 4 — Select complexity using a held-out signal. Because training error is monotonically deceptive (it always prefers more capacity), model selection must use a signal the model did not fit on: a validation set, cross-validation, or a penalized criterion (AIC/BIC) that explicitly charges for capacity. The complexity level minimizing validation error is chosen, and only then is test error — from data touched exactly once — reported as the final, honest estimate of generalization performance. ```text ALGORITHM: DiagnoseAndSelectComplexity INPUT: training set D_train, validation set D_val, a family of hypothesis spaces H_1 ⊂ H_2 ⊂ ... ⊂ H_K of increasing capacity (e.g., polynomial degrees 1..K, or tree depths 1..K) for k = 1 .. K: h_k = argmin_{h in H_k} EmpiricalRisk(h, D_train) # fit on training data only train_err[k] = EmpiricalRisk(h_k, D_train) val_err[k] = EmpiricalRisk(h_k, D_val) # never used to fit h_k

# Diagnostic pass (informational, does not change selection) for k = 1 .. K: gap[k] = val_err[k] - train_err[k] if train_err[k] is high and gap[k] is small: label[k] = "underfitting region" elif train_err[k] is low and gap[k] is large: label[k] = "overfitting region" else: label[k] = "reasonable fit" k_star = argmin_k val_err[k] # model selection uses ONLY validation error h_star = h_{k_star}

# Final, one-time evaluation on data untouched by both fitting and selection test_err = EmpiricalRisk(h_star, D_test) return h_star, test_err, label ``` The subtlety worth emphasizing: `val_err` is used to choose kk, so it is no longer an unbiased estimate of the generalization error of h⋆h_\star once selection has happened (a small amount of overfitting to the validation set itself occurs). The final, honest number must come from a third, untouched test set — this is why practitioners maintain a strict train / validation / test split, or use nested cross-validation when data is scarce.

Figure
Training error and validation error as a function of model complexity
Model complexity → Error Training error Validation / test error sweet spot k* underfitting overfitting

Complexity & correctness

Complexity, computationally. The `DiagnoseAndSelectComplexity` procedure fits KK models, one per complexity level. If a single fit at complexity level kk costs T(k)T(k) time (e.g., O(n⋅dk)O(n \cdot d_k) for a degree-dkd_k polynomial regression via least squares, or O(nlog⁡n⋅dk)O(n \log n \cdot d_k) for tree induction of depth dkd_k), the total procedure costs

∑k=1KT(k),\sum_{k=1}^{K} T(k),

which is dominated by the largest, most complex model in the sweep — typically O(K⋅T(K))O(K \cdot T(K)). Space is O(n)O(n) per fit plus O(K)O(K) to store the error curves, or O(K⋅pK)O(K \cdot p_K) if all KK fitted models are retained (pKp_K the parameter count of the richest model). This is the honest cost of any principled complexity search: there is no way to know the right complexity without trying several and checking held-out performance, short of using a capacity-penalizing criterion (AIC, BIC, minimum description length) that estimates the U-curve analytically from a single fit at each complexity, trading search cost for a bias toward the specific penalty's assumptions.

Why training error is monotonically misleading. For nested hypothesis spaces H1⊂H2⊂⋯\mathcal{H}_1 \subset \mathcal{H}_2 \subset \cdots, since Hk⊂Hk+1\mathcal{H}_k \subset \mathcal{H}_{k+1}, the minimizer of empirical risk over the larger space can always at least match the smaller space's minimum (it contains it as a candidate), so

min⁡h∈Hk+1R^(h)  ≤  min⁡h∈HkR^(h).\min_{h \in \mathcal{H}_{k+1}} \hat{R}(h) \;\le\; \min_{h \in \mathcal{H}_k} \hat{R}(h).

Training error is therefore non-increasing in kk — a mathematical certainty, not an empirical trend — which is exactly why it cannot be used alone to pick kk: it would always select the richest available space, including one so rich it interpolates noise.

Why validation/test error is U-shaped — the bias-variance argument. Decompose expected test error (for squared loss, on a point xx) as

E[(y−h(x))2]=(E[h(x)]−f(x))2⏟bias2+Var(h(x))⏟variance+σ2,\mathbb{E}\big[(y - h(x))^2\big] = \underbrace{\big(\mathbb{E}[h(x)] - f(x)\big)^2}_{\text{bias}^2} + \underbrace{\mathrm{Var}(h(x))}_{\text{variance}} + \sigma^2,

where ff is the true regression function and σ2\sigma^2 is irreducible noise. Low-capacity models have high bias (they cannot represent ff even with infinite data) but low variance (they barely change from one training sample to another, since there is little freedom to change). High-capacity models have low bias but high variance (small perturbations of the training sample — different noise draws — produce very different fitted functions, especially where the model is free to chase individual points). Test error is the sum of these two decreasing/increasing quantities plus a constant, and a sum of a decreasing and an increasing function is minimized at an interior point — this is the mathematical reason the U-shape is not a coincidence but a theorem-level consequence of the decomposition, made fully precise in The Bias-Variance Tradeoff.

Tradeoffs to be honest about. Reducing capacity to fight overfitting introduces bias — you may now systematically miss real structure. Adding regularization to fight overfitting (previewed in Regularization) shrinks variance at the cost of a controlled, small bias increase, and is usually preferable to hard-capping capacity because it degrades gracefully with a tunable knob rather than a discrete choice. Gathering more data reduces variance without adding bias, but is often the most expensive fix in practice. There is no complexity level that is universally correct — the U-curve's minimum depends on sample size (more data shifts it rightward, tolerating more capacity), noise level (more noise shifts it leftward), and true underlying complexity of ff itself.

Worked example

Suppose the true relationship is y=sin⁡(1.5πx)+εy = \sin(1.5\pi x) + \varepsilon, ε∼N(0,0.09)\varepsilon \sim \mathcal{N}(0, 0.09), with x∈[0,1]x \in [0,1], and we have n=12n=12 training points. We fit polynomial regression h(x)=∑j=0dwjxjh(x) = \sum_{j=0}^{d} w_j x^j for degrees d∈{1,3,9}d \in \{1, 3, 9\} and record training MSE and held-out MSE on a fresh 200-point validation set drawn from the same distribution.

Degree ddEffective paramsTraining MSEValidation MSEDiagnosis
120.420.46underfitting — line can't follow the sine bend; both errors high and close
340.090.11good fit — captures the main curvature; small, expected gap
9100.0020.61overfitting — near-zero training error, validation error worse than degree 1

Walking through why degree 9 fails: with 10 free coefficients and only 12 training points, the polynomial has almost enough freedom to pass through every training point exactly (interpolation), including the specific noise draws εi\varepsilon_i at each of the 12 xix_i's. Between training points, the fitted curve is forced to oscillate wildly to hit each noisy target exactly (a manifestation of Runge's phenomenon for high-degree interpolation). Those oscillations are a function purely of this sample's noise realization; a different draw of 12 points from the same true process would force wildly different oscillations. On the validation set, the oscillations are essentially uncorrelated with the true signal, so they contribute pure error — hence validation MSE of 0.61, worse than the underfit line's 0.46, even though training MSE for degree 9 is nearly perfect. Degree 3 sits near the true model's effective complexity (the population signal has a dominant single oscillation over [0,1][0,1] under this frequency, well-approximated by a cubic), so nearly all the reduction in training error going from degree 1 to degree 3 reflects genuine captured signal, and validation error drops correspondingly. Going from degree 3 to degree 9, training error keeps falling (guaranteed, by the nesting argument above) but validation error rises sharply — the signature of crossing from the productive regime into the overfitting regime, exactly the right half of the U-curve in the figure. A second, smaller trace makes the underfitting side concrete with real numbers. Suppose we instead fix degree at 1 but vary sample size n∈{5,50,500}n \in \{5, 50, 500\}:

nnTraining MSE (degree 1)Validation MSE (degree 1)
50.350.58
500.400.45
5000.410.43

Notice training and validation error converge toward the same nonzero floor (around 0.41–0.43) as nn grows, and neither approaches zero. More data does not fix underfitting — the gap between train and validation shrinks, but both stay stubbornly high, because the bottleneck is model bias (a line cannot represent a sine curve), not sample noise. This is the diagnostic contrast with overfitting: overfitting's gap shrinks with more data (variance falls), while underfitting's gap is already small and adding data does not move either curve toward zero.

Common pitfalls & traps

PitfallWhy it happensFix
Using training error to select model complexityTraining error is monotonically non-increasing in capacity, so it always favors the richest modelSelect using a held-out validation set or cross-validation, never training error alone
Reporting validation error as final performanceValidation error was used to choose among models, so it is optimistically biased (selection overfits the validation set)Reserve a separate, untouched test set for the final number
Confusing high training error with a bugAssuming any bad performance means broken code, when the model is simply underfittingCheck the training-error level first: if it is high, suspect capacity/bias, not implementation
Adding features indiscriminately to "improve" fitMore features always reduce training error, masking overfittingTrack validation error alongside training error whenever features are added
Early stopping applied without a validation curveStopping training arbitrarily early or late without checking the U-curve of validation loss over epochsMonitor validation loss per epoch; stop near its minimum, not by a fixed epoch count
Small dataset, complex model, no cross-validationA single train/validation split on tiny data gives a noisy, unreliable U-curve estimateUse k-fold cross-validation to average out split-specific noise when nn is small
Treating "more data always helps" as universalMore data reduces variance (fights overfitting) but does nothing for bias (does not fix underfitting)Diagnose bias vs. variance first; only add data if the diagnosis is overfitting

Pioneers & history

The formal study of the tension between model flexibility and generalization emerged from statistics and learning theory across the 20th century, long before "overfitting" became standard machine-learning vocabulary.

Origins · 1 minRonald A. Fisher and how this was discovered
RA
Ronald A. Fisher
1890–1962 · Foundations of statistical estimation and model fitting

Fisher's development of maximum likelihood estimation and the analysis of degrees of freedom gave the first rigorous language for "how much a model can bend" relative to data, underpinning later formalizations of overfitting via effective parameter counts.

VV
Vladimir Vapnik
1936–present · Statistical learning theory, VC dimension

Vapnik, together with Alexey Chervonenkis, developed VC theory, which gives a formal capacity measure for hypothesis spaces and bounds the generalization gap R(h)−R^(h)R(h) - \hat{R}(h) in terms of that capacity and sample size — the theoretical backbone explaining why the U-curve exists and where its minimum shifts as data grows.

History
1949
— Hirotugu Akaike's later-formalized ideas trace to earlier work connecting model complexity penalties to generalization, culminating in AIC (1974).
1971
— Vapnik and Chervonenkis publish the VC theory bounding generalization error via hypothesis space capacity.
1978
— Gideon Schwarz introduces the Bayesian Information Criterion (BIC), penalizing complexity more heavily than AIC for large samples.
1992
— Cross-validation and bootstrap-based model selection become standard practice in statistics and early machine learning, popularized through work by Bradley Efron and others.
2010
s — Deep learning practice popularizes early stopping and explicit train/validation/test discipline as the default overfitting countermeasure at scale.

Where this matters

Every production machine learning pipeline is architected around this tension. Search ranking and recommendation systems (used by web search engines and streaming platforms) hold out validation data specifically to catch models that have overfit to historical click patterns rather than learning genuinely predictive user preferences. Autonomous driving perception systems must generalize to weather, lighting, and road conditions never seen in training, so validation on deliberately distribution-shifted held-out sets is standard to catch overfitting to the training distribution's idiosyncrasies. Medical diagnostic models trained on data from one hospital system are routinely evaluated on external hospitals precisely to detect overfitting to site-specific artifacts (scanner type, patient demographics) rather than the actual disease signal. Large language model training uses validation loss curves over the course of training to decide when additional training epochs stop helping and start memorizing, informing decisions about dataset size, model size, and stopping point (related to the "compute-optimal scaling" tradeoffs that are themselves a large-scale instance of the bias-variance tradeoff). Regularization techniques such as weight decay, dropout, and data augmentation — the practical machinery introduced in Regularization — exist entirely because engineers need a tunable knob to move along the complexity axis without discretely changing the hypothesis space, and cross-validation and the train/validation/test protocol described here remain the universal diagnostic tool for locating where on that axis a given model sits.

Ask the tutor: How does the bias-variance decomposition mathematically prove that the U-shaped validation error curve must have an interior minimum?

Is overfitting always bad, or can a slightly overfit model still be useful?

A model with a small generalization gap and low test error is fine even if the gap is technically nonzero — some gap is normal and expected, since training error is a slightly optimistic estimate by construction. The danger threshold is when the gap becomes large relative to the achievable error level, or when the validation error is rising rather than merely nonzero. In some applied settings (e.g., ensembles with many trees), individual base learners intentionally overfit slightly, because the ensembling procedure itself removes the variance component afterward. So "overfitting" should be judged by held-out performance trending worse, not by the mere existence of a train/test gap.

How is this different from the bias-variance tradeoff — aren't they the same thing?

They describe the same phenomenon at different levels of formality. Overfitting and underfitting are the symptoms, diagnosed by comparing training and validation error curves — a purely empirical, operational description. The bias-variance decomposition is the mathematical explanation for why those symptoms occur: it decomposes expected test error into a bias term (from capacity being too low) and a variance term (from capacity being too high) plus irreducible noise. Overfitting corresponds to the high-variance/low-bias regime, underfitting to the high-bias/low-variance regime. The Bias-Variance Tradeoff develops the decomposition itself; this article develops the empirical diagnostic and the mechanics behind it.

Does more training data always cure overfitting?

More data reduces variance, which is the direct driver of overfitting, so it generally helps — but with important caveats. If the noise level in the data is very high, or the model's capacity is astronomically larger than what any feasible dataset could constrain, more data helps but may require an impractically large amount before the effect becomes visible. More data does nothing for bias, so if the real problem is that the hypothesis space cannot represent the true function (underfitting), adding data will not close that gap; both training and validation error will converge to the same nonzero floor, as shown in the worked example's second table.

How does regularization prevent overfitting without literally shrinking the hypothesis space?

Regularization (previewed in Regularization) adds a penalty term to the training objective — for example λ∥w∥22\lambda \|w\|_2^2 in ridge regression — that discourages large parameter values without formally removing any hypothesis from consideration. Effectively, it reshapes the optimization landscape so that solutions requiring extreme, noise-chasing parameter values become costly, biasing the search toward smoother functions that happen to generalize better. This achieves a similar effect to reducing capacity (moving leftward on the complexity axis) but continuously and smoothly via the regularization strength λ\lambda, rather than discretely by changing the model family.

How do neural networks fit into this, given they have millions of parameters yet often don't overfit badly?

Naively, a network with far more parameters than training examples should overfit catastrophically by the classical capacity argument, and indeed it can perfectly memorize random labels. In practice, however, implicit regularization from stochastic gradient descent, architectural constraints (weight sharing in convolutions), explicit regularization (dropout, weight decay, data augmentation), and early stopping combine to keep the effective capacity used by the optimizer well below the nominal parameter count. This is an active research area (the "double descent" phenomenon shows the classical U-curve can even have a second descending region past the interpolation threshold), but the core diagnostic — compare training loss to validation loss — remains exactly as described here.

What is the difference between a validation set and a test set, and why does it matter for this topic?

The validation set is used during model development to choose hyperparameters, including complexity level, and is therefore repeatedly queried and implicitly overfit to by the model-selection process itself. The test set is touched exactly once, after all decisions are finalized, to produce an unbiased estimate of real-world generalization. Conflating the two — reporting validation error as if it were test error — silently understates the true generalization gap, because the complexity level was chosen precisely to minimize error on that same validation set.

Can a model underfit and overfit simultaneously in different parts of the input space?

Yes — this is common with heterogeneous data. A single global model of modest capacity might underfit a densely-sampled, complex region of the input space while simultaneously overfitting a sparsely-sampled region where few training points exist to constrain it. Aggregate training/validation error can look reasonable even while local behavior is poor in both directions. This motivates diagnostics beyond a single scalar error — residual plots, per-segment error breakdowns, or local models (e.g., trees, k-nearest neighbors) — to catch complexity mismatches that vary across the input domain.

Before this

Where this leads