Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours on Instagram and YouTube and waste money on coffee and fast food, but won’t spend 30 minutes a day learning skills to boost our careers.
Master in DevOps, SRE, DevSecOps & MLOps!

Learn from Guru Rajesh Kumar and double your salary in just one year.

Get Started Now!

How to avoid overfitting in machine learning models

How to avoid overfitting in machine learning models
Machine Learning

Last updated: 27 November 2026

To avoid overfitting in machine learning, measure performance on data the model has not learned from, keep that evaluation free of leaks, and then limit how closely the model can fit noise. The main tools are better data, cross-validation, simpler models, regularization, early stopping and ensembles.

No single setting fixes every case. The right remedy depends on what your training and validation scores show, so start with diagnosis.

What overfitting is and why it happens

A model overfits when it learns details of the training set that do not hold for new data. Training results look strong, but results on unseen examples are clearly worse. Underfitting is the opposite problem: the model is too limited to capture the pattern, so it does poorly even on training data.

Google’s Machine Learning Crash Course points to two common causes, which can occur together:

  • The training data does not adequately represent real-world data, or the validation and test data.
  • The model is too complex.

A scikit-learn example makes the second cause concrete. It fits polynomials of degree 1, 4 and 15 to 30 noisy points taken from part of a cosine curve. The straight line underfits, degree 4 follows the true curve closely, and degree 15 chases the noise and produces a far larger cross-validated error.

How to detect overfitting

Compare training and validation scores

Training score Validation score Likely diagnosis First move
Low Low Underfitting Add capacity or better features, or relax regularization
High Much lower Overfitting Constrain the model or improve the data
High High Reasonable fit Confirm once on the test set

“High” and “low” depend on the problem. Compare against a simple baseline, such as always predicting the most common class or the mean value.

Read the curves

Three plots answer different questions:

  • Loss curves track loss over training iterations. If training loss keeps falling or levels off while validation loss starts to rise, the model is overfitting.
  • Validation curves vary one hyperparameter, such as tree depth, and show where the gap between training and validation scores opens.
  • Learning curves vary the number of training examples. They help you judge whether collecting more data is likely to pay off.

In scikit-learn, ValidationCurveDisplay and LearningCurveDisplay draw the last two directly.

Flowchart: split the data, train a pipeline with validation, compare scores, adjust for underfitting or overfitting and retrain, then evaluate once on the test set.
A workflow for diagnosing and reducing overfitting

Build an evaluation you can trust

Separate training, validation and test data

Training data fits the model. Validation data guides your choices. The test set is held back for a final estimate. If you keep adjusting the model after looking at test results, that score stops being an independent check.

Use cross-validation that matches your data

In k-fold cross-validation, the training data is split into k parts. Each part serves once for validation while the model trains on the others, and you average the scores. It does not prevent overfitting by itself, but it gives a steadier view than one split, especially with limited data.

Data situation scikit-learn splitter Reason
Independent, similar examples KFold with shuffling Simple general-purpose choice
Imbalanced classes StratifiedKFold Keeps class proportions in each fold
Repeated patients, users or devices GroupKFold Keeps one group out of both sides of a split
Time-ordered records TimeSeriesSplit Validates on data later than the training data

Do not randomly shuffle time-ordered or otherwise dependent samples. Doing so can inflate scores.

Stop data leakage

Leakage happens when model building uses information that would not be available at prediction time. It can hide overfitting completely.

The scikit-learn documentation shows this with random features and random labels, where accuracy should be about 0.5. Selecting features on the full dataset before splitting produced 0.76. Selecting them from the training data only brought the result back to 0.5.

The same risk applies to scaling, imputation, dimensionality reduction and similar steps. Split first, then fit every transformation on training data only. A pipeline does this inside each fold. The code below has not been tested here, and it assumes numeric features in X_train and class labels in y_train.

from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

pipe = make_pipeline(
    SimpleImputer(),
    StandardScaler(),
    LogisticRegression(max_iter=1000),
)

search = GridSearchCV(
    pipe,
    {"logisticregression__C": [0.001, 0.01, 0.1, 1, 10]},
    cv=5,
)
search.fit(X_train, y_train)
print(search.best_params_, search.best_score_)

Account for tuning bias

The best score from a hyperparameter search is optimistic because you chose the settings to maximize it. Report performance on the untouched test set. When data is scarce, consider nested cross-validation: an inner loop tunes the model and an outer loop estimates how well the whole tuning process generalizes.

Techniques that reduce overfitting

Technique What it does Typical use Trade-off
More representative data Makes noise harder to memorize Any model Collection and labeling effort
Data augmentation Creates label-preserving variations Images, audio, some text Bad transforms distort labels
Fewer or better features Removes chances to fit coincidences Many features, few rows May discard useful signal
L2 or L1 regularization Penalizes large weights Linear models, neural networks Too much causes underfitting
Tree limits and pruning Restricts tree growth Decision trees May miss fine structure
Bagging, random forests Averages varied models Unstable learners More compute, harder to interpret
Early stopping Halts before further fitting hurts Boosting, neural networks Needs reliable validation data
Dropout Randomly zeroes units in training Neural networks Rate needs tuning

Improve the data first

Remove duplicates that cross your splits, check suspicious labels, and make sure the training examples cover the conditions the model will face. More data helps most when the training score is well above the validation score. If both curves have already converged at a poor level, more of the same data is unlikely to help.

