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

The bias-variance trade-off explained

The bias-variance trade-off explained with Python simulations: what bias and variance are, the error decomposition, and how model choices move each one.

By theprogrammers team · · 13 min read

Four friends practise darts. The first throws every dart into a tight cluster, but the cluster is in the top corner, far from the bullseye. The second's darts land all around the bullseye, but scattered across the whole board. The first is consistently wrong; the second is right on average but unreliable. In machine learning, the first player has high bias and the second has high variance.

The previous lesson showed that models fail by being too simple (underfitting) or too flexible (overfitting). The bias-variance trade-off explains why: every model's error on new data comes from bias, variance and unavoidable noise, and the choices that lower one usually raise the other. In this lesson you'll measure bias and variance directly with a Python simulation, see how they change with model complexity, and learn which tools reduce each one.

What you need first: overfitting and underfitting explained and statistics for machine learning, especially variance.

Key terms

  • Bias: how far the model's average prediction is from the truth. It comes from wrong assumptions, such as fitting a straight line to a curve.
  • Variance: how much the model's predictions change when you train it on a different sample of data. It comes from being too sensitive to the particular training set.
  • Irreducible error (noise): randomness in the data that no model can predict, such as a delivery held up by a surprise road closure.
  • Expected error: the average error you'd get if you trained the model on many different training sets and tested on new data.

Darts on a board

import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(3)
cases = [("Low bias, low variance", (0, 0), 0.15), ("High bias, low variance", (0.8, 0.8), 0.15),
         ("Low bias, high variance", (0, 0), 0.6), ("High bias, high variance", (0.8, 0.8), 0.6)]

fig, axes = plt.subplots(1, 4, figsize=(14, 3.8))
for ax, (title, centre, spread) in zip(axes, cases):
    for radius in [1.5, 1.0, 0.5]:
        ax.add_patch(plt.Circle((0, 0), radius, fill=False, color="#9ca3af"))
    ax.plot(0, 0, "x", color="black", markersize=10)
    throws = rng.normal(centre, spread, size=(12, 2))
    ax.scatter(throws[:, 0], throws[:, 1], color="#c2410c", s=25, zorder=3)
    ax.set_xlim(-1.8, 1.8)
    ax.set_ylim(-1.8, 1.8)
    ax.set_aspect("equal")
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_title(title, fontsize=11)
plt.suptitle("Each dart is a model trained on a different sample; the cross is the truth")
plt.tight_layout()
plt.show()
Four dartboards, each with a black cross at the centre and 12 orange darts. Low bias, low variance: darts tightly grouped on the centre. High bias, low variance: darts tightly grouped but in the upper right, away from the centre. Low bias, high variance: darts spread widely across the board but centred on the cross. High bias, high variance: darts spread widely and centred away from the cross.

Think of each dart as one model, trained on one random sample of data, making one prediction. Bias is how far the centre of the darts is from the cross. Variance is how spread out the darts are. You want both small, as in the first board.

Measure bias and variance with a simulation

In real life you have one training set. In a simulation you can make as many as you like, because you know the true pattern. Use the cold drinks sales wave from the previous lesson. Imagine the shop records its sales on the same 15 days, spread evenly through the year, in 200 different years. The days are the same every year; only the random day-to-day noise differs. Fit the same model to each year's data and look at how the predictions vary:

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression

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

noise_sd = 0.25
xs = np.linspace(0, 1, 100)                     # where we check the predictions

def predictions_from_many_samples(degree, n_samples=200, n_points=15):
    x = np.linspace(0, 1, n_points)              # the same days every year
    all_predictions = []
    for _ in range(n_samples):
        y = true_pattern(x) + rng.normal(0, noise_sd, n_points)
        model = make_pipeline(PolynomialFeatures(degree), LinearRegression()).fit(x.reshape(-1, 1), y)
        all_predictions.append(model.predict(xs.reshape(-1, 1)))
    return np.array(all_predictions)             # shape: (200 models, 100 points)

predictions = predictions_from_many_samples(degree=1)
print("shape:", predictions.shape)
shape: (200, 100)

Each row is one model's predictions across the year. From those 200 rows:

