Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Concept · 20 min · revision 2

Underfitting, Overfitting and Learning Curves

Read training and validation error to tell underfitting from overfitting, measure bias and variance directly on a simulated problem, and use learning curves to decide whether more data, a more flexible model or a simpler one will help.

Contentsand lesson path

What you will learn

  • Diagnose underfitting and overfitting from training versus validation error and learning curves, and explain the bias-variance trade-off.

Prerequisites: Data Handling

01. Why it matters

When a model is not good enough, there are many things you could try: collect more data, add features, pick a more flexible model, add regularisation, train longer. Each costs time, and half of them make some problems worse. Collecting ten times more data does nothing for a model that is too simple to capture the pattern; adding flexibility hurts a model that is already memorising noise.

Two numbers, training error and validation error, plus one plot, the learning curve, tell you which situation you are in. This lesson builds that diagnosis on a problem where the true answer is known, so you can see the effects directly. The code uses Python 3.12, NumPy 2.5, scikit-learn 1.9 and Matplotlib 3.11.

02. Training error, validation error and model flexibility

Training error measures how well a model fits the rows it learned from. Validation error measures how well it predicts rows it has not seen, which is what you care about. The gap between them shows how much the model has learned things that are true only of its training sample.

The demo uses data where the truth is known: y = sin(2πx) plus random noise with a standard deviation of 0.3. The noise variance, 0.3² = 0.09, is the irreducible error: no model can predict random noise, so no model can get a validation MSE below about 0.09 on average. The models are polynomial regressions of degree 1, 4 and 15. A higher degree means a more flexible curve, with more coefficients to fit. Save data.py, which the other scripts import.

Python · data.py
import numpy as np


def make_data(n, seed):
    """y = sin(2*pi*x) plus noise with standard deviation 0.3."""
    rng = np.random.default_rng(seed)
    x = rng.uniform(0, 1, n)
    y = np.sin(2 * np.pi * x) + rng.normal(0, 0.3, n)
    return x.reshape(-1, 1), y


def poly_model(degree):
    from sklearn.linear_model import LinearRegression
    from sklearn.pipeline import make_pipeline
    from sklearn.preprocessing import PolynomialFeatures, StandardScaler

    return make_pipeline(
        PolynomialFeatures(degree), StandardScaler(), LinearRegression()
    )
Python · degree.py
from sklearn.metrics import mean_squared_error

from data import make_data, poly_model

X_train, y_train = make_data(30, seed=1)
X_val, y_val = make_data(1000, seed=2)       # a large validation set: a stable score

print("degree  train MSE  val MSE")
for degree in [1, 4, 15]:
    model = poly_model(degree).fit(X_train, y_train)
    train = mean_squared_error(y_train, model.predict(X_train))
    val = mean_squared_error(y_val, model.predict(X_val))
    print(f"{degree:6d} {train:10.3f} {val:8.3f}")
Expected output
degree  train MSE  val MSE
     1      0.272    0.308
     4      0.077    0.098
    15      0.049    0.142

Read the three rows as three diagnoses.

  • Degree 1 underfits. A straight line cannot follow a sine wave, so it is wrong on the training data (0.272) and about equally wrong on new data (0.308). Both errors are high and close together.
  • Degree 4 fits well. Both errors are low and close, and the validation error (0.098) is near the noise floor of 0.09.
  • Degree 15 overfits. It has the lowest training error (0.049), below the noise level, which means it has bent its curve to pass near individual noisy points. Its validation error (0.142) is higher than degree 4: the extra flexibility was spent on noise.

So the rule of thumb is: high training error means underfitting; low training error with a much higher validation error means overfitting. One warning in the other direction: a validation error far below the training error is not a good sign. It usually means the validation rows are easier than the training rows, or that information about them leaked into training.

03. Bias and variance, measured

The two kinds of failure have names. Imagine training the same kind of model on many different training sets drawn from the same source.

  • Bias is how far the average of those models is from the truth. A straight line is wrong for a sine wave whatever data you give it, so it has high bias.
  • Variance is how much the models differ from each other. A degree-15 polynomial changes shape dramatically with each new sample of 30 points, so it has high variance.

For squared error, the expected validation error splits into bias² + variance + irreducible noise. You cannot usually measure these on real data, because you get only one training set. In a simulation you can: the script trains each model on 200 different training sets of 30 rows and compares the predictions at 50 fixed points.

Python · bias_variance.py
import numpy as np

from data import make_data, poly_model

x_grid = np.linspace(0.05, 0.95, 50).reshape(-1, 1)
truth = np.sin(2 * np.pi * x_grid.ravel())

for degree in [1, 4, 15]:
    preds = []
    for seed in range(200):                  # 200 different training sets of 30 rows
        X, y = make_data(30, seed=100 + seed)
        preds.append(poly_model(degree).fit(X, y).predict(x_grid))
    preds = np.array(preds)                  # shape (200, 50)
    bias_sq = np.mean((preds.mean(axis=0) - truth) ** 2)
    variance = np.mean(preds.var(axis=0))
    print(f"degree {degree:2d}: bias² {bias_sq:7.3f}   variance {variance:9.3f}")
