Module 4 · Beginner · How models learn and why they fail

Overfitting and underfitting explained

Overfitting and underfitting in machine learning explained with Python: how to spot them from training and test scores, real examples, and how to fix each one.

By theprogrammers team · · 12 min read

Two students prepare for a maths exam. The first barely studies and gets most questions wrong, both the practice ones and the real ones. The second memorises every answer in the last five years' papers word for word: perfect marks on old papers, but when the exam asks a new question, they're lost. Neither student learnt maths. The first underfitted; the second overfitted.

Machine learning models fail in exactly these two ways, and recognising which one you're facing is one of the most useful skills in the field. This lesson explains overfitting and underfitting with charts you can reproduce, shows how to diagnose them from training and test scores on a real dataset, and lists the fixes for each.

What you need first: how machine learning models learn from data and train, validation and test sets. It helps to have seen polynomial regression.

Key terms

  • Underfitting: the model is too simple to capture the real pattern. It does badly on training data and on new data.
  • Overfitting: the model learns the noise and quirks of the training data as if they were the pattern. It does very well on training data and worse on new data.
  • Generalisation: how well a model does on data it hasn't seen.
  • Model complexity (or capacity): how flexible a model is, such as the degree of a polynomial or the depth of a tree.
  • Generalisation gap: the difference between the training score and the test score.

See it in a picture

A cold drinks shop's sales rise and fall through the year in a wave, plus random day-to-day noise. You have 30 days of data and fit polynomials of three degrees: 1 (a straight line), 4 (a gentle curve) and 15 (a very wiggly curve).

import numpy as np
import matplotlib.pyplot as plt
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression

rng = np.random.default_rng(1)

def true_pattern(x):
    return np.sin(2 * np.pi * x)

x_train = np.sort(rng.uniform(0, 1, 30))
y_train = true_pattern(x_train) + rng.normal(0, 0.25, 30)
x_test = rng.uniform(0, 1, 500)
y_test = true_pattern(x_test) + rng.normal(0, 0.25, 500)

def polynomial_model(degree):
    return make_pipeline(PolynomialFeatures(degree), LinearRegression())

xs = np.linspace(0, 1, 400)
fig, axes = plt.subplots(1, 3, figsize=(13, 4), sharey=True)
for ax, degree, name in zip(axes, [1, 4, 15], ["Underfitting", "A good fit", "Overfitting"]):
    model = polynomial_model(degree).fit(x_train.reshape(-1, 1), y_train)
    ax.scatter(x_train, y_train, s=18, color="#374151", label="Training days")
    ax.plot(xs, true_pattern(xs), color="#9ca3af", linestyle="--", label="True pattern")
    ax.plot(xs, model.predict(xs.reshape(-1, 1)), color="#c2410c", linewidth=2, label="Model")
    ax.set_ylim(-2, 2)
    ax.set_title(f"Degree {degree}: {name}")
    ax.set_xlabel("Time of year")
axes[0].set_ylabel("Sales (scaled)")
axes[0].legend(loc="lower left")
plt.tight_layout()
plt.show()
Three charts side by side showing 30 training points scattered around a grey dashed sine wave. Left, degree 1: the orange model is a straight sloping line that misses the wave completely. Middle, degree 4: the orange curve follows the wave closely. Right, degree 15: the orange curve wiggles sharply to pass close to individual points and swings far off the wave in places, especially near the edges.
  • Degree 1 can only draw a straight line, so it can't follow a wave at all. That's underfitting: the model is too simple.
  • Degree 4 follows the true wave and ignores the noise. That's what you want.
  • Degree 15 bends to chase individual points, including their random noise. That's overfitting: it has memorised these 30 days.

Spot it with numbers

You can't draw a chart for a model with 50 features, but you can always compare the error on training data with the error on new data:

from sklearn.metrics import mean_squared_error

print("degree   train MSE   test MSE")
for degree in [1, 4, 15]:
    model = polynomial_model(degree).fit(x_train.reshape(-1, 1), y_train)
    train_mse = mean_squared_error(y_train, model.predict(x_train.reshape(-1, 1)))
    test_mse = mean_squared_error(y_test, model.predict(x_test.reshape(-1, 1)))
    print(f"{degree:6}   {train_mse:9.3f}   {test_mse:8.3f}")
degree   train MSE   test MSE
     1       0.212      0.315
     4       0.043      0.081
    15       0.017   1896.524

Degree 1 has a high error on both training data (0.212) and test data (0.315): underfitting. Degree 4 has a low error on both (0.043 and 0.081): a good fit. Degree 15 has the lowest training error of all (0.017), below the noise floor, but a test error of 1,896: its wild swings between and beyond the training points make some predictions absurd. A low training error on its own tells you nothing.

The rule of thumb:

Training scoreTest scoreDiagnosis
BadBad, about the sameUnderfitting (high bias)
GoodGood, about the sameA good fit
Very goodClearly worseOverfitting (high variance)

