Why a perfect training score can be bad news
Suppose a student memorizes answers to last year’s practice exam. They may score 100% when given the same questions but struggle when the examiner changes the numbers. A machine-learning model can make the same mistake: it can fit its training examples extremely well without learning a rule that works on new cases.
That is the difference between fitting training data and generalization. Training adjusts a model’s parameters based on examples it is allowed to see. Generalization measures whether the resulting model performs well on appropriately chosen, unseen examples.
Two opposite problems can occur. A model that is too simple may miss a real relationship, which is called underfitting. A model that is too flexible may follow random noise or peculiarities of its training set, which is called overfitting. Complexity is not automatically good or bad; what matters is how the model performs on the intended task.
A practical diagnostic is to compare training and validation results. Poor performance on both often suggests underfitting or another modeling issue. Very strong training performance with noticeably weaker validation performance suggests overfitting, although data quality and distribution differences must also be checked. The article develops these distinctions, explains regularization, and shows how to investigate them in code.
A machine learning model is useful when it performs well on new observations, not merely on examples it has already seen. During training, an algorithm adjusts model parameters to improve an objective measured on training data. The central challenge is generalization: learning relationships that remain useful beyond the particular training sample.
Two common failures illustrate this challenge. An underfit model fails to capture important patterns even in its training data. An overfit model captures details that work on the training set but do not hold reliably on unseen data. Understanding these behaviors is essential before comparing algorithms, tuning hyperparameters, or deploying a model.
1. What happens during model training?
Model training is the process of estimating a model’s learnable parameters from data according to a specified learning objective.
A supervised training dataset contains input features and corresponding target values:
Here, represents the features of example , and represents its target. A parameterized model produces a prediction:
where denotes its learnable parameters. A loss function measures how different a prediction is from the desired target. The training process seeks parameters that reduce an objective such as:
This expression describes empirical risk minimization: minimizing average loss on the observed training sample. It does not guarantee the smallest error on future examples.
Parameters versus hyperparameters
| Element | What it controls | Example |
|---|---|---|
| Model parameter | A quantity estimated during fitting | A regression coefficient or neural network weight |
| Hyperparameter | A configuration chosen outside ordinary parameter fitting | Tree depth, regularization strength, learning rate |
| Loss function | How training errors are measured | Squared error, cross-entropy |
| Optimizer or fitting algorithm | How parameters are estimated | Gradient descent, closed-form solver, tree-splitting procedure |
Not every model trains with gradient descent. A decision tree, for instance, typically chooses splits using a recursive procedure; a nearest-neighbor classifier primarily stores its training examples. The details differ, but all supervised approaches must be evaluated on data that did not determine their final modeling decisions.
2. Training performance is not generalization performance
Suppose a model correctly classifies of training emails. That result tells us how it fits those particular emails. It does not establish how accurately it will classify new messages.
We distinguish two related quantities:
- Training error: Error measured on observations used for fitting the model.
- Generalization error: Expected error on new observations drawn from the intended deployment distribution.
A held-out test set gives an estimate of generalization error; it is not the true expected error itself.
In symbolic form, the population risk is:
The distribution represents the intended population or deployment environment. In practice, we rarely know exactly, so we evaluate the model using appropriately sampled, previously unseen data.
Important assumption: Good test performance supports future performance only when the test set is representative of the intended use. Changes in users, devices, locations, time periods, or labeling conventions may invalidate that assumption.
3. Underfitting: When the model learns too little
Underfitting occurs when a model fails to capture important structure in the data and consequently performs poorly, often on both training and validation examples.
For example, the relationship between a feature and a target might be curved:
Trying to represent this with a straight line,
may leave systematic errors because the model class is too restrictive for the relationship.
Common causes include:
- Insufficient model capacity for the problem.
- Features that omit useful information.
- Excessively strong regularization.
- Inadequate optimization or premature stopping.
- An inappropriate problem formulation or loss function.
Typical evidence: Training error and validation error are both high relative to a suitable baseline. This is a diagnostic clue, not a universal proof; high error can also arise from noisy targets or a poorly specified evaluation setup.
Possible remedies include choosing more informative features, increasing model flexibility, reducing excessive regularization, or improving the fitting procedure.
4. Overfitting: When the model learns the training sample too closely
Overfitting occurs when a model learns training-specific patterns, including accidental variation, that do not generalize well to new observations.
Imagine a small dataset of house prices. A very flexible model might fit every recorded price almost perfectly, including unusual measurements and random noise. If it learned those accidental details rather than a stable relationship, its predictions for new houses may be poor.
Signs often include:
- Very low training error.
- Substantially higher validation error.
- A large and persistent training–validation performance gap.
- Instability when the training sample changes slightly.
Overfitting does not mean that a model merely has many parameters. It describes a relationship between a fitted model, its data, and its performance on unseen observations. Some large models generalize well because of the data available, training choices, architectural constraints, or implicit regularization.
A conceptual illustration
5. Model complexity and the bias–variance tradeoff
Model complexity refers broadly to how flexible a model is in representing patterns. A shallow decision tree is generally less flexible than a very deep tree. A low-degree polynomial is less flexible than a high-degree polynomial.
A common explanation uses bias and variance:
- Bias: Systematic error associated with restricting the types of relationships a model can represent or learn.
- Variance: Sensitivity of a learned predictor to changes in the training sample.
High bias is often associated with underfitting; high variance can contribute to overfitting. These are tendencies rather than labels that uniquely classify every model.
For squared-error regression, the expected prediction error at a fixed input can be decomposed, under the usual assumptions, as:
Here represents irreducible noise in the target at . The expectation over the predictor reflects variation across possible training samples. This formula is not a universal decomposition for every loss function.
The practical lesson is not to choose the simplest or most complex model automatically. Choose a model with the best validated performance for the actual task and its constraints.
6. Training, validation, and test sets
Different subsets of data serve different purposes:
| Dataset | Primary role | Should influence training decisions? |
|---|---|---|
| Training | Fit model parameters | Yes |
| Validation | Select models and hyperparameters | Yes, for model development |
| Test | Estimate final performance after development | No, except to report and interpret the final evaluation |
A typical workflow is:
- Define the prediction target, unit of observation, and performance metric.
- Reserve a test set before extensive experimentation.
- Fit candidate models on training data.
- Compare candidates using a validation set or cross-validation.
- Select hyperparameters and finish the modeling procedure.
- Evaluate the selected procedure on the held-out test set.
In some workflows, the final model is refitted on the combined training and validation data before test evaluation. That refitting step must use choices already made without examining the test results.
Data leakage occurs when information unavailable at prediction time or reserved for evaluation improperly influences model building. Fitting a scaler on all observations before splitting is one example. Repeatedly choosing a model after inspecting test scores can also turn the test set into part of the selection process.
For time-series forecasting, chronological splitting often matters. For data containing repeated observations from the same patients, customers, or devices, group-aware splitting may be needed. Randomly splitting correlated records can produce misleading performance estimates.
7. Learning curves and validation curves
Two diagnostic tools make training behavior easier to interpret.
Learning curves
A learning curve plots a training or validation metric against the amount of training data or training progress, depending on the context.
When plotted against the number of training examples:
- High training and validation errors may indicate insufficient capacity, features, or optimization.
- Low training error with substantially higher validation error suggests overfitting.
- A shrinking validation gap as data increases suggests additional representative examples could help.
Curves must use consistent evaluation methods. A single split can be noisy, especially with small datasets.
Validation curves
A validation curve compares training and validation performance as a chosen hyperparameter varies, such as a decision tree’s max_depth or a regularization coefficient.
Its purpose is to reveal which settings perform well on unseen validation examples. Selecting a hyperparameter solely because it yields the lowest training loss usually defeats the purpose of validation.
8. Techniques that support generalization
There is no one remedy for every generalization problem. The useful choice depends on why errors occur.
8.1 Regularization
Regularization changes the learning objective or procedure to discourage undesirable model behavior, often excessive sensitivity or complexity.
An explicit regularized objective can be written as:
where penalizes a selected property of the parameters and controls its strength.
Common examples include:
| Technique | Basic idea | Caution |
|---|---|---|
| L2 penalty | Discourages large parameter magnitudes through squared coefficients | Feature scaling often affects its behavior |
| L1 penalty | Encourages some coefficients to become zero | Can be unstable among highly correlated features |
| Tree pruning or depth limits | Restricts the detail a tree can model | Too much restriction causes underfitting |
| Early stopping | Stops iterative training when a monitored criterion stops improving | The monitored data must be separate from the fitting targets |
| Dropout | Randomly deactivates units during neural network training | Mostly relevant to particular neural network architectures |
The term regularization includes more than adding a penalty to an equation. Architectural constraints and certain training practices can also act as forms of regularization.
8.2 Better data and features
More representative data, improved labels, and useful features can improve generalization. However, simply adding examples does not automatically solve distribution shift, systematic label errors, or incorrect targets.
8.3 Cross-validation
Cross-validation evaluates a modeling procedure across multiple train–validation partitions. In -fold cross-validation, each fold serves as validation data in turn, and the other folds serve as training data.
This can reduce dependence on a single arbitrary split, but the folds must respect time, groups, and other dependency constraints. Preprocessing must be fitted inside each training fold rather than once on the complete dataset.
8.4 Baselines and error analysis
Compare a model with simple baselines, then inspect errors by class, input range, subgroup, or operating condition. A sophisticated model should demonstrate a practical improvement rather than merely produce impressive training scores.
9. Worked Python example: A decision tree that overfits
The following example uses a synthetic classification dataset. A deep decision tree can capture details specific to a training sample, while a shallower tree may generalize better. Exact numbers depend on the sample and environment; the goal is to compare held-out performance rather than assume one tree always wins.
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
X, y = make_classification(
n_samples=600,
n_features=20,
n_informative=5,
n_redundant=5,
flip_y=0.12,
class_sep=0.8,
random_state=42,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
for depth in [2, 4, 8, None]:
model = DecisionTreeClassifier(max_depth=depth, random_state=42)
model.fit(X_train, y_train)
train_accuracy = accuracy_score(y_train, model.predict(X_train))
test_accuracy = accuracy_score(y_test, model.predict(X_test))
print(
f"max_depth={str(depth):>4} | "
f"train={train_accuracy:.3f} | test={test_accuracy:.3f}"
)
The code deliberately uses the test set to illustrate the training–held-out gap for several depths. In a real project, comparing depths this way would amount to tuning on the test set. You should instead select the depth using validation data or cross-validation, then evaluate the selected model once on the test set.
A leakage-safe model selection procedure
A more appropriate workflow is to search over tree depths with cross-validation inside the training data:
from sklearn.model_selection import GridSearchCV
search = GridSearchCV(
estimator=DecisionTreeClassifier(random_state=42),
param_grid={"max_depth": [2, 4, 6, 8, None],
"min_samples_leaf": [1, 5, 10]},
scoring="accuracy",
cv=5,
n_jobs=-1,
)
search.fit(X_train, y_train)
print("Selected parameters:", search.best_params_)
print("Cross-validation accuracy:", round(search.best_score_, 3))
print("Final test accuracy:", round(search.score(X_test, y_test), 3))
The final test accuracy measures performance on the reserved data after the configuration is selected. For correlated, grouped, or time-ordered samples, replace the default folds with an appropriate splitting strategy.
10. Training neural networks: Epochs and early stopping
Neural network optimization often progresses through multiple epochs, each representing one pass through the training dataset. With mini-batches, the optimizer updates parameters repeatedly within an epoch.
Training loss may continue to decrease even after validation loss stops improving. This pattern can indicate overfitting to the training sample, although fluctuations and optimization behavior can complicate interpretation.
Early stopping monitors a chosen validation metric and stops training when it fails to improve according to a defined rule. Some implementations restore the parameter values from the best observed validation point. Avoid using the final test set to decide when to stop training.
Deep learning also introduces additional considerations, such as data augmentation, weight decay, dropout, normalization, and the influence of optimizer settings. These mechanisms deserve separate treatment in the neural-network articles.
11. Common misunderstandings
“A model with 100% training accuracy is excellent.”
Not necessarily. It may have memorized the sample, including noise or accidental artifacts. Evaluate the intended task on representative unseen examples.
“Overfitting always means the model is too large.”
No. Overfitting depends on data, model flexibility, selection, and training. High capacity is a possible contributor, not a complete diagnosis.
“Regularization always improves accuracy.”
No. Excessive regularization can cause underfitting. Its effect must be checked using validation data.
“A random test split is always unbiased.”
No. If observations share identities or temporal dependencies, a random split may leak information and misrepresent deployment conditions.
“More training epochs always produce a better model.”
No. Additional optimization may improve training loss without improving validation performance.
“Cross-validation prevents every kind of leakage.”
No. Leakage can occur within folds through improper preprocessing, grouping, target construction, or use of future information.
12. Practical diagnostic checklist
Before trusting a trained model, verify that:
- The target and deployment population are clearly defined.
- The evaluation metric matches the real task and error costs.
- Training, validation, and test partitions reflect deployment conditions.
- Preprocessing and feature selection are fitted only on allowed training data.
- Model performance is compared with meaningful baselines.
- Training and validation metrics are examined together.
- Hyperparameters are selected without using final test results.
- Errors are analyzed for important groups and operating conditions.
- The final reported test performance is distinguished from a guarantee of future reliability.
- Monitoring is planned if the deployment distribution can change.
13. Check your understanding
- Why is low training loss insufficient evidence that a model will work on new examples?
- What pattern in training and validation results commonly suggests underfitting?
- What is the generalization gap?
- Why might a deep decision tree overfit a small dataset?
- How does regularization differ from an optimizer?
- Why should scaling be fitted within each cross-validation training fold?
- Why is test-set tuning problematic?
- What is one reason that excellent held-out accuracy might not persist after deployment?
Show suggested answers
- The model may fit training-specific noise rather than a relationship that persists in unseen data.
- Both training and validation performance remain poor relative to a useful baseline.
- The difference between performance on training examples and previously unseen examples; it must be interpreted with the metric and sampling method.
- The tree can create many specific partitions that fit accidental fluctuations in the training sample.
- Regularization constrains or changes what is learned, while an optimizer is a method for estimating parameters under a specified objective.
- Fitting on held-out folds would let information from validation examples influence the transformation.
- It makes the test set part of development, biasing the reported estimate of generalization.
- The deployed inputs or targets may shift away from the distribution represented by the test set.
14. Related concepts
- AI Knowledge Map — the full learning sequence.
- Machine Learning Paradigms — where supervised training fits among learning methods.
- Optimization and Gradient Descent — parameter updates and objective minimization.
- Data Splitting, Labeling, and Leakage — trustworthy separation of datasets.
- Feature Engineering, Encoding, and Scaling — data transformations and model inputs.
- Decision Trees, Random Forests, and Boosting — model complexity in tree-based methods.
- Evaluating Machine Learning Models — next article: metrics, baselines, and evaluation procedures.
- Training Neural Networks: Loss, Optimizers, and Regularization — generalization during deep learning.
References and further reading
- An Introduction to Statistical Learning — training error, test error, model flexibility, and resampling.
- scikit-learn: Common Pitfalls and Recommended Practices — leakage, preprocessing, and reproducibility.
- scikit-learn: Cross-Validation — strategies for evaluating estimators.
- scikit-learn: Validation Curves and Learning Curves — diagnostic tools for training behavior.
- scikit-learn: GridSearchCV — cross-validated hyperparameter selection.
- Deep Learning, Chapter 5: Machine Learning Basics — capacity, overfitting, and generalization.
Related articles in
- Clustering and K-Means — Learn how unsupervised clustering discovers groups in data, how K-Means optimizes cluster centroids, and how to evaluate and use its results responsibly.
- Data, Model, and Experiment Versioning — Learn to trace ML results to exact datasets, code revisions, configurations, and artifacts.
- Decision Trees, Random Forests, and Boosting — Learn how decision trees partition data, how random forests reduce variance through bagging, and how boosting combines sequential learners to improve predictions.