print("noise variance (irreducible): 0.090")
Expected output
degree  1: bias²   0.156   variance     0.021
degree  4: bias²   0.003   variance     0.018
degree 15: bias²   0.002   variance     5.213
noise variance (irreducible): 0.090

Degree 1 has a large bias² (0.156) and a small variance: its predictions are consistently wrong. Degree 15 has almost no bias, but its variance is enormous, because a few of the 200 fits swing wildly between the training points. Degree 4 keeps both small. This is the bias-variance trade-off: making a model more flexible usually lowers bias and raises variance, and the best flexibility for a given amount of data sits in between. More data shifts that balance, as the next section shows.

04. Learning curves

A learning curve plots training and validation error against the number of training rows. scikit-learn computes it with learning_curve: for each training size it fits the model on that many rows inside each cross-validation fold, and scores it on the fold that was held out. The script draws the curves for a degree-1 and a degree-12 polynomial, prints the averages and saves learning_curves.png.

Python · curves.py
import matplotlib
import numpy as np

matplotlib.use("Agg")
import matplotlib.pyplot as plt
from sklearn.model_selection import KFold, learning_curve

from data import make_data, poly_model

X, y = make_data(400, seed=3)
sizes = [20, 40, 80, 160, 320]
cv = KFold(5, shuffle=True, random_state=0)
fig, axes = plt.subplots(1, 2, figsize=(9, 3.5), sharey=True)
for ax, degree in zip(axes, [1, 12]):
    n, train, val = learning_curve(poly_model(degree), X, y, train_sizes=sizes,
                                   cv=cv, scoring="neg_mean_squared_error")
    train_mse, val_mse = -train.mean(axis=1), -val.mean(axis=1)
    print(f"degree {degree}:   n  train MSE  val MSE")
    for row in zip(n, train_mse, val_mse):
        print("          {:3d} {:10.3f} {:8.3f}".format(*row))
    ax.plot(n, train_mse, "o-", label="training")
    ax.plot(n, val_mse, "o-", label="validation")
    ax.set(title=f"degree {degree}", xlabel="training rows")
axes[0].set(ylabel="MSE", ylim=(0, 0.6))
axes[0].legend()
fig.savefig("learning_curves.png", dpi=100, bbox_inches="tight")
Expected output
degree 1:   n  train MSE  val MSE
           20      0.291    0.299
           40      0.298    0.279
           80      0.293    0.272
          160      0.265    0.273
          320      0.263    0.269
degree 12:   n  train MSE  val MSE
           20      0.042    3.510
           40      0.064    0.119
           80      0.073    0.101
          160      0.079    0.091
          320      0.084    0.090

The two shapes are the ones to recognise.

  • High bias (degree 1). The two curves meet early and stay together at about 0.27, far above the noise floor of 0.09. Adding rows from 80 to 320 changes almost nothing. More data cannot fix a model that cannot express the pattern; you need a more flexible model or better features.
  • High variance (degree 12). With 20 rows the gap is huge (0.042 against 3.510). As rows are added, training error rises slightly (it is harder to memorise more points) and validation error falls fast. At 320 rows the gap has almost closed at the noise floor. While the gap is still closing, more data is the most direct remedy; regularisation or a simpler model are the alternatives when data is expensive.

Training error that rises with more data is normal, not a bug. And when both curves have flattened together near the error you can accept, you have reached the limit of this model on this kind of data.

Turn the diagnosis into action:

  • Underfitting (both errors high, small gap): use a more flexible model, add informative features, reduce regularisation, or train longer if training stopped early.
  • Overfitting (large gap): get more training data, add regularisation (the next lesson), use a simpler model or fewer features, or stop training earlier.
  • Near the noise floor (both low and close): further gains need better data, such as cleaner labels or new kinds of features, not a different algorithm.

05. Check your understanding

Practice check · 3 questions

Diagnose the model

Use the patterns from this lesson.

Q1. A churn model has 14% training error and 6% validation error. What is the most reasonable next step?
Q2. Polynomial fits on one dataset give train/validation MSE of 0.40/0.42 (degree 2), 0.11/0.13 (degree 5) and 0.03/0.35 (degree 11). Which degree should you keep, and why?
Q3. In the learning curves of `curves.py`, the degree-12 training MSE rises from 0.042 at 20 rows to 0.084 at 320 rows. Why?
Practice only: not graded, not saved, not evidence.

06. Apply it

The practice project asks you to plot learning curves and argue which model generalises best. Do it for the models from the lab on your practice dataset.

  1. Use learning_curve with KFold(5, shuffle=True, random_state=0) for a regularised linear or logistic model and for k-NN with k = 1 and k = 25.
  2. Plot the curves side by side and label each as high bias, high variance or close to its limit.
  3. Write three sentences: which model you would choose, what would most likely improve it, and what evidence in the curves supports that.

07. Review prompt

Without looking back, describe the training and validation errors of an underfitting model and of an overfitting model; define bias and variance in terms of many models trained on different samples; sketch the learning curves of a high-bias and a high-variance model; and name two remedies for each situation and one that would make it worse.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check