The noise in this data has a variance of 0.25² = 0.0625, so no model can get a test MSE below about 0.06: that's the floor. A training error below that floor is a warning sign that the model has started fitting noise.

The complexity curve

Now try every degree from 1 to 15 and plot both errors:

degrees = range(1, 16)
train_errors, test_errors = [], []
for degree in degrees:
    model = polynomial_model(degree).fit(x_train.reshape(-1, 1), y_train)
    train_errors.append(mean_squared_error(y_train, model.predict(x_train.reshape(-1, 1))))
    test_errors.append(mean_squared_error(y_test, model.predict(x_test.reshape(-1, 1))))

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(degrees, train_errors, "o-", color="#1f5fbf", label="Training error")
ax.plot(degrees, test_errors, "o-", color="#c2410c", label="Test error")
ax.axhline(0.0625, color="grey", linestyle=":", label="Noise floor")
ax.set_yscale("log")
ax.set_xlabel("Polynomial degree (model complexity)")
ax.set_ylabel("MSE (log scale)")
ax.set_title("Training error keeps falling; test error falls, then rises")
ax.legend()
plt.show()
print(f"lowest test error at degree {list(degrees)[int(np.argmin(test_errors))]}")
lowest test error at degree 5

Degrees 3 to 6 are almost equally good (test MSE about 0.08), so the exact winner, degree 5, matters less than staying out of the two bad zones on either side.

Line chart of training and test error against polynomial degree from 1 to 15 on a log scale. The blue training error falls steadily as the degree rises, ending well below the dotted noise floor. The orange test error falls steeply from degree 1 to about degree 3 or 4, stays low for several degrees, then rises sharply at the highest degrees. The left side is the underfitting zone and the right side the overfitting zone.

This U-shaped test curve appears in almost every model family. On the left, the model is too simple (underfitting). On the right, it's too flexible for the amount of data (overfitting). The best model is at the bottom of the U, and you find it with validation data or cross-validation, never with the test set.

A real example: decision tree depth

The same thing happens with real data. Here is a decision tree spam filter on the Spambase emails, with depths from 1 to 25. The deeper the tree, the more questions it can ask, so the more complex it is:

Download the data: spambase.csv (1.1 MB), or from the original source, the UCI Machine Learning Repository. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with pd.read_csv("spambase.csv").

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

X, y = fetch_openml(data_id=44, as_frame=True, return_X_y=True)   # Spambase: 4,601 emails
y = y.astype(int)
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)

depths = range(1, 26)
train_acc, val_acc = [], []
for depth in depths:
    tree = DecisionTreeClassifier(max_depth=depth, random_state=0).fit(X_train, y_train)
    train_acc.append(tree.score(X_train, y_train))
    val_acc.append(tree.score(X_val, y_val))

for depth in [1, 3, 8, 25]:
    print(f"depth {depth:2}: train {train_acc[depth - 1]:.3f}, validation {val_acc[depth - 1]:.3f}")
print(f"best validation accuracy {max(val_acc):.3f} at depth {list(depths)[int(np.argmax(val_acc))]}")
depth  1: train 0.795, validation 0.782
depth  3: train 0.887, validation 0.893
depth  8: train 0.957, validation 0.921
depth 25: train 0.999, validation 0.917
best validation accuracy 0.928 at depth 15
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(depths, train_acc, "o-", color="#1f5fbf", label="Training accuracy")
ax.plot(depths, val_acc, "o-", color="#c2410c", label="Validation accuracy")
ax.set_xlabel("Maximum tree depth")
ax.set_ylabel("Accuracy")
ax.set_title("Spam filter: deeper trees memorise the training emails")
ax.legend()
plt.show()
Line chart of accuracy against maximum tree depth from 1 to 25. Training accuracy, in blue, rises steadily from about 0.79 to almost 1.0. Validation accuracy, in orange, rises quickly at first, levels off around 0.92 for medium depths, and then stays flat or dips slightly while the gap to the training line keeps growing.

The training accuracy climbs all the way to 0.999 at depth 25: the tree has almost memorised the 3,220 training emails. The validation accuracy tells a different story. It rises quickly to about 0.92 by depth 6, then stays roughly flat between 0.91 and 0.93, while the gap to training accuracy keeps widening. At depth 1 the tree underfits (0.795 and 0.782); from about depth 6 onwards, every extra level only adds memorisation. The best validation score, 0.928 at depth 15, is barely above depth 6's 0.921, and differences that small are mostly luck in which emails landed in the validation set.

How to fix underfitting

The model is too simple, or the features don't carry enough information. Make it more capable:

FixExample
Use a more flexible modelA tree ensemble instead of a straight line
Increase complexityHigher polynomial degree, deeper trees, more layers
Add better featuresDay of the week, distance to the city centre, ratios
Reduce regularisationLower alpha in Ridge, higher C in logistic regression or SVM
Train longerMore epochs for a neural network that hasn't converged

More data does not fix underfitting: a straight line stays a straight line however many points you give it.

