You fit a curve to 15 noisy points. A friend collects another 15 points from the same source and fits the same kind of curve. The two curves are not the same, because the two sets of points are not the same. Which curve do you trust? Neither exactly: each carries the accidents of its own 15 points. This lesson measures how much.
A very simple model gives nearly the same curve for both of you, but that shared curve can be wrong in the same way every time. A very flexible model follows each set of points closely, so your curve and your friend’s differ a lot, and each carries the noise of its own points. The first problem is called bias. The second is called variance. P3.A3 showed both failures on one data set (underfitting and overfitting). This lesson puts a number on each and shows how they add up.
A fitted prediction is a random variable
Fix one input . Suppose the world works like this.
- There is a true function that we do not know.
- A target is the true value plus noise: . The noise has mean and variance , and it is new every time a target is produced.
- A training set is a random draw of examples from this world. The model is fitted to it and gives a prediction .
In the simulations below only the noise is redrawn and the inputs stay fixed; the algebra is the same when the inputs are drawn too.
Draw another training set and the fitted prediction at changes. So is a random variable (P1.D2), and its randomness comes from the choice of training set. Two numbers describe it, using the mean and variance of P1.D4.
- The bias is where it is centred, compared with the truth: . A model with zero bias is right on average over training sets.
- The variance is how much it moves from one training set to the next: .
The third piece is not about the model at all: the target at has its own noise, with variance .
All the expectations here are over the random training set (and over the noise of a fresh target). You cannot see them in a single experiment, which is why the next section draws many training sets. By the law of large numbers (P1.D8), averages over many training sets come close to these expectations.
See it: many fits from resampled data
The widget below runs the thought experiment. The true curve is made up: . Each training set has points at fixed, equally spaced inputs, with fresh noise on the targets. The widget fits a polynomial of the chosen degree to each of training sets and draws all fitted curves on top of each other.
Things to try.
- Degree 0 to 1. All the faint curves lie almost on top of each other, so the variance is tiny. But their mean is far from the true curve, so the bias is large: the model cannot bend. More training sets do not help.
- Degree 9. The faint curves now fan out, especially near the ends, so the variance is large. Their mean is close to the true curve, so the exact bias is almost zero (the measured value shrinks towards it as grows). Each single fit chases its own noise.
- Move . The bias and the variance both depend on where you look. At degree 3 the exact bias² is about at and at , but only about at , where the mean fit happens to cross the true curve. The variance is also largest near the two ends: about at and , against at .
- Slide the number of training sets. With the “variance” is zero, because there is only one fit. The values in the first column of the table get steadier as grows and approach the exact column. With few sets the measured bias² is too big by about variance/, because the mean of a few fits is itself noisy, and the measured variance is a little too small. At the whole error of the one fit shows up as “bias²”. (The exact column is a formula for what very many sets would give; it does not depend on the sets drawn.)
- Raise the noise σ. The variance grows with . Compare (best degree 6) with (best degree 4) at : more noise favours simpler models. At the best degree is 6 for up to , 5 at and 4 from .
- Points per set. Going from to at degree 5 shrinks the fan of curves. The bias does not change.
The decomposition
For the squared error at the fixed input , with a fresh target (in the formulas, and stand for and ):
The expectation is over the training set and over the noise in the fresh target. Here is why it holds, one step at a time.
Step 1: split off the noise. Since , we have . Squaring gives
Step 2: take the expectation of each term. The first term gives , because has mean . For the middle term we assume that the noise of the fresh target is independent of the training set, and hence of . Then . So
Step 3: split the model’s own error. The remaining term is the expected squared distance of a random variable from the constant . P1.D4 showed that for any random variable and constant , . With and :
Together, steps 2 and 3 give bias² + variance + σ².
The independence in Step 2 is a real assumption. It holds when the fresh target is a new example that was not in the training set. If you measure the error on the training examples themselves, the noise in also went into , the cross term is not zero, and the formula no longer holds. That is another reason to measure error on held-out data (P3.A4).
From one input to the whole test set. A test example has an input as well as noise. If the test inputs are drawn from some distribution, take the average of the formula over , and call the left side , the expected test MSE:
with a constant noise level (if the noise level depends on , use its average). The “averaged over x” rows of the widget take the plain average over 101 equally spaced values of between and , which is the case where the test inputs are uniform on .
A small example you can do by hand
At one input, suppose the true value is . Over the possible training sets, the fitted value is with probability , with probability and with probability . The noise is with equal probability, so . (These numbers are made up to keep the arithmetic short.)
- The mean fit is , so the bias is and .
- The variance is .
- The total is .
Check it the long way: list all six combinations of fit and noise, square for each, and weigh by probability. Running the code confirms that the average is . The two pieces you can control (bias² and variance) add up to of the .
Bias falls, variance rises: the U
Now fix the setting of the widget ( points per set, so the noise is ) and change only the degree. Here are the exact averages over .
| degree | bias² | variance | total |
|---|---|---|---|
| 0 | 0.519 | 0.006 | 0.615 |
| 1 | 0.504 | 0.012 | 0.606 |
| 2 | 0.158 | 0.019 | 0.267 |
| 3 | 0.097 | 0.025 | 0.212 |
| 4 | 0.006 | 0.033 | 0.129 |
| 5 | 0.002 | 0.042 | 0.134 |
| 6 | under 0.001 | 0.054 | 0.144 |
| 7 | under 0.001 | 0.074 | 0.164 |
| 8 | under 0.001 | 0.118 | 0.208 |
| 9 | under 0.001 | 0.250 | 0.340 |
(“Total” is bias² + variance + σ².) Read the two columns separately. Bias² falls from to almost zero, because a more flexible family can come closer to the true curve. Variance rises from to , because the extra freedom is used to follow the noise of each training set. The total is the sum plus the constant , so it falls while bias is dropping faster than variance rises, and then climbs once variance takes over. Its lowest point here is degree , with .
The exact numbers belong to this made-up setting. The shape does not: bias falling and variance rising with flexibility is the usual pattern, and it is why test error against flexibility is often U-shaped (P3.A3 showed the U on one data set). It is a tendency, not a law. The degree where the total is lowest depends on the true curve, the noise and the number of points.
Two details are worth seeing in the table. Degrees 0 and 1 have almost the same bias here: the true curve goes up, down and up again, so a tilted line does hardly better than a flat one. And the variance climbs steeply at the end. With only points and degree , the polynomial has 10 free numbers, so it passes exactly through every training point (it interpolates them), and in the widget (click and set the degree to 9; the table above is for ) the exact average variance is , about 240 times the noise level .
The three pieces, one at a time
Noise, , is a floor. Take a model with zero bias and zero variance: it predicts exactly. Its expected squared error on a new target is still , because the target itself is plus noise that nobody could have predicted. No model, however good and however much data, gets below it for squared error. This is called irreducible error. In the widget’s chart it is the dashed line that the total never crosses. It also tells you when to stop: if your validation error is already close to a plausible noise level, a bigger model cannot help.
More data lowers variance and leaves bias alone. Variance comes from the fit following the noise of a particular training set, and with more points each point matters less. Bias comes from the family of curves not being able to match the truth, and more points do not change what the family can do. A simulation at degree 5 with 2000 training sets per row (the code below) gives:
| bias² | variance | |
|---|---|---|
| 10 | 0.0035 | 0.0736 |
| 15 | 0.0024 | 0.0415 |
| 30 | 0.0021 | 0.0194 |
| 60 | 0.0021 | 0.0095 |
Doubling roughly halves the variance. For a fit by least squares with parameters, that is a known result for fixed inputs and independent noise: the variance, averaged over the training inputs, is exactly (see the Go-deeper box below). This is why “get more data” is the standard cure for overfitting, and why it does little for underfitting.
A penalty or an average lowers variance. Two ways of reducing variance without simplifying the family are previewed here and taught later.
- Regularization (P3.A6) adds a penalty on large weights. It pulls the fit towards smoother curves, so it moves less from set to set, at the price of some bias. The code below does this for the degree-9 fit with a ridge penalty of strength (here the penalty is times the sum of squared coefficients of the same Chebyshev basis, intercept included, added to the sum of squared errors, so these values only make sense in this setup; P3.A6 sets this up properly; the numbers are simulated from 2000 sets, so the last digit can differ from the exact values): the variance drops from to at while bias² rises from to , so their sum falls from to . A penalty that is too strong () adds so much bias that the sum rises again to .
- Averaging (bagging, P3.B4). The widget’s pink curve, the mean of many fits, has far less spread than any one fit. If you could average models whose errors were independent, each with variance , the average would have variance and the same bias as one of them. You usually have only one training set, so bagging builds the different models from resampled copies of it. Those models are correlated, so the saving is smaller than . (If each model has variance and any two have correlation , the average has variance .)
Go deeper Why the variance of a least-squares fit is σ²p/n on average
For a linear least-squares fit with fixed inputs, the fitted values at the training inputs are , where is a fixed matrix (the “hat” matrix, which projects onto the span of the columns of the design matrix). Only is random, with independent noise of variance , so (using and ). The diagonal entries add up to the trace, which equals the rank . So the variance averaged over the training inputs is . This needs fixed inputs and independent noise of equal variance . It holds even if the model is wrong; a wrong model only adds bias. A polynomial of degree has . For and , a degree-3 fit has , and a degree-9 fit has . Running the code confirms these.
This is the average over the training inputs only. At other inputs, especially near the ends of the range, the variance can be much larger, which is why the widget’s average over all of gives and for these two degrees, not and . The formula also says what happens near : the model has as many knobs as data points, and the variance averaged over the training inputs reaches .
You cannot compute this from one data set
To get bias and variance you need the true function (to subtract it) and the ability to draw many training sets (to average over them). In real problems you have neither: one data set, and an unknown truth. The widget and the code in this lesson work because we made up and can simulate as many data sets as we like. In practice you do not measure bias and variance. You measure the total, on data that the model has not seen (P3.A4), and you use the picture to reason about what to try: a large gap between training and validation error suggests variance (more data, a simpler model or a penalty); a high error on both suggests bias (a more flexible model or better features). These are reasonable rules of thumb, not proofs.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The column “sum” is bias² + variance + , computed from the fits. The column “test” is the squared error measured directly against fresh noisy targets. The two agree to within about at each degree, as the decomposition says they should (they would match more closely with more training sets). In this run the average over confirms the table: bias² is at degree 1 and variance is at degree 9, as in the exact values.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Where the clean picture stops
Classification. The decomposition above is an identity for squared error. For a classifier scored by the 0–1 loss (right or wrong), there is no single standard way to split the error into bias, variance and noise that keeps the clean “add up” form. Several different decompositions have been proposed, and they are not equivalent, so you will see different definitions in different books. The intuition carries over: a stiff classifier is stable but can be systematically wrong, a very flexible one changes with the training set. But do not expect the formula to hold for classification accuracy. When a classifier outputs probabilities, scored by squared error on the probability (the Brier score), the squared-error argument above applies to those numbers (with a noise term that depends on the input).
Very large models. The U-shaped picture comes from models whose flexibility grows slowly and is tuned to the data. In modern machine learning, networks with far more parameters than training examples have been observed to fit the training data exactly and still do well on new data, and test error plotted against model size has been seen to rise and then fall again, a pattern called double descent. This has been reported in several kinds of models. It does not contradict the decomposition (the identity above still holds for squared error); it shows that variance does not have to keep rising with the number of parameters. The details are still an active area of research, so this lesson only names it; P4.24 shows it with a small experiment. P3.A3 and P3.A4 give the practical advice that still holds: judge a model on data it has not seen.
Common misunderstandings
Intuition
Think of many archers. Each learns from their own random set of practice shots, then shoots once. Bias is how far the centre of all the final arrows is from the bullseye. Variance is how spread out the arrows are. Noise is a bullseye that jitters by a random amount each round, so even an archer who aims at its average position misses by that jitter. The analogy breaks because an archer’s “shot” here is a whole fitted curve.
Math
At a fixed , with , , , and independent of the training set:
Average over for the expected test MSE. For least squares with parameters and fixed inputs, the variance averaged over the training inputs is . For models with variance and pairwise correlation , the average has variance .
Code
import numpy as np
# the whole experiment: draw many training sets, fit each, look at the fits at x0
fits = np.array([fit(draw_training_set())(x0) for _ in range(S)]) # pseudo-code
bias2 = (fits.mean() - f(x0)) ** 2 # needs the true f: only possible in a simulation
variance = fits.var() # spread of the fits
expected_mse = bias2 + variance + sigma**2The cells above are the runnable version.
Check your understanding
At one input, a model has bias² equal to and variance equal to , and the noise variance is . What is the expected squared error on a new target there?
The expected squared error is bias² + variance + . The value leaves out the noise, which the model cannot remove. The value is the noise alone, which would be the error only if bias and variance were both zero. The value adds the noise to the variance but forgets the bias.
A degree-5 polynomial fits well on average but changes a lot from one training set to the next. Which change lowers its variance without raising its bias?
With more examples each one has less influence, so the fit moves less between training sets, while the family of curves is the same, so the bias stays. A higher degree raises variance. A degree of 1 lowers variance but raises bias a lot for a curved truth. More noise in the targets raises variance and does nothing for bias.
Over thousands of training sets, a model's prediction at averages to exactly the true value , but individual predictions are often far above or below it. How would you describe the model at ?
Bias is the average prediction minus the truth, which is zero here. Variance is the spread of the individual predictions, which is large. High bias would need the average to be off. Zero variance would need every training set to give the same prediction.
A model has zero bias and zero variance at every input, so its prediction is exactly . For targets with noise variance , what is its expected squared error on new targets?
Nothing can predict the noise, so even the exact misses each target by , and the average of is . The error is zero only when there is no noise. There is no factor of 2 in the decomposition. The value has the wrong units: squared error is in squared units, like .
Which statement about the decomposition is correct?
The derivation uses the square and the mean, which is why it fits squared error. For 0–1 loss several different decompositions exist and they do not agree. Computing bias needs the true function and many training sets, and one data set gives neither. Very large models have been observed to have test error that falls again, so rising forever is not implied.
Exercises
- At one input the true value is . The fitted value is or , each with probability over training sets, and the noise variance is . Find the bias, the variance and the expected squared error.
Show answer
The mean fit is , so the bias is and bias² is . The variance is . The expected squared error is . - Using the table of this lesson (n = 15, σ = 0.3), which degree has the lowest total? Why is the degree with the lowest bias² (degrees 7 to 9) not the best?
Show answer
Degree 4, with total . From degree 5 on, bias² is already below , so there is almost nothing left to gain, while the variance keeps rising ( at degree 4, at degree 5, at degree 9). The total grows with it. - Four models each have variance . What is the variance of their average if their errors are independent? What if each pair has correlation ?
Show answer
Independent: . With : . Correlated models share their errors, so averaging helps much less. - In the widget, set and compare with . Does the degree with the lowest total move up or down? Explain.
Show answer
It moves up: the exact totals at are lowest at degree 6 (, against at degree 4), while at it is degree 4. Variance is proportional to , so with less noise a flexible model pays a smaller variance price for each extra degree, and the bias savings are worth more. The best degree rises as the noise falls. - A student says: “My model has training error and test error , so its bias is large.” Which of bias or variance does that pattern suggest more, and what would you try?
Show answer
A big gap between a tiny training error and a much larger test error suggests variance (overfitting). Reasonable things to try are more data, a simpler model or a penalty (P3.A6). This is a rule of thumb: it does not prove the diagnosis. - Code: in the second cell, change the degree from to in the “more data” loop. Does the bias² change with ?
Show answer
It stays near for every , because a straight line cannot follow this curve however many points it sees. The variance falls roughly in proportion to .
Next: P3.A6 takes the regularization idea previewed here and shows how an L2 or L1 penalty shapes the fit, and P3.B4 builds bagging and random forests on the averaging idea.