Machine learning practitioners fear more than most a failure pattern that comes out of the box looking brilliant during development but then falls apart in production. The model has excellent training accuracy and validation metrics that look solid. Real-world data comes along and the model's performance collapses.
Often the culprit is overfitting. This is a fundamental problem in statistical modeling that is both easy to grasp conceptually and remarkably easy to fall into in practice. Understanding overfitting, why it happens and how to prevent it is foundational for anyone working with machine learning systems.
What Overfitting Means
A machine learning model learns from training data: a set of examples from which it extracts patterns to use when making predictions on new data. The goal is not to describe the training data perfectly but to learn the underlying rules well enough to generalize, making accurate predictions on data the model has never seen.
Overfitting. A model that learns the training data too precisely gets overfit and captures not only the true underlying patterns but also the noise, measurement errors and random variation specific to that dataset. When that happens, the model has memorized the training examples instead of learning rules that can be applied more widely.
Diagnosing a model means looking for a gap between how well it performs on training data and how well it performs on validation or test data. When a model gets 98% accuracy on training data and only 62% accuracy on test data, it is almost certainly overfit.
The model has learned details specific to the training set that do not hold for the wider distribution and that is why the training accuracy is misleadingly high.
Think of a student who memorizes every exam from the last five years and scores 100% when handed the exact same paper. Hand them new questions testing the same concepts and their score drops fast because they memorized the specific questions instead of learning the subject.
The Bias-Variance Tradeoff
Overfitting can be understood through the technical framework known as the bias-variance tradeoff. This breaks down prediction error into three components.
Bias. It means the error that comes from assuming a model is too simple. No matter how much training data there is, a linear model fitted to data that has a fundamentally curved relationship will constantly miss the true pattern. That constant, systematic error is bias as an underfitting issue.
Variance refers to the error introduced by sensitivity to small fluctuations in the training data. A highly complex model will fit the training data closely, but different training datasets drawn from the same distribution will produce very different models.
This sensitivity to the specific training data is variance: an overfitting problem.
Irreducible error. This term means noise that comes built into the data itself as measurement error and genuine randomness and no model can get rid of it.
Total expected error = Bias² + Variance + Irreducible Error
Decomposition shows the basic tension that appears here. Models that are simple (with low variance) most often have high bias. Models that are complex (with low bias) most often have high variance. As model complexity moves from underfitting through overfitting, variance goes up and bias goes down. What is sought is the point where total error is minimized.
| Model State | Bias | Variance | Training Error | Test Error |
|---|---|---|---|---|
| Underfitting | High | Low | High | High |
| Optimal fit | Balanced | Balanced | Moderate | Low |
| Overfitting | Low | High | Very low | High |
Tradeoff symmetry does not hold always. High-stakes fields including medical diagnosis, autonomous vehicles and financial risk have error types with unequally high costs and optimization should reflect that asymmetry instead of regarding all errors as equal.
Why Overfitting Happens
Too Much Model Capacity
Every model architecture has a capacity: roughly, the complexity of functions it can represent. A linear model has limited capacity. A polynomial of degree 20 has more. A deep neural network with millions of parameters has enormous capacity.
When model capacity exceeds what the data can support, that is, when the model has more parameters than there are meaningful patterns to learn, the model fills that excess capacity by fitting noise.
This is like having more variables in a regression than there are data points. The model can always find a perfect fit but the result is meaningless.
Model capacity that matches what is needed comes from the complexity of the true pattern and the quantity of training data and not from what is technically possible. More powerful models are not always better models.
Too Little Training Data
When datasets are small, the variance problem gets worse because each training set is a poor stand-in for the true data distribution. What the model learns are features specific to those particular examples instead of features that generalize.
The same architecture that overfits on 1,000 examples might fit appropriately on 100,000 examples of the same problem. More data is often the most practical solution to overfitting when it is available.
When more data is not available, alternatives such as regularization, simpler architectures and data augmentation all work around the basic problem of data scarcity.
Training for Too Long
Even with enough data, neural networks can overfit if they are trained for too many epochs. At the beginning of training, the model picks up broad patterns. With training that goes on, the model progressively refines its fit to the specific training examples and ends up fitting noise.
This is why early stopping, halting training when validation loss starts to increase, is a standard technique.
Learning curves that track both training and validation loss across epochs provide the diagnostic signal. The point where validation loss stops decreasing and begins increasing is the overfit transition: the model has learned everything generalizable and is beginning to memorize.
Data Leakage
A subtle but important form of overfitting occurs when information from the test distribution leaks into the training process. Common sources include:
- Feature leakage: Including features that encode the target variable (a timestamp that perfectly predicts the outcome in historical data but would not be available at prediction time)
- Preprocessing leakage: Fitting a scaler or encoder on the full dataset (including test data) before splitting, so the test set statistics influence the preprocessing
- Hyperparameter selection on test data. Choosing models by test set performance effectively trains on the test set implicitly.
- Target leakage: Including variables that are measured after the outcome has occurred, which would be unavailable at prediction time in deployment
These leakage sources produce models that appear to generalize well during development but fail when deployed on genuinely new data. Data leakage is one of the most common serious errors in applied machine learning and is frequently found in published academic research.
How to Detect Overfitting
The standard diagnostic approach requires splitting data into at least two sets:
Training set: Used to fit the model parameters. The model sees this data during learning.
Validation set (or development set). This set is used to evaluate how the model performs during development and to guide decisions about model architecture as well as hyperparameters. The model does not get trained on this data but development decisions use it for guidance.
Test set: Used only once, for a final evaluation of the selected model. No decisions should be made based on test set performance; its purpose is to estimate generalization to new data.
Overfitting is indicated by a large gap between training performance and validation/test performance. How that gap sizes up as well as how it changes with model complexity guide the choice of an appropriate model size and of regularization.
Learning Curves
Graphing model performance on both training and validation sets against training data size gives learning curves. The curves diagnose what kind of problem the model is facing.
- Underfitting: Both training and validation error are high and similar; adding more data does not help much; the model needs more complexity
- Overfitting: Training error is low, validation error is high; the gap is large; adding more training data typically helps
- Good fit: Both errors are low and similar; the gap is small; additional data provides diminishing returns
Learning curves are one of the most useful diagnostic tools available to ML practitioners and should be standard practice in any serious modeling project.
Preventing Overfitting
Regularization
Regularization. It is techniques that penalize model complexity and make it harder for the model to fit noise.
L2 regularization (Ridge) gives the loss function a penalty term that is proportional to the sum of squared model weights. That discourages large weights and pushes all weights toward zero and makes the model smoother and less sensitive to any single training example.
L2 regularization has a probabilistic interpretation as placing a Gaussian prior on the weights.
L1 regularization (Lasso) gives a penalty that is proportional to the sum of absolute values of weights. That tends to push some weights exactly to zero and produces sparse models that in effect ignore some features. That is useful when only a subset of features is truly relevant.
Dropout (for neural networks) randomly deactivates a proportion of neurons during each training step. This prevents neurons from co-adapting, that is, from developing patterns that depend on the presence of specific other neurons, and forces the network to learn more robust representations.
At test time, all neurons are active, and their weights are scaled to compensate.
Weight decay is L2 regularization applied to neural network weights; it is a standard component of most neural network training regimens and is routinely used in modern transformer-based models.
Batch normalization. Introducing noise through the normalization process, this method stabilizes training as well as has a mild regularizing effect.
Cross-Validation
K-fold cross-validation is a technique for getting a more reliable estimate of model performance and for model selection. The training data is divided into k equal folds. The model is trained k times, each time using k-1 folds for training and the remaining fold for validation. Performance is averaged across all k runs.
Because cross-validation uses all available data for both training and validation across different iterations when training data is limited, the method becomes especially valuable. The variance of the performance estimate gets reduced compared to a single train-validation split.
Nested cross-validation. With an inner loop for picking hyperparameters. An outer loop for assessing model performance, this approach stops the subtle overfitting that happens when one and the same dataset is used to choose hyperparameters and to evaluate performance.
The outer loop provides an unbiased estimate of how well the model-selection procedure works.
Cross-validation does not eliminate the need for a held-out test set. It is a model selection tool, not a final evaluation tool.
Reducing Model Complexity
Sometimes the answer is to use a model that is less complex instead. Occam's razor works as a useful rule in machine learning. When a simpler model gives similar performance to a complex one, go for the simpler model. It is less prone to overfitting, trains and serves faster and most often is easier to interpret and debug.
Specific techniques for reducing complexity include:
- Pruning in decision trees: removing branches that provide little discriminative power
- Dimensionality reduction cuts down the number of input features. It does this through PCA or feature selection to eliminate noise features.
- Architecture search: systematically comparing simpler and more complex model architectures on held-out validation data
Getting More Training Data
More training data is often the most effective remedy for overfitting. More data means a more representative sample, which gives the model less opportunity to exploit idiosyncrasies of the training set.
Data augmentation is a technique for artificially expanding training data by applying transformations to existing examples. In computer vision, this includes random cropping, flipping, rotation, color jitter and more sophisticated techniques like MixUp and CutMix.
Back-translation, synonym substitution and paraphrasing are all part of what augmentation includes in NLP. Variation brought in by augmentation stops the model from overfitting to the exact training examples.
Transfer learning. Instead of learning from scratch, models can use patterns that were learned from large datasets (most often in a related domain).
A vision model pre-trained on ImageNet can be fine-tuned for a specific task with relatively few examples, because the general visual features are already learned. This dramatically reduces the data requirements for any specific task and provides a strong regularizing effect.
Real-World Examples of Overfitting
Medical Diagnosis Models
Academic papers have shown performance for several high-profile AI medical diagnosis models that did not replicate in clinical use. A common problem is that the models learned artifacts of the imaging equipment, scanner settings or hospital-specific preprocessing instead of clinical pathology.
When deployed at hospitals using different equipment, performance dropped dramatically.
In a 2018 study, models trained on chest X-ray pneumonia learned hospital-specific and scanner-related cues instead of clinical pathology alone and they performed worse on images coming from new hospitals.[1]
Correlating with labels in the training set by chance, these features were not causally related to diagnosis. Impressively benchmarking models did this by exploiting dataset-specific shortcuts instead of learning medicine.
This pattern, models learning spurious correlations in training data that do not generalize to deployment settings, has become a recognized research problem in medical AI and is now studied under the rubric of "shortcut learning."
Language Models and Benchmark Contamination
Large language models (LLMs) are trained on enormous crawls of internet text. Many academic benchmarks, standardized tests used to evaluate model capabilities, are also present in that training data.
When a model is evaluated on benchmarks it has effectively been trained on, its performance estimates are inflated. This is a form of test set contamination at massive scale.
This problem has been documented for multiple large models, where performance on some benchmarks decreases substantially when care is taken to exclude benchmark data from training.
Reported benchmark performance for LLMs most often gives an overestimate of true generalization ability and this is especially the case for newer benchmarks that were created after models' training data cutoffs.
The research community has responded by developing "living benchmarks" that are regularly refreshed with new problems, and by evaluating models on held-out test sets that were deliberately excluded from training data.
The basic problem persists. Training data is vast and mostly uncurated that makes it hard to rule out contamination.
Algorithmic Trading
Historical price data goes into developing trading strategies for systematic traders. The problem of overfitting to historical data is large and that means fitting strategies so closely to past market conditions that they capture noise instead of real patterns. Strategies that do well on backtests most often fail when put into live trading.
The financial industry has developed specific tools for this problem, including: walk-forward testing (training on one period, testing on the next, advancing the window and repeating), analysis of the number of parameters in a strategy relative to the data used, explicit multiple-comparison corrections for the number of strategies tested, and "deflated Sharpe ratio" methods that account for the number of strategy attempts made.
Because the researcher's search through many potential strategies amounts to implicit training on the test set and even when each strategy gets evaluated on out-of-sample data, the selection of the best one from many attempts swells performance estimates, the problem is especially acute.
With enough parameters, you can fit any dataset perfectly. The question is whether you have learned anything.
The Test Set Contamination Problem in Practice
The gap between theoretical data hygiene and practical research behavior is a recognized problem in machine learning. Several studies have found that test set performance is frequently optimistic because of contamination.
Common violations include:
Multiple evaluation rounds. By repeatedly evaluating on the same test set and picking the best run, the test set gets used for model selection and that inflates the estimate. Every evaluation partly "uses up" the independence of the test set.
Shared preprocessing. Before splitting occurs, fitting preprocessing pipelines including scalers, encoders and imputers on the entire dataset causes test statistics to get into training and test information to leak subtly.
Architecture selection: Choosing between model architectures based on test set performance is equivalent to training on the test set. This should be done on a separate validation set, with the test set reserved for a single final evaluation.
Benchmark overuse: When the same benchmark is used to evaluate dozens of models over years of research, the research community collectively overfits to that benchmark.
Models that perform well may do so because they happen to suit the idiosyncrasies of that particular evaluation, not because they are better in general. Several widely-used NLP benchmarks (MNLI, SQuAD, others) show evidence of this saturation problem.
Strict data hygiene, pre-registered evaluation protocols and new test sets for each model generation are the solution. It is known but needs institutional commitment that goes against the pressure to produce impressive results fast.
Double Descent: A Modern Complication
Recent research in machine learning has found a phenomenon that complicates the classical bias-variance picture: double descent.
In today's overparameterized models (neural networks that have far more parameters than training examples), pushing model capacity past the classical overfitting point sometimes brings test error down again. The result is a lower error than what was possible in the "good fit" region.
Belkin and colleagues documented this finding in 2019 in PNAS and many subsequent studies have corroborated it. It points to the conclusion that the classical U-shaped bias-variance tradeoff curve does not apply to all model families.
For very large neural networks trained with appropriate regularization, the interpolation regime (where the model exactly fits the training data) can still generalize well.
The explanation is not fully settled but it does involve the implicit regularization effects of stochastic gradient descent as well as the structure of overparameterized neural networks' solution spaces.
Double descent does not get rid of the overfitting idea. It makes more complicated the link between model complexity and how well the model generalizes. It gives the explanation for why in practice scaling up the capacity of neural networks has worked instead of regularizing it.
Overfitting vs. Underfitting: Finding the Balance
Preventing overfitting does not mean minimizing model complexity. A model that is too simple systematically fails to capture real patterns; this is underfitting, and it produces high error on both training and test data.
Model selection aims practically at choosing the model. That means finding the complexity level that minimizes total expected error on new data. What that level depends on is.
- The complexity of the true underlying relationship in the data
- The amount of training data available
- The signal-to-noise ratio in the data
- The cost of different types of errors in the application
To make this choice, cross-validation on held-out data is the right tool and not just training performance. Models should be judged by how they perform on data they have not seen.
The central lesson of overfitting is that in machine learning, performance on the data you have is not what matters. Performance on the data you have not seen yet is what matters. Machine learning model development is oriented toward that goal and overfitting is the most common way that goal gets undermined.
Sources and Further Reading
- Zech, J. R., Badgeley, M. A., Liu, M., Costa, A. B., Titano, J. J., & Oermann, E. K. (2018). Variable generalization performance of a deep learning model to detect pneumonia in chest radiographs: A cross-sectional study. PLOS Medicine, 15(11), e1002683. View source
- Belkin, M., Hsu, D., Ma, S., & Mandal, S. (2019). Reconciling modern machine-learning practice and the classical bias-variance trade-off. Proceedings of the National Academy of Sciences, 116(32), 15849-15854. View source