How to fix overfitting

The model is too flexible for the amount of data. Make it simpler, or give it more data:

FixExample
Get more training dataOften the single best fix
Simplify the modelLower degree, max_depth or min_samples_leaf for trees
Add regularisationRidge or Lasso penalties; see regularisation explained
Remove useless featuresEach extra feature is one more thing to fit noise with
Average many modelsRandom forests average many overfitted trees
Stop training earlyStop a neural network when the validation error starts rising

Practice question 3 shows the first fix working: the same degree-15 polynomial behaves much better with more data.

Common mistakes

  • Only checking the training score. A model with 100% training accuracy may be badly overfitted. Always compare with validation data.
  • Tuning on the test set. Choosing the depth that scores best on the test set overfits to the test set. Use a validation set or cross-validation for choices, and the test set once.
  • Assuming a gap always means trouble. A small gap is normal. What matters is whether the validation score is as good as it can be.
  • Treating overfitting as a problem of the algorithm. The same algorithm can overfit 100 rows and fit 100,000 rows well. It's about complexity relative to the data.

Practice

  1. A model scores 0.99 accuracy on training data and 0.71 on validation data. Underfitting or overfitting? Name two fixes.
Show the answer

Overfitting: a big gap, with a near-perfect training score. Fixes: more data, a simpler model (shallower trees, fewer features), regularisation, or averaging models.

  1. A model scores 0.62 on training data and 0.60 on validation data, on a problem where others report 0.85. What's wrong?
Show the answer

Underfitting: both scores are low and close together. Use a more flexible model, add better features, or reduce regularisation. More data alone won't help.

  1. Fit the degree-15 polynomial again, but with 300 training days instead of 30. What happens to the test error?
Show the answer
x_big = rng.uniform(0, 1, 300)
y_big = true_pattern(x_big) + rng.normal(0, 0.25, 300)
model = polynomial_model(15).fit(x_big.reshape(-1, 1), y_big)
print(f"degree 15 with 300 days: test MSE {mean_squared_error(y_test, model.predict(x_test.reshape(-1, 1))):.3f}")
degree 15 with 300 days: test MSE 0.072

With ten times as much data, the same degree-15 model has a test MSE of 0.072, close to the noise floor of 0.0625, instead of 1,896. The model is just as flexible, but 300 points pin the curve down everywhere, so it has no room to wiggle. That's why more data is often the best cure for overfitting.

  1. For the spam decision tree, which depth would you choose, and why not depth 25?
Show the answer

A depth of about 6 to 8. Validation accuracy reaches about 0.92 there, and deeper trees don't do clearly better: depth 15's 0.928 is within the random variation between depths. A shallower tree is faster, easier to explain and less likely to fail on new emails. Depth 25 scores 0.999 on training data but only 0.917 on validation: it's memorised the training emails. To choose more reliably than with one validation split, use cross-validation.

Interview questions

What is overfitting and how do you detect it?

Overfitting is when a model learns noise and specifics of the training data instead of the general pattern, so it performs well on training data but poorly on new data. You detect it by comparing training performance with validation or cross-validation performance: a large gap, with high training performance, signals overfitting.

How do you prevent overfitting?

Collect more data, simplify the model or reduce its capacity, apply regularisation (L1, L2, dropout), use early stopping, remove irrelevant features, use ensembles such as bagging, and choose hyperparameters with cross-validation.

Can a model overfit and underfit at the same time?

In a sense, yes: it can be too simple in one part of the data and too complex in another, or fail to capture an important feature while fitting noise in others. The training-versus-validation comparison still guides you, but error analysis on different groups of examples shows where each problem is.

Key takeaways

  • Underfitting: too simple, bad on training and new data. Overfitting: too flexible, great on training data, worse on new data.
  • Diagnose by comparing the training score with a validation or cross-validation score.
  • As complexity grows, training error keeps falling while validation error falls and then rises: pick the bottom of that U.
  • Fix underfitting with more flexibility or better features; fix overfitting with more data, simpler models, regularisation or averaging.
  • Choose the complexity with validation data, never with the test set.

Frequently asked questions

Is overfitting or underfitting worse?

Overfitting is the more dangerous of the two, because the training results look excellent and can fool you into deploying a model that fails on real data. Underfitting is obvious from the start, because the training score is already poor.

What is a good gap between training and test accuracy?

There's no fixed number. A gap of a few points is normal, especially with small datasets. Compare models by their validation score, and treat a growing gap as a sign you've gone past the best complexity.

Does more data always reduce overfitting?

More data of the same quality almost always reduces overfitting, because noise averages out and the model has more real patterns to learn. It won't help an underfitting model, and more data from a different situation can bring its own problems.

What to learn next

  1. Understand the theory behind the U-shaped curve in the bias-variance trade-off explained, the next lesson in this module.
  2. See how penalties keep models simple in ridge and lasso regression.
  3. Revisit the role of the validation set in train, validation and test sets.