← All posts

Machine learning algorithms › Training and evaluation

What is overfitting? A gentle guide to models that memorize

What overfitting is, why a model that aces its training data can fail on new data, how to spot it with learning curves, and how to reduce it.

If you’ve trained a model, you may have seen this happen. The score on the training data is close to perfect, but on data the model hasn’t seen, it drops sharply. The explanation you’ll hear most often is overfitting. The word comes up more and more these days, partly because anyone can now train a model in a few lines of code, and partly because models have grown big enough to memorize their training data outright. In an ICLR 2017 paper, Chiyuan Zhang and colleagues showed that convolutional networks for image classification easily fit their training data even when the labels had been assigned at random.

Overfitting is when a model learns its training data so closely, chance noise and all, that it does well on that data but poorly on data it hasn’t seen before. Google’s Machine Learning Crash Course describes an overfit model in much the same way, as one that matches, or memorizes, the training set so closely that it fails to make correct predictions on new data. If instead the model is too simple to do well even on the training data, that’s called underfitting. What we actually want is generalization, doing well on data the model has never seen, and both problems stand in its way.

Fitting three curves to the same 30 points

Overfitting is easiest to understand when you watch it happen, so let’s cause it on purpose. The code below takes 30 points along one wave of a sine curve and adds noise to each, then draws 1,000 more points the same way and sets them aside as test data. The model never learns from the test data, so the score it gets there shows how it does on data it hasn’t seen.

The model is polynomial regression. PolynomialFeatures turns x into x, x², x³, and so on up to the chosen degree, and LinearRegression finds a weight for each of them. The higher the degree, the more the curve can bend, so degree 1 is a straight line and degree 12 can change direction up to 11 times. The setup is modeled on a scikit-learn example that fits degrees 1, 4, and 15 to 30 points from a cosine curve. The score is mean squared error (MSE), the average of the squared gaps between predictions and actual values, so lower is better.

import numpy as np
from sklearn.linear_model import LinearRegression, Ridge
from sklearn.metrics import mean_squared_error
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures

rng = np.random.default_rng(1)  # fixed seed: the same data on every run

def make_data(n):
    # x between -1 and 1; y is one wave of a sine curve plus noise (sd 0.3)
    x = rng.uniform(-1, 1, size=(n, 1))
    y = np.sin(np.pi * x[:, 0]) + rng.normal(0, 0.3, size=n)
    return x, y

X_train, y_train = make_data(30)  # the points the model learns from
X_test, y_test = make_data(1000)  # new points it never sees while learning

def errors(model, X=X_train, y=y_train):
    model.fit(X, y)
    train = mean_squared_error(y, model.predict(X))
    test = mean_squared_error(y_test, model.predict(X_test))
    return f"train {train:.3f}  test {test:.3f}"

for degree in (1, 4, 12):
    model = make_pipeline(PolynomialFeatures(degree), LinearRegression())
    print(f"degree {degree:2d}   {errors(model)}")
true_curve = np.sin(np.pi * X_test[:, 0])  # the real curve, without the noise
print(f"true curve  test {mean_squared_error(y_test, true_curve):.3f}")
degree  1   train 0.240  test 0.316
degree  4   train 0.058  test 0.109
degree 12   train 0.037  test 0.410
true curve  test 0.094

The straight line misses on both sets, with 0.240 on the training data and 0.316 on the test data. It’s too simple to follow the wave, and that’s underfitting. Degree 4, on the other hand, does well on both. Degree 12 has the lowest training error of the three, yet its test error of 0.410 is nearly four times that of degree 4.

The last line shows why. The noise I added is random, so even the true sine curve, used as is, scores 0.094 on the test data. When degree 12 pushes its training error down to 0.037, well below that floor, it has bent itself to follow the noise in these 30 points, and that memorized noise is what trips it up on new ones. More generally, as a model becomes more flexible, training error keeps falling, while test error falls only for a while and then climbs back up. That widening gap between the two is what overfitting looks like.

Why it happens, seen through bias and variance

Overfitting tends to show up when the model is very flexible for the amount of data, when there’s little data, and when the data is noisy. People usually describe this balance in terms of bias and variance. scikit-learn’s guide to validation and learning curves defines bias as a model’s average error over different training sets, and variance as how sensitive the model is to the training set it happened to get. In darts terms, high bias is a tight cluster of throws away from the bullseye, and high variance is throws scattered widely around it.

You can see both by repeating the experiment. The code below draws 200 new training sets of 30 points, fits each degree to every one of them, and reports the median and worst test error.

# 200 more training sets of 30 points; refit each degree on every one
sets = [make_data(30) for _ in range(200)]
for degree in (1, 4, 12):
    model = make_pipeline(PolynomialFeatures(degree), LinearRegression())
    tests = [mean_squared_error(y_test, model.fit(X, y).predict(X_test)) for X, y in sets]
    print(f"degree {degree:2d}   test  median {np.median(tests):.3f}  worst {max(tests):.3g}")
degree  1   test  median 0.308  worst 0.418
degree  4   test  median 0.116  worst 0.849
degree 12   test  median 0.877  worst 2.25e+07

Even at its worst, the straight line only reaches 0.418, so whichever 30 points it gets, it makes much the same mistake. That’s high bias. Degree 12, on the other hand, has a median of 0.877, and its worst, 2.25e+07, is about 22 million. In that set, the training points happened to stop at -0.834 and 0.758, and nearly all of the error came from beyond them, where the curve shot off. That’s high variance. Making a model more flexible lowers its bias but raises its variance, so the lowest test error lies somewhere in between. That’s why this is called the bias-variance trade-off.

