This is the idea behind overfittingWhen a flexible model follows the noise in its training data too closely, so its predictions on new data are poor., and it’s explained in section 2.2.2 of An Introduction
to Statistical Learning. It’s the reason a model
that looks perfect in testing can fail in production, and the reason three later posts
(baggingA general way to reduce a method's variance, used most with decision trees: fit on many bootstrap samples and combine., random forestsMany decision trees, each grown on a bootstrap sample, where every split may only choose from a random subset of the features., boostingCombining many trees grown one after another, each using what the earlier trees got wrong.) exist at all.
In the decision trees post, a fully grown tree scored a perfect
1.000 on the rows it trained on and 0.742 on test rows it had not seen (on a scale where 0.5 is
a coin flip). This post explains why, with a formula you
can actually measure.
The idea, with a person
Imagine two new risk analysts forecasting next month’s volatilityHow much an asset's price spikes and dips; most often measured as the standard deviation of its per-period returns..
Analyst A has one rule: “a jumpy month is followed by a jumpy month.” Simple, consistent,
and often wrong in the same way. That’s bias: a model too simple for the real pattern.
Analyst B remembers every single month they’ve ever seen and predicts from the most
similar one. Give B a different few years of history, and B’s forecasts change completely.
That’s varianceA measure of how much a quantity varies around its mean value.: a model that reacts too much to the particular data it learned from.
A good analyst is in between: they learn the real pattern and ignore the one-off quirks.
The formula
For a model f^ trained on some data, the expected squared error on a new point x0
splits into three parts. This is equation 2.7 in An Introduction to Statistical Learning:
f̂, the model's predictionf and y, the truthbiasvariance
Table 1. Symbols in the bias-varianceGood test results need both low variance and low bias, and pushing one down easily pushes the other up. decomposition
Symbol
Meaning
f(x)
the true average answer at x, the real pattern
f^(x)
what our model predicts at x
E[f^(x)]
the model’s average prediction, if we could train it again and again on fresh samples
σ2
the variance of the noise: randomness in y that no model can predict
In words:
Bias2: how far the model’s average guess is from the truth. Too simple → large.
Variance: how much the model’s guess jumps around depending on the sample it trained on.
Too complex → large.
Noise: the part of the error that stays even with a perfect model.
The expectationThe probability-weighted average of a quantity over all the values it can take.E[⋅] here is over many different training samples. That is the thing to hold on to about variance. It is not a property of one trained model. It
measures how much the model would change if you had collected different data.
Measuring it
Usually you can’t measure bias and variance, because you don’t know the true pattern f(x).
With made-up data, you can. I invented a true curve for next month’s volatility as a function
of this month’s, shaped like the real SPY data in the
linear regression post: a gentle slope, plus a step up
once the market is already above about 25% (once markets are wild, they tend to stay wild). Then I added random
noise with a standard deviationThe square root of the variance, a measure of spread in the same units as the data. of 3 points (so σ2=9).
Then, for each tree depth, I repeated this 300 times: draw 80 fresh months, train a regressionA prediction problem whose answer is a number; when the answer is a category it is classification instead.
tree, record its predictions. That gives me 300 versions of each model, enough to measure its
average and its spread (Table 2).
Table 2. Bias2, variance and measured error by tree depth, simulated
Tree depth
Bias2
Variance
Noise
Bias2 + variance + noise
Measured error on new months
1
8.00
6.25
9.00
23.24
23.29
2
0.57
4.46
9.00
14.02
14.00
3
0.01
2.82
9.00
11.83
11.82
5
0.02
6.09
9.00
15.11
15.06
8
0.03
8.49
9.00
17.52
17.44
15
0.04
9.11
9.00
18.14
18.21
Two things to see. First, the formula works: the three parts add up to the error I measured
directly on new months, to within simulation noise. Second, the trade-off, drawn in Figure 1:
Figure 1. Bias, variance and total error by tree depth, and the fitted trees
Depth 1 (blue on the right): a single question. Every version gives the same kind of flat
steps, with the cut-off landing in a different place each time, and all of them miss the shape of the curve. High bias.
Depth 15 (red): every version zig-zags through its own noise, and no two agree. Bias is
almost zero, because on average they follow the curve, but each one alone is far off. High
variance.
Depth 3 gives the lowest total error here. Not the most flexible model, not the simplest.
Three questions are enough to place the step and the slope on either side of it.
A detail I did not expect: depths 1 and 2 have more variance than depth 3. With so few splits, where
the cut-offs land jumps around a lot between samples. The general trend (more depth, more
variance) holds after that.
Overfitting and underfitting
These are the everyday names (Table 3):
Table 3.UnderfittingWhen a model is too simple for the data, the opposite end from overfitting, so its test error is high. against overfitting
Item
Underfitting
Overfitting
Cause
Model too simple
Model too complex
Main error
Bias
Variance
Training error
High
Very low
Error on new data
High
High
Fix
More flexible model, better features
Simpler model, more data, or averaging
The tell-tale sign of overfitting is a big gap between training error and error on new data,
like the decision treeA model that splits the inputs into simple regions with splitting rules drawn as a tree, and predicts from the training rows in each region. with a perfect 1.000 on training rowsThe observed examples a method learns from: they are used to teach it how to make its estimate. and 0.742 on test rows.
The same curve on real data
On the real version of the problem, predicting next month’s volatility from this month’s for
the five tickers, with one regression treeA decision tree that predicts a number: the average answer of the training rows in the same leaf. and the minimum rows per leaf swept from 1 to 200 (Table 4).
The score is RMSEThe square root of the mean squared error., the typical size of a miss in points of volatility; lower is better:
Table 4. Training and test RMSE by rows per leaf, one tree on real data
Rows per leaf
Training RMSE
Test RMSE
Reading
1
0.00
18.26
memorised: perfect on seen rows, worse than guessing the mean on new ones
5
8.35
15.40
already under the baseline of 17.69
20
11.36
13.35
the gap has closed to two points
50
12.53
12.90
the two curves have all but met
100
12.89
12.57
test now below training
200
13.31
12.40
the best of the table, and still falling
Training error rises the whole way. Test error falls the whole way too, and at 200 rows per
leaf (about 4% of the training rows) it is still falling, probably because this target is noisy enough that a
tree needs to average hundreds of rows before it says anything true. The right-hand side of the
U, where a too-simple tree blurs the real pattern, lies past the sizes swept here; the bagging
post shows what happens when averaging, not leaf size, does the smoothing. Read any model from
the two numbers (Table 5):
Table 5. Reading a model from its training and test error
Training error
Test error
Diagnosis
Fix
high
high, and similar
underfit, bias
a more flexible model, better features; a simpler one makes it worse
very low
much higher
overfit, variance
a simpler model, a penalty on the weights (ridge, lasso), more or more representative data
low
low, and similar
good
test once and stop
Two rules of thumb that go with the curve. Choose the simplest model whose validation error
is within one standard errorRoughly how far an estimate is likely to be from the true value; it shrinks as you collect more observations. of the best (ISLP section 6.1.3 calls this the one-standard-error
rule; the standard error is how much the validation score itself would wobble with different
data), since a difference that small is noise. And remember that some
dials run backwards: in nearest neighboursPredict for a new point by finding the K closest training points and averaging their answers. a larger k is a simpler model, and in ridgeLeast squares with a penalty that shrinks the coefficients towards zero; a tuning parameter sets how strong the shrinking is. or
lassoLike ridge, it shrinks coefficients towards zero, but with a large enough penalty it sets some exactly to zero, so it also picks variables. a larger penalty is a simpler model, the opposite of tree depth and polynomial degree.
How to find the sweet spot in practice
You never know the true curve in real life, so you can’t compute bias and variance directly.
Instead:
Hold out data. Train on part of the history, test on the rest. Only the test score counts.
Cross-validationA way to estimate how a model will do on new data, using only the training data.. Split the data into, say, 5 parts. Train on 4, test on the 5th, rotate,
and average. More reliable than one split.
For time series, test forward in time. In finance, never test on dates before your
training data. Train on January to June, test on July. Otherwise the model quietly learns from
the future.
Tune complexity on validation data, a slice held back from training, or on cross-validation:
tree depth, number of featuresAn input variable a model uses to make its prediction; also called a predictor or an independent variable., and so on. Keep the real test setData the model never saw during training, used to check how well it predicts new cases. for one final check at the
end. A setting chosen by looking at the test score makes that score look better than the model
is, the subject of the scoring post.
And there’s a third option, which the bagging post builds on: keep the complex, low-bias model, but
reduce its variance by averaging many of them. If each deep tree zig-zags differently,
the average of many comes much closer to the real curve. That’s bagging.
Check yourself
A depth-15 tree has almost no bias. Why is its error on new months still high?
Its error is mostly variance. Each version zig-zags through its own noise, so they agree on
average but each one alone is far off: bias2 is 0.04 but variance is 9.11, and the measured
error is 18.21. Depth 3 balances the two and has the lowest error, 11.82.
How do training and test error tell you whether a model overfits or underfits?
An overfit model has very low training error and much higher test error. The one-row-per-leaf tree
scores 0.00 on training rows and 18.26 on test rows, worse than guessing the mean (17.69). An
underfit model has high training and test error that are similar, and a simpler model makes it
worse.
What does bagging do about a deep tree's errors, instead of making the tree simpler?
It keeps the complex, low-bias tree and reduces its variance by averaging many of them. Each deep
tree zig-zags differently, so the average of many comes much closer to the real curve.
The code
The simulation behind Table 2, complete, so it runs as pasted
(pip install numpy scikit-learn). true_curve is the made-up truth; each round draws 80 fresh
months (x is this month’s volatility, y next month’s), trains one tree, and records its
predictions at 200 test points. preds ends up with 300 rows, one per trained tree, which is
what makes bias and variance measurable:
import numpy as npfrom sklearn.tree import DecisionTreeRegressordef true_curve(x): """A made-up 'true' next-month volatility for this month's volatility x (both % a year): a gentle slope, plus a step up once the market is already above about 25%.""" return 6 + 0.45 * x + 8 / (1 + np.exp(-(x - 25) / 3))NOISE = 3.0 # spread of the random part no model can predictgrid = np.linspace(5, 45, 200) # 200 values of this month's volatility to test attruth = true_curve(grid) # known only because we made the curve uprng = np.random.default_rng(11)print("depth bias^2 variance noise sum measured error on new months")for depth in [1, 2, 3, 4, 5, 6, 8, 10, 15]: preds, errors = [], [] for _ in range(300): # 300 different training samples of 80 months each sample = np.random.default_rng(rng.integers(1 << 31)) x = sample.uniform(5, 45, 80) # this month's volatility y = true_curve(x) + sample.normal(0, NOISE, 80) # next month's: truth plus noise tree = DecisionTreeRegressor(max_depth=depth, random_state=0).fit(x.reshape(-1, 1), y) p = tree.predict(grid.reshape(-1, 1)) preds.append(p) y_new = truth + rng.normal(0, NOISE, len(grid)) # fresh months the tree never saw errors.append(np.mean((y_new - p) ** 2)) preds = np.array(preds) # 300 rows: one per trained tree bias2 = np.mean((preds.mean(axis=0) - truth) ** 2) # how far the AVERAGE tree is off variance = np.mean(preds.var(axis=0)) # how much the trees disagree print(f"{depth:5} {bias2:6.2f} {variance:8.2f} {NOISE**2:5.2f} " f"{bias2 + variance + NOISE**2:5.2f} {np.mean(errors):5.2f}")
It prints Table 2, number for number, including the depths left out of it (4, 6 and 10).
preds.mean(axis=0) averages the 300 trees at each test point (down the rows), and
preds.var(axis=0) measures how much they disagree there.
The scripts behind the charts and the real-data table