How to Fix Overfitting and Underfitting: A Practical Model Tuning Guide
How to Fix Overfitting and Underfitting: A Practical Model Tuning Guide
Search
Ask the AI

How to Fix Overfitting and Underfitting: A Practical Model Tuning Guide

Training and validation scores provide diagnostic clues. A large gap prompts checks for overfitting; low scores on both sets prompt checks of capacity, features, and optimisation. Distribution changes, labels, and evaluation settings can also produce these patterns.

Use the decision-tree examples below to inspect complexity and scores, then combine split checks, regularisation, and error analysis to choose a tuning direction.

If you have just finished Model Training and Evaluation, this is the next step: moving from reading metrics to diagnosing a model.

1. What overfitting and underfitting mean

Overfitting is a model memorising the detail, and even the noise, in the training data. It shows up as a high training score alongside a clearly lower validation or test score.

Underfitting means the fitted model has not captured useful structure in the training objective. Limited capacity, excessive regularisation, or incomplete optimisation can contribute. Low training and validation scores also require checks of labels, features, and task difficulty.

One line to remember it by:

  • Training high, validation low: suspect overfitting first
  • Training low, validation low: suspect underfitting first
  • Training and validation both high: the model is currently in reasonable shape

2. Demonstrating model complexity with a decision tree

The original teaching code below compares tree depths. Although the variable is named X_test, repeatedly comparing depths on these rows makes them development validation data. Their score is not an independent final test of the selected model.

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier


X, y = load_breast_cancer(return_X_y=True)

X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=0.25,
    random_state=42,
    stratify=y,
)

for depth in [1, 2, 3, 4, 6, 10, None]:
    model = DecisionTreeClassifier(max_depth=depth, random_state=42)
    model.fit(X_train, y_train)

    train_score = model.score(X_train, y_train)
    test_score = model.score(X_test, y_test)
    print(f"max_depth={depth}: train={train_score:.3f}, test={test_score:.3f}")

Save it as decision_tree_depth_demo.py and run:

python decision_tree_depth_demo.py

You will normally see a shallow tree score poorly on training data, which indicates limited expressive power. As the tree gets deeper the training score rises, but the test score does not necessarily keep improving. That is the classic trade-off introduced by model complexity.

3. Telling overfitting apart from underfitting

Do not rely on a single test score. The more reliable diagnosis records the training score and the validation score together.

  • Underfitting clue: low training and validation scores prompt checks of capacity, optimisation, features, and labels
  • Overfitting clue: inspect a train–validation gap alongside evaluation mode, distribution, and leakage checks
  • Insufficient data: the training score fluctuates and the validation score is unstable, so you may need more samples or cross-validation
  • Wrong metric: accuracy is high but the business outcome is poor, which can mean class imbalance or asymmetric error costs

This is exactly why The Complete Machine Learning Workflow stresses splitting into training, validation and test sets. Without reliable evaluation there is no way to tell what has actually gone wrong with the model.

4. How to fix overfitting

The core problem in overfitting is that the model finds it too easy to memorise the training data. The usual directions are:

  • Reduce model complexity: limit tree depth, reduce the number of features, use a simpler model
  • Add regularisation: increase the regularisation strength on linear models; add weight decay or dropout on neural networks
  • Add more data: more samples reduce the chance of the model memorising incidental noise
  • Apply data augmentation: especially common in image, text and speech tasks
  • Use cross-validation: reduces the randomness of depending on a single split
  • Stop early: halt training once validation performance stops improving

To reduce tree complexity, lower max_depth or increase min_samples_leaf and min_samples_split. For logistic regression, a smaller C means stronger regularisation. Choose settings using development validation.

5. How to fix underfitting

The core problem in underfitting is that the model lacks expressive power, or the input features do not carry enough information. The usual directions are:

  • Move to a stronger model: from a linear model to a tree model, an ensemble or a neural network
  • Add meaningful features: bring in domain variables, interaction features or time-window features
  • Reduce excessive regularisation: regularisation that is too strong stops the model learning
  • Train longer: in deep learning tasks, too few epochs can cause underfitting
  • Check label quality: with heavy label noise, a model struggles to learn stable structure

Underfitting is not simply a matter of making the model bigger. If the raw features carry no information, a more complex model can only learn noise.

6. Using cross-validation to avoid misdiagnosis

Cross-validation displays performance across validation subsets. The retained full-data code below is a development comparison. Selecting a depth by these means makes that score part of selection. Use an isolated test set, or outer folds in nested cross-validation, to assess the selection procedure.

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score
from sklearn.tree import DecisionTreeClassifier


