Part 3: Machine learning Lesson 17 of 20 in this part
Bias, variance and the limits of learning
What you will learn. Explain the two ways a model goes wrong (too simple, too flexible), read training and test error to tell which one you have, and know why more features and more data change the answer.
Before this lesson: How a model learns: loss, training and overfitting, Measuring models honestly. Already know these? Carry on.
In plain words
Every model makes mistakes for three reasons. First, it may be too simple to follow the real pattern. A straight line cannot follow a curve. That kind of mistake is called bias. Second, it may be too flexible: it follows the random wobble in the training data as if it were the pattern, so a different training sample gives a very different model. That kind of mistake is called variance. Third, the data itself has noise that no model can predict. Making a model more flexible lowers bias and raises variance. Your job is to find the middle, where the error on new data is lowest. You find it by watching two numbers together: the error on the training data and the error on test data.
Too simple (high bias)
- Misses the real pattern
- Error is high on training data and on test data
- Same model on every training sample
Too flexible (high variance)
- Copies the wobble in the training data
- Tiny training error, large test error
- Gives a different model on every training sample
Both models are wrong, in opposite ways. Neither is the one you want.
- InputLook at training errorIs it already high?
- ModelLook at test errorIs it much higher than training error?
- OutputChoose the fixHigh both: more flexible model. Big gap: simpler model or more data
The gap between the two errors, and the level of both, tell you what to do next.
Bias
- The model is too simple
- Fix: a more flexible model or better features
Variance
- Too sensitive to its training sample
- Fix: simpler model, more data, or averaging
Noise
- Randomness in the data itself
- No model can remove it
You can reduce the first two. You cannot reduce the third.
Real-world example
A delivery company predicts how long each delivery takes. Their first model is a single rule: "time = distance × 3 minutes". It is wrong in the same way every day, because traffic and stairs matter too. That is bias. Their second model asks about 200 details, such as the exact street and the weather hour by hour. It is nearly perfect on last year's deliveries and poor on this month's, because it memorised last year's accidents. That is variance. The model they ship sits in between, and they pick it by looking at error on deliveries the model never saw.
How it works
- Pick one dial that controls flexibility: tree depth, the number of neighbours, the degree of a curve, or the strength of regularisation.
- For each dial setting, train on the training rows and measure the error on both the training rows and the test rows.
- Read the pair. Both high: too simple. Training low and test high: too flexible. Both low and close: good.
- Compare the best test error with the noise floor: the error you would get from the random part alone. If you are close to it, stop tuning. More work on the model cannot help much.
Bias and variance can be seen with a tiny hand calculation. Suppose the true answer is 10. You train a model four times on four different training samples and look at what each trained model predicts for that one case.
- RiskFew training rowsTraining error is low, test error is high
- ProcessMore training rowsThe two errors move towards each other
- OutputMany training rowsIf both are high and close, more data will not help; make the model more flexible
Plot error against the number of training rows. The gap shows whether more data would help.
More features need many more examples
Adding features seems free: more information can only help. It is not free. With more features, the same number of rows covers a smaller and smaller share of the possible cases. This is the curse of dimensionality.
- InputAdd a featureMore information, if it is useful
- RiskThe data thins outFewer rows per combination of values
- ProblemVariance risesThe model fits chance patterns
Each new feature is only worth it if it carries real signal.
Two limits to remember
- No free lunch. No single model is best on every problem. A model works when its built-in assumptions (a line, a tree, similar inputs have similar outputs) fit the data. That is why you compare models on your own data and keep a baseline.
- Occam's razor. When two models perform equally well on test data, choose the simpler one. It is easier to explain, cheaper to run and less likely to be fragile.
Live simulation
Overfitting and underfitting are two ends of one dial. Turn the dial and watch both errors.
The question. Why does a more flexible model do better on training data but sometimes worse on new data?
What to watch
- The grey curve is the real pattern (a sine wave). The dots are noisy samples of it. The coloured curve is the polynomial fitted to the dots.
- Degree 1 is a straight line: too stiff to follow the wave (high bias). A high degree can pass through every dot and swing wildly in between (high variance).
- The second chart shows training error always falling, while the error on new points falls and then rises. Try more training points.
This simulation needs JavaScript, which is switched off or not loaded. The lists above say what it shows, and the example programs below print the same kind of numbers.
Try this
- With 15 points, choose degree 7 or more and make the error on new points more than 3 times the training error.
- Raise the training points to 50 or more at degree 7 or more, and bring the two errors within 1.5 times of each other.
What this leaves out. One input, a made-up sine pattern and polynomials only. Real models overfit in other ways (deep trees, many features), and the usual cures there include regularisation, simpler models and more data. Error on new points here uses a fresh made-up sample.
Python program that prints the same headline numbers: examples/sim-core/core.py.
Python example
Python: example run The example programme behind this lesson's quoted output ran on 2026-11-19 (Python 3.12.10). 1 code block in the lesson passed a syntax check, 1 also ran on their own.
The run below uses 60 points on a curve plus a repeatable wobble that stands in for noise. Even-numbered points train the model and odd-numbered points test it. The dial is the number of neighbours k that a k-nearest-neighbours model averages: k = 1 copies the nearest training point (very flexible), and k = 29 averages nearly everything (very simple).
import numpy as np
from sklearn.neighbors import KNeighborsRegressor
n = 60
i = np.arange(n)
x = (6 / 59) * i + np.where(i % 2 == 1, 0.013, 0.0) # the small offset avoids equal distances
y = np.sin(x) + 0.35 * np.sin(17.0 * i + 1.0) # curve plus wobble
train = i % 2 == 0
test = ~train
def rmse(a, b):
return float(np.sqrt(np.mean((a - b) ** 2)))
print("wobble alone (the error no model can remove): %.3f" % rmse(0.35 * np.sin(17.0 * i + 1.0), 0))
print("always predict the training average: test RMSE %.3f" % rmse(y[test], y[train].mean()))
print(" k train RMSE test RMSE")
for k in (1, 3, 5, 9, 15, 29):
model = KNeighborsRegressor(n_neighbors=k).fit(x[train].reshape(-1, 1), y[train])
print("%2d %10.3f %9.3f" % (k, rmse(y[train], model.predict(x[train].reshape(-1, 1))),
rmse(y[test], model.predict(x[test].reshape(-1, 1)))))wobble alone (the error no model can remove): 0.249
always predict the training average: test RMSE 0.762
k train RMSE test RMSE
1 0.000 0.394
3 0.300 0.246
5 0.250 0.274
9 0.321 0.315
15 0.358 0.367
29 0.750 0.755Read the table the way step 3 describes. At k = 1 the training error is 0.000 (the model memorised every training point) but the test error is 0.394: too flexible. At k = 29 both errors are about 0.75, no better than always predicting the average (0.762): too simple. The best test error is at k = 3, which is 0.246, almost exactly the wobble alone (0.249).
.NET (C#) example
C#: compiled and run The C# sample compiled on 2026-11-19 with .NET SDK 10.0.400 (no extra packages). It also ran to the end without error.
ML.NET has no ready-made k-nearest-neighbours trainer, so this version is written from scratch with plain C#. It needs no packages. It uses the same data and prints the same numbers as the Python version.
// k-nearest-neighbours regression written from scratch, so it needs no packages.
// Same data and same numbers as generalisation.py.
const int n = 60;
double[] x = new double[n], y = new double[n];
for (int i = 0; i < n; i++)
{
x[i] = 6.0 / 59 * i + (i % 2 == 1 ? 0.013 : 0.0); // the small offset avoids equal distances
y[i] = Math.Sin(x[i]) + 0.35 * Math.Sin(17.0 * i + 1.0); // curve plus wobble
}
int[] train = Enumerable.Range(0, n).Where(i => i % 2 == 0).ToArray(); // even points train the model
int[] test = Enumerable.Range(0, n).Where(i => i % 2 == 1).ToArray(); // odd points test it
// Predict one point: the average of the y values of the k closest training points.
double Predict(double at, int k) =>
train.OrderBy(j => Math.Abs(x[j] - at)).Take(k).Average(j => y[j]);
double Rmse(int[] rows, int k) =>
Math.Sqrt(rows.Average(i => Math.Pow(y[i] - Predict(x[i], k), 2)));
double wobble = Math.Sqrt(Enumerable.Range(0, n).Average(i => Math.Pow(0.35 * Math.Sin(17.0 * i + 1.0), 2)));
double mean = train.Average(j => y[j]);
double baseline = Math.Sqrt(test.Average(i => Math.Pow(y[i] - mean, 2)));
Console.WriteLine($"wobble alone (the error no model can remove): {wobble:F3}");
Console.WriteLine($"always predict the training average: test RMSE {baseline:F3}");
Console.WriteLine(" k train RMSE test RMSE");
foreach (int k in new[] { 1, 3, 5, 9, 15, 29 })
Console.WriteLine($"{k,2} {Rmse(train, k),10:F3} {Rmse(test, k),9:F3}");In a real project you would use a library trainer such as a decision tree or FastTree in ML.NET and sweep its depth setting the same way: train, measure both errors, read the pair.
Maths behind it
- Expected squared error as bias squared plus variance plus noise (statistics)
- Root mean squared error (statistics)
- Counting combinations: powers of 10 (arithmetic)
- Distance between points in many dimensions (geometry)
Common mistakes
- Judging a model by training error alone. A model that copies the data scores perfectly and still fails.
- Tuning against the test rows again and again. Then the test error is no longer honest. Keep a validation set for tuning and touch the test set once.
- Adding many features "just in case". Each one thins the data and invites chance patterns.
- Chasing a lower test error when you are already at the noise floor. The remaining error is not the model's fault.
- Reading a small test set too closely. With few test rows, differences of a few hundredths are noise.
Quick check
Training error is 0.01 and test error is 0.40. Is the model too simple or too flexible, and what do you try first?
Show answer
Too flexible (high variance): it fits the training data but not new data. Try a simpler model, stronger regularisation, fewer features or more training data.
Training error is 0.70 and test error is 0.72. What does that tell you?
Show answer
Both are high and close together, so the model is too simple (high bias). More data will not help much; try a more flexible model or better features.
Why does adding more features sometimes make test results worse?
Show answer
Each new feature spreads the same rows over many more combinations of values, so the data becomes thin and the model can fit chance patterns. This is the curse of dimensionality.
Two models give the same test error. One is a simple tree and the other is a large ensemble. Which do you choose, and why?
Show answer
The simple one. When test performance is equal, the simpler model is easier to explain, cheaper to run and less fragile (Occam's razor).
Completion
Evidence of completion. A table of training and test error for at least five settings of one model dial, with a written sentence saying which setting you would ship and why.
Saved in this browser only. Reading and exercise are ticked separately because they are different achievements. A tick records your own work; it is not a test result. See all progress.
This lesson prepares you for: Learning paradigms beyond plain training.