Velamuvi AIAcademy

Lesson 10 of 13 · Getting It Right

Bias and Variance

The bias-variance trade-off made simple: consistently wrong vs unpredictably wrong. Train models on different samples in Python and connect it to overfitting.

  • 5 min read
  • Beginner
  • Reviewed
In this lesson you will learn
  • Explain bias and variance with an everyday picture
  • Measure both by training a model on different samples
  • Connect high bias to underfitting and high variance to overfitting
  • Describe the trade-off and how to reduce each

Two ways to miss the target

Picture four archers. One hits tightly around the bullseye. One hits tightly, but always up and to the left. One is centred on the bullseye but scattered all over. The last is scattered and off-centre. Models make the same two kinds of mistake.

Low varianceHigh variance
Low biasAccurate and stable: the goalRight on average, but each model is different
High biasStable, but consistently wrongWrong and unstable

Measuring them

To see bias and variance, you need several versions of a model. The program below draws six different training samples from the same population (the true pattern is curved: y = 0.5x²), trains three kinds of model on each sample, and compares their predictions at x = 9, where the true value is 40.5:

Try it yourselfPython
import random

def truth(x):
    return 0.5 * x * x            # the real pattern (unknown to the models)

def sample(seed):
    rng = random.Random(seed)
    xs = [rng.uniform(0, 10) for _ in range(20)]
    return [(x, truth(x) + rng.uniform(-8, 8)) for x in xs]    # 20 noisy examples

def average_model(data, x):       # very simple: ignores x completely
    return sum(y for _, y in data) / len(data)

def line_model(data, x):          # simple: best straight line
    n = len(data)
    mx = sum(a for a, _ in data) / n
    my = sum(b for _, b in data) / n
    slope = sum((a - mx) * (b - my) for a, b in data) / sum((a - mx) ** 2 for a, _ in data)
    return my + slope * (x - mx)

def neighbour_model(data, x):     # very flexible: copy the closest example
    return min(data, key=lambda p: abs(p[0] - x))[1]

x = 9
print(f"Predicting at x = {x}. The true value is {truth(x):.1f}.\n")
for name, model in [("average", average_model), ("straight line", line_model), ("nearest neighbour", neighbour_model)]:
    preds = [model(sample(seed), x) for seed in range(6)]      # 6 different training sets
    mean = sum(preds) / len(preds)
    print(f"{name:<17} predictions: {' '.join(f'{p:5.1f}' for p in preds)}")
    print(f"{'':<17} average {mean:5.1f} (off by {mean - truth(x):+5.1f}),  spread {max(preds) - min(preds):4.1f}")
  • Average: predictions are about 22 too low every time. That's high bias: ignoring x is a wrong assumption, and no amount of data fixes it.
  • Nearest neighbour: right on average (only 0.7 off), but predictions jump between 31 and 48 depending on which sample it saw. That's high variance.
  • Straight line: a little bias (a straight line can't follow the curve exactly) and the smallest spread. Here it's the best balance of the three.

The trade-off

Making a model more flexible usually lowers bias but raises variance; making it simpler does the opposite. The best model balances the two for the amount of data you have.

How to reduce each:

  • Reduce bias: a more flexible model, better features, fewer restrictions.
  • Reduce variance: more training data, a simpler model, regularisation, or averaging many models.

Common mistakes

Practice exercise

Measure bias (how far the average prediction is from the truth) and variance (how much predictions spread) for one model.

Your solutionPython
# Predictions for the same house from models trained on 5 different samples
predictions = [36, 44, 31, 47, 37]
true_value = 40

# Print three lines:
# Average: <mean of the predictions, 1 decimal>
# Off by: <average minus true value, 1 decimal, with a + or - sign>
# Spread: <largest minus smallest prediction>
Knowledge check

A model's predictions change a lot whenever it's trained on a different sample of data. Which problem does it have?

Summary

  • Bias is being consistently wrong because of wrong assumptions; it causes underfitting.
  • Variance is being unstable across training samples; it causes overfitting.
  • Flexible models have low bias and high variance; simple models the reverse.
  • Reduce variance with more data, simpler models or averaging many models; reduce bias with more flexibility or better features.

Next: how to measure a model's performance properly.

Finished reading? Tick it off to track your progress.