Apply regularization

Regularization adds a complexity penalty to the training objective. L2 regularization penalizes squared weights, pushing them toward zero without usually making them exactly zero. L1 regularization can set some weights to zero, which also acts as feature selection.

Watch the parameter’s direction. A larger regularization rate, often called lambda, means a stronger penalty. In scikit-learn’s LogisticRegression, C is the inverse: smaller values regularize more. L2 regularization is applied there by default.

For neural networks trained with Adam, note that L2 regularization and weight decay are not equivalent. The AdamW method separates weight decay from the gradient-based update.

Control tree-based models

An unrestricted decision tree can grow until it memorizes the training set. In scikit-learn, limit it with max_depth or min_samples_leaf, or prune it with ccp_alpha, where larger values prune more.

Random forests reduce variance by training trees on bootstrap samples, considering random feature subsets at splits, and averaging the results.

Gradient boosting adds trees sequentially, so control the learning rate, tree size and number of iterations. A smaller learning rate generally needs more trees. In scikit-learn’s histogram-based gradient boosting estimators, early stopping is on by default when there are more than 10,000 samples.

Regularize neural networks

Early stopping ends training when validation performance stops improving. Dropout randomly sets units to zero during training and is inactive at inference. Keras scales the surviving values during training to compensate.

This untested Keras sketch combines both with weight decay for a binary classifier. It assumes you have prepared separate training and validation arrays. The values are starting points to tune.

import keras
from keras import layers

model = keras.Sequential([
    keras.Input(shape=(X_train.shape[1],)),
    layers.Dense(64, activation="relu"),
    layers.Dropout(0.3),
    layers.Dense(1, activation="sigmoid"),
])

model.compile(
    optimizer=keras.optimizers.AdamW(learning_rate=0.001, weight_decay=0.01),
    loss="binary_crossentropy",
)

stop = keras.callbacks.EarlyStopping(
    monitor="val_loss", patience=5, restore_best_weights=True
)

model.fit(X_train, y_train, validation_data=(X_val, y_val),
          epochs=200, callbacks=[stop])

Hands-on exercise: shrink the gap

This exercise uses synthetic data with some randomly assigned labels. The code has not been tested here, so no expected scores are given.

from sklearn.datasets import make_classification
from sklearn.model_selection import (
    GridSearchCV, StratifiedKFold, cross_validate, train_test_split)
from sklearn.tree import DecisionTreeClassifier

X, y = make_classification(
    n_samples=1000, n_features=30, n_informative=5,
    flip_y=0.1, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)

tree = DecisionTreeClassifier(random_state=42)
base = cross_validate(tree, X_train, y_train, cv=cv,
                      return_train_score=True)
print("full tree:", base["train_score"].mean(), base["test_score"].mean())

grid = {"max_depth": [2, 3, 5, 8, None],
        "min_samples_leaf": [1, 5, 20],
        "ccp_alpha": [0.0, 0.001, 0.01]}
search = GridSearchCV(tree, grid, cv=cv, return_train_score=True)
search.fit(X_train, y_train)

i = search.best_index_
print(search.best_params_)
print("tuned:", search.cv_results_["mean_train_score"][i], search.best_score_)

# Run once, after all choices are final
print("test:", search.score(X_test, y_test))

In the output, test_score from cross_validate means the validation-fold score, not your held-out test set. Check whether tuning narrows the train-validation gap and improves validation accuracy. Then, as a follow-up, swap in a random forest and compare using cross-validation only. Because you will already have seen the test score, use fresh data for an unbiased final check of any new choice.

Common mistakes and troubleshooting

  • Judging by training accuracy: it says little about performance on new data.
  • Preprocessing before splitting: move every fitted step into a pipeline.
  • Oversampling before splitting: resample only the training portion of each fold.
  • Validation score far above reality: look for leakage, duplicates, shared groups or random splits of time-ordered data.
  • Scores vary widely between folds: the dataset or folds may be too small, or subgroups may differ. Report the spread, not only the mean.
  • Both scores fall after a fix: you may have over-regularized. Ease the constraint.
  • Good test results but weak production results: check whether the data has changed. Generalization is more likely when training, test and real-world data share a similar, stable distribution.

Best-practice checklist

  1. Set aside test data using a split that reflects real use.
  2. Build a simple baseline.
  3. Put preprocessing and the model in one pipeline.
  4. Compare training and validation results.
  5. Change one major factor at a time and record the effect.
  6. Prefer the simpler model when performance is effectively similar.
  7. Evaluate the final choice on the test set, then monitor it after deployment.

FAQ

Can overfitting be eliminated completely?

You cannot guarantee that. You can reduce it, measure the remaining gap honestly and keep checking performance on new data.

Is any train-validation gap a problem?

No. Some gap is common. Focus on validation performance and whether it meets your needs. A smaller gap is not helpful if both scores become poor.

Does more data always fix overfitting?

No. It often helps a high-variance model, but unrepresentative data, leakage and systematic labeling errors will not disappear just because the dataset grows.

Which technique should I try first?

Verify the splits and rule out leakage. Then try the most direct constraint for your model: stronger regularization for linear models, depth or leaf limits for trees, and early stopping for neural networks.

Related reading

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
0
Would love your thoughts, please comment.x
()
x