QuantityFormulaIn words
Average predictionmean over the 200 modelsWhere the darts land on average
Bias²(average prediction − truth)², averaged over xHow far the average is from the truth, squared
Variancethe variance of the 200 predictions, averaged over xHow much the models disagree
def bias_and_variance(predictions):
    average_prediction = predictions.mean(axis=0)
    bias_squared = np.mean((average_prediction - true_pattern(xs)) ** 2)
    variance = np.mean(predictions.var(axis=0))
    return bias_squared, variance

for degree in [1, 4, 12]:
    b2, var = bias_and_variance(predictions_from_many_samples(degree))
    print(f"degree {degree:2}: bias² = {b2:.4f}, variance = {var:.4f}")
degree  1: bias² = 0.2121, variance = 0.0084
degree  4: bias² = 0.0062, variance = 0.0180
degree 12: bias² = 0.0015, variance = 0.3257

The straight line (degree 1) has a large bias² of 0.212 but a small variance: every year's line looks much the same, and they're all wrong. Degree 4 has a tiny bias² (0.006) and a small variance (0.018). Degree 12 has almost no bias (0.0015) but a variance of 0.326, about 18 times degree 4's: on average it's right, but any one model can be far off.

See it: 20 models of each kind

fig, axes = plt.subplots(1, 3, figsize=(13, 4), sharey=True)
for ax, degree in zip(axes, [1, 4, 12]):
    predictions = predictions_from_many_samples(degree, n_samples=20)
    for row in predictions:
        ax.plot(xs, row, color="#c2410c", alpha=0.3)
    ax.plot(xs, predictions.mean(axis=0), color="#1f5fbf", linewidth=2.5, label="Average of 20 models")
    ax.plot(xs, true_pattern(xs), color="black", linestyle="--", label="Truth")
    ax.set_ylim(-2, 2)
    ax.set_title(f"Degree {degree}")
    ax.set_xlabel("Time of year")
axes[0].set_ylabel("Predicted sales")
axes[0].legend(loc="lower left")
plt.tight_layout()
plt.show()
Three charts, each with 20 thin orange curves (one per training sample), a thick blue average curve and a black dashed true sine wave. Degree 1: the orange lines are all similar straight sloping lines, and their blue average is a straight line that misses the wave. Degree 4: the orange curves are close together and their average lies almost on the wave. Degree 12: the orange curves spread wildly, especially near the edges, although their average stays roughly near the wave in the middle.
  • Degree 1: the 20 lines agree with each other (low variance), but they're all wrong in the same way (high bias).
  • Degree 4: the curves agree and follow the truth: low bias and low variance.
  • Degree 12: on average the curves are roughly right in the middle, but any single model can be far off, especially near the edges. That's high variance: the model you get depends heavily on the random noise in the one year of data you happened to collect.

The error decomposition

For squared error, the expected error on a new point splits exactly into three parts:

Expected error = Bias² + Variance + Irreducible error

Read it as "the average squared error equals the squared bias, plus the variance, plus the noise". The noise here is noise_sd² = 0.25² = 0.0625, and no model can do better than that. Check the formula by measuring the real test error of each model directly:

def expected_test_error(predictions):
    # error of every model against fresh noisy observations at the same points
    fresh_y = true_pattern(xs) + rng.normal(0, noise_sd, size=predictions.shape)
    return np.mean((predictions - fresh_y) ** 2)

print("degree   bias²     variance  noise    sum      measured")
for degree in [1, 4, 12]:
    predictions = predictions_from_many_samples(degree)
    b2, var = bias_and_variance(predictions)
    total = b2 + var + noise_sd ** 2
    print(f"{degree:6}   {b2:.4f}   {var:.4f}    {noise_sd ** 2:.4f}   {total:.4f}   {expected_test_error(predictions):.4f}")
degree   bias²     variance  noise    sum      measured
     1   0.2124   0.0066    0.0625   0.2815   0.2819
     4   0.0059   0.0174    0.0625   0.0858   0.0854
    12   0.0007   0.3627    0.0625   0.4259   0.4255

The sum of bias², variance and noise matches the measured test error to within a few thousandths for all three models: 0.2815 against 0.2819, 0.0858 against 0.0854, and 0.4259 against 0.4255. The small differences are just randomness in the simulation. Degree 1 loses mostly to bias, degree 12 mostly to variance, and degree 4 has little of either, so most of its error is the noise floor.

