Sub topic 3
Bias and variance in plain terms
This chapter assumes you know supervised learning basics (features, labels, train and test splits), can read short Python and NumPy code, and have used scikit-learn estimators with fit, predict and score. You should also have a working idea of overfitting and hyperparameters. The previous chapter defined underfitting and overfitting by comparing training and validation scores. This chapter explains why those two failures happen. The answer is two sources of error called bias and variance. They are the vocabulary used to read learning curves and validation curves later in the tutorial.
Two ways a model can be wrong
Suppose you train the same kind of model many times, each time on a different random sample of data from the same source. Each run gives you a slightly different fitted model. The errors you see come from two separate things.
- Bias is the systematic error. It is the gap between the average prediction of those many models and the true relationship. A model has high bias when its assumptions are too rigid to represent the pattern, for example a straight line fitted to a curved relationship. More data does not remove this error, because every model makes the same mistake.
- Variance is the instability error. It measures how much the predictions change from one training sample to another. A model has high variance when it reacts strongly to the particular points it saw, including their noise. Different samples produce visibly different models.
A third part, irreducible noise, is randomness in the labels that no model can predict. It sets a floor on the error you can reach.
For squared error, these three parts add up exactly:
expected error = bias squared + variance + irreducible noise
The sum is the reason for the familiar trade-off. Changing a model to lower one term usually raises the other, so the goal is the combination with the lowest total, not zero bias or zero variance.
An intuition with a target
Picture each trained model as one dart thrown at a target, where the bullseye is the true value.
| Pattern of darts | Bias | Variance | Typical model |
|---|---|---|---|
| Tight cluster, far from the bullseye | High | Low | Linear model on a nonlinear problem |
| Scattered around the bullseye | Low | High | Deep unpruned tree, tiny regularization |
| Scattered and off-center | High | High | Poor model with too little data |
| Tight cluster on the bullseye | Low | Low | Well-matched model with enough data |
You never see the bullseye in practice, and you rarely train a model many times on fresh samples. Learning curves and validation curves are the practical substitute. They let you infer which kind of error dominates from the scores you can measure.
Measuring bias and variance by simulation
In a real project the true function is unknown, so you cannot compute bias directly. In a controlled experiment you can, because you choose the true function yourself. The following script draws 200 independent training sets from a noisy sine curve and fits a polynomial of a given degree to each. It then measures how far the average prediction is from the truth (bias squared) and how much the individual predictions spread around their average (variance).
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures
rng = np.random.default_rng(0)
def true_fn(x):
return np.sin(2 * np.pi * x)
x_test = np.linspace(0, 1, 50).reshape(-1, 1)
f_test = true_fn(x_test).ravel()
def simulate(degree, n_repeats=200, n_train=30, noise=0.3):
preds = np.empty((n_repeats, len(x_test)))
for i in range(n_repeats):
x = rng.uniform(0, 1, size=(n_train, 1))
y = true_fn(x).ravel() + rng.normal(0, noise, size=n_train)
model = make_pipeline(PolynomialFeatures(degree), LinearRegression())
model.fit(x, y)
preds[i] = model.predict(x_test)
mean_pred = preds.mean(axis=0)
bias_sq = np.mean((mean_pred - f_test) ** 2)
variance = np.mean(preds.var(axis=0))
return bias_sq, variance
for degree in (1, 4, 15):
bias_sq, variance = simulate(degree)
print(f"degree={degree:2d} bias^2={bias_sq:.4f} variance={variance:.4f}")Run it and compare the three rows. The exact numbers depend on the random seed, but the pattern is stable.
- Degree 1 (a straight line) has large bias squared and small variance. The line cannot bend to follow a sine wave, and it barely changes between samples.
- Degree 4 has small bias squared and small variance. It is flexible enough for the shape, and 30 points are enough to pin it down.
- Degree 15 has near-zero bias squared but large variance. Given 30 noisy points, it bends to fit the noise, so each sample yields a different curve.
This is the whole story in three rows. Increasing model flexibility moves you from the first row toward the third.
How the two errors show up in scores
The experiment above needs the true function. A learning curve or validation curve needs only your data, and it exposes the same two problems through the training and validation scores from the previous chapters.
- High bias appears as a low training score and a validation score close to it. The model cannot even fit the data it has seen. Both scores are poor, and the gap between them is small.
- High variance appears as a high training score and a clearly lower validation score. The model fits the training set well but does not carry that performance to new data. The gap is large.
The table below summarizes the link. Later chapters build on it when reading curve shapes.
| Observation | Likely cause | Underfit or overfit |
|---|---|---|
| Training score low, validation score low, small gap | High bias | Underfitting |
| Training score high, validation score much lower | High variance | Overfitting |
| Both scores high, small gap | Low bias, low variance | Good fit |
What counts as "low" depends on the task and the metric. A training accuracy of 0.80 is low for a problem where humans reach 0.99, and it may be fine for a noisy problem where no model exceeds 0.82. You need a reference point, such as a simple baseline, known human performance, or the best score any model has reached on the data.
What moves each error
Knowing which error dominates tells you which lever to pull. The effects below are tendencies, not guarantees.
- Model flexibility. More flexible models (higher polynomial degree, deeper trees, more neighbors removed from
n_neighbors, largerCin an SVM) lower bias and raise variance. Less flexible models do the reverse. - Regularization strength. Stronger regularization (larger
alphain ridge, smallerCin logistic regression) raises bias slightly and lowers variance. It is the standard way to tame a high-variance model without changing its form. - Training set size. More data lowers variance because individual points matter less. It does not lower bias. This is the reason a learning curve can tell you whether collecting more data is worth the cost.
- Number of features. Adding features can lower bias if they carry signal. It can raise variance, especially when you have few samples relative to features.
- Ensembling. Averaging many high-variance models, as in random forests, cuts variance while keeping bias roughly the same. Boosting works the other way, reducing bias by adding models that correct earlier errors.
Limits of the trade-off picture
The bias-variance decomposition is exact for squared error. For other losses, such as classification error or log loss, there is no equally clean split, but the intuition still guides practice.
Modern high-capacity models can also break the simple rule that more flexibility always means more variance in test error. Very large neural networks and some interpolating models show test error that falls again past the point where they fit the training data perfectly. This effect is called double descent. For the scikit-learn models in this tutorial, the classical picture is a reliable guide, but do not assume a U-shaped test error in every setting.
Finally, variance has two meanings that are easy to confuse. The variance in this chapter is the spread of predictions across different training sets. The fold-to-fold spread you will plot as error bands in a later chapter is a related but different quantity. It is the spread of scores across cross-validation folds, and it mixes sampling noise in the evaluation with the model's own instability.
Key points
- Bias is systematic error from a model that is too rigid. Variance is instability from a model that reacts too strongly to its particular training sample.
- For squared error, expected error equals bias squared plus variance plus irreducible noise.
- High bias shows as low training and validation scores with a small gap. High variance shows as a high training score with a much lower validation score.
- More data reduces variance but not bias. More flexibility and less regularization reduce bias but raise variance.
Exercise
A model has a training accuracy of 0.62 and a cross-validated accuracy of 0.60 on a problem where a simple baseline reaches 0.85. Which error dominates, and would collecting ten times more data help much?
Show answer
High bias dominates. The training score is low and close to the validation score, so the model cannot fit even the data it has seen. More data lowers variance, not bias, so it would help little. Better remedies are a more flexible model, better features, or weaker regularization.
Exercise
In the simulation, you change simulate to use n_train=300 instead of 30. What do you expect to happen to the bias squared and the variance of the degree-15 model, and why?
Show answer
The variance drops sharply, because each fit is determined by many more points and is less sensitive to any one sample's noise. The bias squared stays near zero, because degree 15 was already flexible enough to represent the sine curve. Bias depends on the model's form, not on the amount of data.