X, y = load_breast_cancer(return_X_y=True)

for depth in [2, 3, 4, 6, None]:
    model = DecisionTreeClassifier(max_depth=depth, random_state=42)
    scores = cross_val_score(model, X, y, cv=5, scoring="accuracy")
    print(f"max_depth={depth}: mean={scores.mean():.3f}, std={scores.std():.3f}")

To check the cross-validation result on its own, save this section as tree_cross_validation_demo.py and run:

python tree_cross_validation_demo.py

mean summarises the fold scores and std describes their spread. It is not the standard deviation of independent repeats, nor a direct standard error or confidence interval for final performance: training folds overlap.

A corrected runnable example separates depth selection from final evaluation. It checks every inner fold against the final row IDs. This public teaching dataset still does not constitute new independent validation.

"""A teaching split contract, not an independent new-data validation study."""
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, StratifiedKFold, train_test_split
from sklearn.tree import DecisionTreeClassifier

X, y = load_breast_cancer(return_X_y=True)
dev_ids, final_ids = train_test_split(
    np.arange(len(y)), test_size=0.25, random_state=42, stratify=y
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
folds = list(cv.split(X[dev_ids], y[dev_ids]))
for train, valid in folds:
    assert not set(dev_ids[train]) & set(dev_ids[valid])
    assert not set(dev_ids[train]) & set(final_ids)
    assert not set(dev_ids[valid]) & set(final_ids)
search = GridSearchCV(
    DecisionTreeClassifier(random_state=42),
    {"max_depth": [1, 2, 3, 4, 6, 10, None]},
    cv=folds, scoring="accuracy",
)
search.fit(X[dev_ids], y[dev_ids])
# Evaluate only after selecting and refitting on development data.
final_score = search.score(X[final_ids], y[final_ids])
print("chosen depth:", search.best_params_["max_depth"])
print("development/final rows:", len(dev_ids), len(final_ids))
print("final teaching score:", final_score)

7. Diagnosis table: identify the problem before tuning

Use the table as a checklist of diagnostic clues. The same score pattern can have several causes. Cross-validation checks and selects an approach; it does not itself regularise the fitted model.

Observation More likely problem First action What not to do first
Training high, validation low Overfitting Limit complexity, add regularisation, cross-validate Keep deepening the model
Training low, validation low Underfitting, or features carry no signal Add effective features, lower regularisation, move to a stronger baseline Only change the random seed
High mean, high std Unstable splits Add samples, use stratified sampling, use grouped cross-validation Report only the best single run
Accuracy high, recall low on the key class Metric mismatch or class imbalance Inspect the confusion matrix, macro F1 and per-class metrics Look at overall accuracy alone

8. A practical tuning order

Use the following order to examine changes one at a time:

  1. Confirm first that the data split has no leakage.
  2. Train a simple baseline model.
  3. Record the training score and the validation score.
  4. Decide whether this is underfitting or overfitting.
  5. Change one class of factor only, such as model complexity or regularisation.
  6. Inspect the gain across cross-validation folds and preserve the selection history.
  7. Run one final evaluation on an independent test set at the end.

This order records changes to the model, features, parameters, and data split separately, so the source of an improvement and its reproducibility can be examined.

9. FAQ

A validation score above the training score does not by itself indicate an error. Compare the same model snapshot, evaluation mode, preprocessing, and metric first. Dropout and training augmentation can make training-time observations harder, but disabling them does not guarantee improvement. Then inspect sample composition and the entity, time, and preprocessing boundaries.

Is 100% training accuracy always a good sign?

Not necessarily. If the validation or test score is clearly lower, 100% training accuracy may instead indicate that the model has overfitted. Read the training score and the validation score together.

Does a low test score always mean the model is not strong enough?

Not necessarily. The score may have dropped back after a data leak was corrected, the label quality may be poor, the training and test distributions may differ, or the evaluation metric may not suit the task.

Should features be removed when overfitting?

It can be worth considering, but do not delete blindly. Check first whether a feature leaks future information, whether it repeats a signal already expressed elsewhere, and whether it only holds in the training data. Keep features that carry business meaning and stay stable.

Can cross-validation replace a test set?

Inner cross-validation used for tuning cannot also serve as an independent final assessment of the chosen model. Hold out a test set, or use nested cross-validation, where outer data that did not participate in inner selection evaluates the whole procedure.

10. What to read next

Overfitting and underfitting are the core diagnostic method in machine learning tuning. To continue, return to A Small Python AI Practice Project and apply this diagnosis to a complete scikit-learn classification pipeline.

Leave a Reply

Scroll down