The trade-off curve

Repeat for every degree from 1 to 12:

degrees = range(1, 13)
bias_values, variance_values = [], []
for degree in degrees:
    b2, var = bias_and_variance(predictions_from_many_samples(degree))
    bias_values.append(b2)
    variance_values.append(var)
totals = np.array(bias_values) + np.array(variance_values) + noise_sd ** 2

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(degrees, bias_values, "o-", color="#1f5fbf", label="Bias²")
ax.plot(degrees, variance_values, "o-", color="#c2410c", label="Variance")
ax.plot(degrees, totals, "o-", color="black", label="Total expected error")
ax.axhline(noise_sd ** 2, color="grey", linestyle=":", label="Irreducible error")
ax.set_yscale("log")
ax.set_xlabel("Polynomial degree (model complexity)")
ax.set_ylabel("Error (log scale)")
ax.set_title("As complexity grows, bias falls and variance rises")
ax.legend()
plt.show()
print(f"lowest total error at degree {list(degrees)[int(np.argmin(totals))]}")
lowest total error at degree 3
Line chart on a log scale of bias squared, variance and total expected error against polynomial degree from 1 to 12. Bias squared, in blue, is high at degrees 1 and 2, drops sharply at degree 3 and again at degree 5, and stays far below the other lines after that. Variance, in orange, starts low and rises steadily, then steeply at degrees 11 and 12. The black total error follows bias on the left and variance on the right: it is lowest and almost flat from degree 3 to about 8, just above the dotted irreducible error line, and rises at both ends.

This is the picture behind the U-shaped test error in the previous lesson. On the left, bias dominates; on the right, variance does. The best model sits where their sum is lowest.

A real example: one tree vs a forest

You can't compute bias exactly on real data, because you don't know the truth, but you can measure variance: train on different samples and see how much the predictions disagree. Here, 30 decision trees and 30 random forests, each trained on a different random half of the California housing data, predict the same 500 houses:

Download the data: california-housing.csv (1.9 MB), or from the original source, the StatLib 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("california-housing.csv").

from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error

X, y = fetch_california_housing(return_X_y=True)        # house values in $100,000s
X_pool, X_check, y_pool, y_check = train_test_split(X, y, test_size=500, random_state=0)

def spread_of_predictions(make_model, repeats=30):
    predictions, errors = [], []
    for seed in range(repeats):
        X_half, _, y_half, _ = train_test_split(X_pool, y_pool, train_size=0.5, random_state=seed)
        model = make_model().fit(X_half, y_half)
        predictions.append(model.predict(X_check))
        errors.append(mean_squared_error(y_check, predictions[-1]))
    return np.mean(np.var(predictions, axis=0)), np.mean(errors)

for name, make_model in [
    ("deep tree   ", lambda: DecisionTreeRegressor(random_state=0)),
    ("shallow tree", lambda: DecisionTreeRegressor(max_depth=3, random_state=0)),
    ("forest      ", lambda: RandomForestRegressor(n_estimators=50, n_jobs=-1, random_state=0)),
]:
    variance, error = spread_of_predictions(make_model)
    print(f"{name}: variance {variance:.3f}, test MSE {error:.3f}")
deep tree   : variance 0.303, test MSE 0.624
shallow tree: variance 0.041, test MSE 0.783
forest      : variance 0.018, test MSE 0.337

The deep tree, with no depth limit, has a prediction variance of 0.303: retrain it on a different half of the data and its predictions for the same houses change a lot. The shallow tree (depth 3) is about seven times more stable (0.041), but it has the worst test error, 0.783, because it's too simple: high bias. The random forest averages 50 deep trees, which cuts the variance to 0.018 without adding much bias, so it has by far the best test error, 0.337. That's why forests beat single trees.

What lowers bias, what lowers variance

To lower bias (fix underfitting)To lower variance (fix overfitting)
A more flexible modelA simpler model
More or better featuresMore training data
Less regularisationMore regularisation
Deeper trees, more layersShallower trees, pruning, dropout
Boosting (adds models to fix errors)Bagging, random forests (average models)
Train longerEarly stopping