How to notice it

The plainest sign is a gap between the training score and the validation score. Validation data is data you hold out to compare models and settings, kept apart from the final test data. The same guide reads the two scores this way: if both are poor, the model is underfitting, and if only the training score is high, it’s overfitting.

A learning curve shows how that gap changes as the training data grows. Let’s train the degree-12 model again on more and more points, from 30 up to 1,000. The first 30 are the same points as before.

# The same degree-12 model, trained on more and more points
X_more, y_more = make_data(970)
X_all, y_all = np.vstack([X_train, X_more]), np.concatenate([y_train, y_more])
for n in (30, 100, 300, 1000):
    model = make_pipeline(PolynomialFeatures(12), LinearRegression())
    print(f"n = {n:4d}   {errors(model, X_all[:n], y_all[:n])}")
n =   30   train 0.037  test 0.410
n =  100   train 0.076  test 0.124
n =  300   train 0.081  test 0.103
n = 1000   train 0.087  test 0.095

At 30 points the gap is wide, 0.037 against 0.410, but at 100 the two almost meet, and at 1,000 both sit close to the 0.094 floor. That’s because with more points, the curve can no longer pass through all of them, so it stops chasing the noise. When the two values come together like this, more data is the cure. When they meet at a high value, though, more data won’t help much. Sure enough, the straight line stayed at 0.274 and 0.291 even with 1,000 points.

Ways to reduce overfitting

Collecting more data is the most direct fix, though it isn’t always possible. The next is a simpler model, like going back from degree 12 to degree 4. For decision trees, that means limiting the depth with max_depth or requiring more samples in each leaf with min_samples_leaf, and scikit-learn’s decision tree guide lists both as ways to avoid overfitting.

Regularization keeps the flexible model but penalizes large weights. Ridge regression makes the sum of squared errors on the training data plus alpha times the sum of the squared weights as small as possible, so the larger alpha is, the more the weights shrink (Ridge). Let’s add it to degree 12 on the same 30 points.

# Back to the first 30 points: degree 12 with ridge regularization
for alpha in (0.0001, 0.01, 1, 10, 100):
    model = make_pipeline(PolynomialFeatures(12), Ridge(alpha=alpha))
    print(f"alpha {alpha:<6}   {errors(model)}")
alpha 0.0001   train 0.052  test 0.116
alpha 0.01     train 0.054  test 0.123
alpha 1        train 0.110  test 0.174
alpha 10       train 0.315  test 0.396
alpha 100      train 0.483  test 0.575

Even a tiny alpha of 0.0001 brings the test error down from 0.410 to 0.116, close to degree 4. The curve fits the training points a little less tightly and stays smooth in return. Of course, push alpha too far and underfitting arrives from the other side, so at alpha 100 the test error of 0.575 is worse than the straight line’s. Since x stays between -1 and 1, so do its powers, which is why I left out a step to scale the features.

That said, I looked at the test error only to show the shape. If you keep changing settings (hyperparameters) while watching the test score, what you learn about the test set seeps into your choices, and as scikit-learn’s cross-validation guide warns, that score no longer reports on generalization. So you choose settings with cross-validation, which splits the training data into several parts and takes turns holding one out for validation, and you look at the test data once, at the end. When I let RidgeCV and 5-fold GridSearchCV choose alpha from the 30 training points alone, both picked 0.1, with a test error of 0.135, far below 0.410. Data leakage inflates scores in a similar way: information that won’t be available at prediction time gets used to build the model, and fitting a scaler on all the data before splitting it is a common example (common pitfalls).

Early stopping is common too. It halts a model that learns step by step, such as boosting or a neural network, once the validation score stops improving. In scikit-learn 1.9.1, HistGradientBoostingRegressor turns it on by itself when there are more than 10,000 training samples (ensemble guide). Combining many models in an ensemble helps as well, and the same guide explains that random forests reduce variance by combining diverse trees. For neural networks, there’s dropout, which randomly switches off units during training so they can’t lean on each other too much (Srivastava et al., 2014).

Why simpler isn’t always better

Still, the simplest model isn’t always the safest. Alpha 100 above was simple enough to underfit, and very large models make the picture more complicated. In a 2019 PNAS paper, Mikhail Belkin and colleagues noted that models such as neural networks, trained to fit their training data exactly, often still do well on test data. They described a “double descent” curve, in which test error falls again as model capacity grows past the point where it fits the training data exactly. Later that year, Preetum Nakkiran and colleagues reported the same shape across a variety of deep learning tasks (Deep Double Descent). So whatever the size of the model, the error measured on data it hasn’t seen is still what you judge it by.

If you’re trying it for the first time

If you’d like to try this yourself, put the four code blocks into one file in order and run it. The later blocks keep drawing from the same random number generator, so running them in another order changes the numbers. Then change one thing at a time. When I cut the training set from 30 points to 15, degree 12’s training error fell to 0.008, while its test error jumped to about 12,400. If you’d like to see these curves as plots, scikit-learn’s validation curve guide has examples of validation_curve and learning_curve. I ran these examples on November 2, 2026, with Python 3.13.12, NumPy 2.5.4, and scikit-learn 1.9.1.

AI tools helped with the research for this post.