Machine Learning • Machine Learning Fundamentals • 16 min read

Model Training, Overfitting, and Generalization

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:

Dtrain={(xi,yi)}i=1n.D_{\mathrm{train}}=\{(x_i,y_i)\}_{i=1}^{n}.

Here, xix_i represents the features of example ii, and yiy_i represents its target. A parameterized model produces a prediction:

y^i=fθ(xi),\hat y_i=f_\theta(x_i),

where θ\theta 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:

θ^=argmin⁡θ  1n∑i=1nℓ(fθ(xi),yi).\hat\theta=\underset{\theta}{\operatorname{argmin}}\;\frac{1}{n}\sum_{i=1}^{n}\ell(f_\theta(x_i),y_i).

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

ElementWhat it controlsExample
Model parameterA quantity estimated during fittingA regression coefficient or neural network weight
HyperparameterA configuration chosen outside ordinary parameter fittingTree depth, regularization strength, learning rate
Loss functionHow training errors are measuredSquared error, cross-entropy
Optimizer or fitting algorithmHow parameters are estimatedGradient 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 99%99\% 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:

R(θ)=E(X,Y)∼P[ℓ(fθ(X),Y)].R(\theta)=\mathbb{E}_{(X,Y)\sim P}\left[\ell(f_\theta(X),Y)\right].

The distribution PP represents the intended population or deployment environment. In practice, we rarely know PP 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 xx and a target yy might be curved:

y≈x2.y\approx x^2.

Trying to represent this with a straight line,

y^=ax+b,\hat y=ax+b,

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

Three conceptual fits: underfitting straight line, appropriately flexible curve, and overfitting curve with unnecessary oscillations
Conceptual model fits. The goal is not the most visually complicated curve; it is the model that performs reliably on new data.

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:

E[(Y−f^(x))2∣X=x]=Bias⁡[f^(x)]2+Var⁡[f^(x)]+σ2(x).\mathbb{E}\left[(Y-\hat f(x))^2\mid X=x\right] =\operatorname{Bias}[\hat f(x)]^2 +\operatorname{Var}[\hat f(x)] +\sigma^2(x).

Here σ2(x)\sigma^2(x) represents irreducible noise in the target at xx. 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:

DatasetPrimary roleShould influence training decisions?
TrainingFit model parametersYes
ValidationSelect models and hyperparametersYes, for model development
TestEstimate final performance after developmentNo, except to report and interpret the final evaluation

A typical workflow is:

  1. Define the prediction target, unit of observation, and performance metric.
  2. Reserve a test set before extensive experimentation.
  3. Fit candidate models on training data.
  4. Compare candidates using a validation set or cross-validation.
  5. Select hyperparameters and finish the modeling procedure.
  6. 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:

J(θ)=1n∑i=1nℓ(fθ(xi),yi)+λΩ(θ),J(\theta)=\frac{1}{n}\sum_{i=1}^{n}\ell(f_\theta(x_i),y_i)+\lambda\Omega(\theta),

where Ω(θ)\Omega(\theta) penalizes a selected property of the parameters and λ≥0\lambda\geq0 controls its strength.

Common examples include:

TechniqueBasic ideaCaution
L2 penaltyDiscourages large parameter magnitudes through squared coefficientsFeature scaling often affects its behavior
L1 penaltyEncourages some coefficients to become zeroCan be unstable among highly correlated features
Tree pruning or depth limitsRestricts the detail a tree can modelToo much restriction causes underfitting
Early stoppingStops iterative training when a monitored criterion stops improvingThe monitored data must be separate from the fitting targets
DropoutRandomly deactivates units during neural network trainingMostly 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 kk-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:

  1. The target and deployment population are clearly defined.
  2. The evaluation metric matches the real task and error costs.
  3. Training, validation, and test partitions reflect deployment conditions.
  4. Preprocessing and feature selection are fitted only on allowed training data.
  5. Model performance is compared with meaningful baselines.
  6. Training and validation metrics are examined together.
  7. Hyperparameters are selected without using final test results.
  8. Errors are analyzed for important groups and operating conditions.
  9. The final reported test performance is distinguished from a guarantee of future reliability.
  10. Monitoring is planned if the deployment distribution can change.

13. Check your understanding

  1. Why is low training loss insufficient evidence that a model will work on new examples?
  2. What pattern in training and validation results commonly suggests underfitting?
  3. What is the generalization gap?
  4. Why might a deep decision tree overfit a small dataset?
  5. How does regularization differ from an optimizer?
  6. Why should scaling be fitted within each cross-validation training fold?
  7. Why is test-set tuning problematic?
  8. What is one reason that excellent held-out accuracy might not persist after deployment?
Show suggested answers
  1. The model may fit training-specific noise rather than a relationship that persists in unseen data.
  2. Both training and validation performance remain poor relative to a useful baseline.
  3. The difference between performance on training examples and previously unseen examples; it must be interpreted with the metric and sampling method.
  4. The tree can create many specific partitions that fit accidental fluctuations in the training sample.
  5. Regularization constrains or changes what is learned, while an optimizer is a method for estimating parameters under a specified objective.
  6. Fitting on held-out folds would let information from validation examples influence the transformation.
  7. It makes the test set part of development, biasing the reported estimate of generalization.
  8. The deployed inputs or targets may shift away from the distribution represented by the test set.

References and further reading

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.

Image preview

Fit