Most of these move along the trade-off: they lower one and raise the other. Two don't, which makes them especially valuable: more data lowers variance without adding bias, and averaging many models (as in a random forest) lowers variance with little extra bias. Better features can lower bias without much extra variance.

Common mistakes

  • Thinking bias is about fairness here. In this lesson, "bias" means systematic error from wrong assumptions. It's related to, but not the same as, unfair treatment of groups of people.
  • Thinking variance means the variance of the data. It means how much the model changes from one training set to another.
  • Trying to remove noise. Irreducible error can't be fixed by any model. Only better features (new information) can turn some of it into predictable signal.
  • Believing the trade-off is fixed. More data, ensembles and better features can lower total error without giving anything up.

Practice

  1. A model has a training error of 2 and a test error of 25. Is bias or variance the main problem?
Show the answer

Variance. The model fits the training data very well but changes a lot with the data it sees, so it does badly on new data. Reduce variance: more data, a simpler model, regularisation, or bagging.

  1. For each change, does it mainly lower bias or variance? (a) Going from linear regression to a degree-3 polynomial. (b) Increasing Ridge's alpha. (c) Training a random forest instead of one deep tree.
Show the answer

(a) Lowers bias: a more flexible model. (b) Lowers variance: a stronger penalty keeps the weights small, so the model is less sensitive to the sample. (c) Lowers variance: averaging many trees cancels out their individual quirks.

  1. Measure bias² and variance for degree 12 with 150 recorded days instead of 15. What changes?
Show the answer
b2, var = bias_and_variance(predictions_from_many_samples(12, n_points=150))
print(f"degree 12 with 150 days: bias² = {b2:.4f}, variance = {var:.4f}")
degree 12 with 150 days: bias² = 0.0000, variance = 0.0058

With 150 days, degree 12's variance falls from about 0.33 to 0.006, and its bias stays near zero. More data reduced variance without increasing bias: the same flexible model is now pinned down by the extra points.

  1. If a model's test error is 0.07 and the irreducible error is 0.0625, how much can a better model improve it?
Show the answer

At most 0.07 − 0.0625 = 0.0075. Bias² plus variance is already tiny, so effort is better spent on new features that add information than on a cleverer algorithm.

Interview questions

Explain the bias-variance trade-off.

A model's expected squared error on new data splits into bias squared, variance and irreducible noise. Bias is error from overly simple assumptions; variance is error from sensitivity to the particular training set. Increasing model complexity usually lowers bias but raises variance, so the best model balances the two, which you find with validation data or cross-validation.

Does a random forest reduce bias or variance? What about boosting?

A random forest mainly reduces variance: it averages many low-bias, high-variance deep trees trained on different bootstrap samples with random features. Boosting mainly reduces bias: it adds many shallow trees in sequence, each correcting the errors of the ones before, though too many rounds can raise variance.

How do you know whether your model has a bias or a variance problem?

Compare training and validation error. High training error with similar validation error points to bias. Low training error with much higher validation error points to variance. Learning curves, which plot both errors against the training set size, make the diagnosis clearer.

Key takeaways

  • Expected error = bias² + variance + irreducible error.
  • Bias is how far the average prediction is from the truth; variance is how much predictions change between training sets.
  • More complexity usually means less bias and more variance; the best model minimises their sum.
  • More data and averaging many models lower variance without much extra bias.
  • Irreducible error is a floor: only new information, not a better algorithm, can get below it.

Frequently asked questions

Is high bias the same as underfitting?

Yes, in practice. High bias means the model is too simple to capture the pattern, which shows up as underfitting: poor scores on training and new data. Likewise, high variance shows up as overfitting.

Does the bias-variance trade-off apply to deep learning?

The decomposition always holds, but very large neural networks often don't follow the simple U-shaped curve: with enough data and regularisation, test error can keep falling as models grow, a pattern called double descent. The practical tools, validation data, regularisation and more data, still apply.

Can you calculate bias and variance on a real dataset?

Not exactly, because you don't know the true function. You can estimate variance by retraining on bootstrap samples and measuring how much predictions change, as the housing example did, and you can judge bias from the training error.

What to learn next

  1. Learn the main tool for controlling variance in regularisation explained, the next lesson in this module.
  2. See averaging cut variance in random forest explained.
  3. Compare the two ways of combining models in bagging vs boosting.