The bias-variance decomposition
Prove the bias-variance-noise decomposition of expected squared error and apply it to k-NN, ridge and polynomial models in closed form and by simulation. Examine why the decomposition does not transfer cleanly to 0-1 loss and the classical U-curve later challenged by double descent.
After this lesson you can
- Prove the decomposition E[(Y - f̂_S(x))²] = noise + bias² + variance, distinguishing the three sources of randomness.
- Calculate bias and variance in closed form for k-NN with fixed design and ridge regression in the spectral basis of XᵀX.
- Estimate bias and variance by Monte Carlo for any scikit-learn algorithm.
- Explain the difficulties of decomposition under 0-1 loss (Domingos) and why variance can reduce error.
- Recognize the U-curve and list its implicit assumptions.
Before you start
A prediction depends on the sample received
Repeat training with another sample of the same size. A flexible algorithm may follow the signal well on average while producing very different predictions across samples. A rigid algorithm can be stable yet systematically wrong. The previous lesson separated the best rule in a class from the selected rule; now we separate the mean prediction of the algorithm from its variation across samples. The two types of bias are not synonymous.
The squared-error identity
Fix a point and write , where , and . Training sample is independent of the test observation. Denote . If the second moments exist,
To prove it, insert the mean: . On expanding the square, and . Independence between test noise and training eliminates the remaining product. The three squares remain. If the training sample includes the test label or shares its noise, this argument can fail. Integrating the identity over the distribution of gives the mean risk decomposition; expectations must not be interchanged without integrability.
Variance describes variation of the algorithm as changes, not label dispersion or uncertainty calculated from one sample. Predictor bias is , with sign; the identity contains its square. The previous lesson’s approximation error compares the best population rule in a class with Bayes. The two can differ even for the same class: the algorithm may have additional estimation or optimization bias.
The identity answers a procedure-design question: if you could obtain many fresh samples from the same distribution and retrain, what error would you expect? It does not assign measurable bias and variance to one observed prediction without additional information. Also distinguish a fixed point from the test distribution. The pointwise identity averages over and conditional on ; the integrated version adds an average over . Variance may be high at an edge of the domain even when its integrated average is small.
For regression with known true function, noise does not limit how closely approaches when information increases; it limits prediction of a new label. For example, if on every sample, predictor bias and variance are zero, yet expected error against remains . If evaluating against the noiseless signal instead, the appropriate sum omits the irreducible term.
The figure trains 50 models on independent samples of size 40 for , and . Polynomials use unregularized least squares and k-NN averages the nearest labels. The mean and one-standard-deviation band are empirical, not a confidence interval. The seed is 1303; the test point can be dragged or selected with the slider.
k-NN: a formula with fixed design
Suppose positions are fixed, training noises are independent with zero mean and common variance , and contains the neighbors of with deterministic tie-breaking. Then
The last equality sums independent variances and divides by . Correlated noise adds covariances; unequal variances give their sum divided by . As increases, variance falls in this fixed model, but bias need not grow monotonically: it depends on the signal and which neighbors are added. If training positions are also resampled, there is another source of variation absent from this conditional formula.
Consider a linear signal and neighbors symmetrically positioned around the test point: their average can equal the signal even as increases. In a curved region or near an edge, the neighborhood can be asymmetric and the average signal can shift. Thus “large k implies more bias” is a common intuition, not an unconditional algebraic consequence. The figure’s simulation draws new positions, so its variance need not equal exactly.
Ridge along spectral directions
For , with fixed and , minimize . If and is the coefficient in direction , for or ,
The shrinkage factor is larger for large eigenvalues. The formula describes coefficient error; prediction risk must be weighted by the covariance of test covariates. If , sets that component to zero and its variance is zero; with one must specify which of the nonunique solutions is chosen. If the objective is divided by , the equivalent penalty under this convention changes by a factor of . No separate intercept is penalized here: the model does not include one.
The derivation projects the solution onto . The signal term is multiplied by , while the random term has variance . With and , variance is : a poorly observed direction amplifies noise. Shrinkage reduces that amplification at the cost of moving the mean away from . To choose it is not enough to see one component fall: their sum under the loss of interest matters.
A U-curve, not a universal law
The classical U-curve summarizes a situation in which more complexity reduces bias and increases variance, with fixed. It is a pattern, not an identity: complexity can be defined in many ways and neither bias nor variance need be monotone for an arbitrary family. Changing regularization, algorithm or distribution can alter the curve.
To make it testable, take , 28 independent Gaussian covariates of variance 1, and noise variance . A linear fit uses the first variables. The sum of omitted is integrated prediction bias and also contributes effective noise to the included regression. For , mean prediction variance is by the expectation of an inverse Wishart matrix. The figure ends at : the expectation used ceases to be finite as it approaches . The line indicates the interpolation threshold, not a value calculated there. Do not extrapolate this formula to the overparameterized regime; the double-descent lesson studies it under different assumptions.
When the loss is 0-1
The squared-error identity does not transfer unchanged to classification. At a point, write and , with training independent of the test label. The expected error is
If and the main prediction is 0 because , the error is 0.68. Raising to 0.4 keeps 0 as the main prediction, but error falls to 0.56: some variation corrects the main bias. If the main prediction is already Bayes, deviations have the opposite effect. At both labels have equal risk. The 0-1 decomposition requires defining bias and variance for discrete decisions.
Domingos defines main prediction as the most frequent label over training runs, , and . In the binary case, with tie-breaking specified,
The explicit coefficient of is when the main prediction matches Bayes and otherwise. The noise term also depends on and : collecting terms, the total coefficient of is . These are not three independent positive terms as in the squared-error case. The example uses known conditional probabilities to illustrate the sign, not to estimate them from one sample.
For example, with and , , and : the formula gives , matching the direct calculation. The sign of the noise coefficient changes when the main prediction ceases to be Bayes. A decomposition convention is useful only if its definitions and coefficients are retained.
Measure with independent repetitions
The following lab trains models on fresh samples, calculates mean and variance on a grid and compares their sum with squared error on independent test labels. Variance uses divisor to decompose the finite average of squares exactly; an unbiased population variance would use . Signal and noise are known by construction. A bootstrap from one sample approximates a different conditional experiment and may poorly estimate variation across fresh samples.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline
rng = np.random.default_rng(1303)
grid = np.linspace(-1, 1, 101)
truth = np.sin(np.pi * grid)
sigma, n, B = .3, 40, 50
class KNN:
def __init__(self, k): self.k = k
def fit(self, X, y): self.x, self.y = X[:,0], y; return self
def predict(self, X):
ids = np.argsort(np.abs(X[:,0,None] - self.x[None,:]), axis=1, kind='stable')[:, :self.k]
return self.y[ids].mean(axis=1)
def sampler():
x = rng.uniform(-1, 1, n)
return x[:,None], np.sin(np.pi*x) + rng.normal(0, sigma, n)
def bias_variance(make_model, sampler, x_grid, B):
predictions = []
for _ in range(B):
X, y = sampler()
predictions.append(make_model().fit(X, y).predict(x_grid[:,None]))
pred = np.array(predictions)
signal = np.sin(np.pi*x_grid)
bias2 = (pred.mean(axis=0) - signal)**2
var = pred.var(axis=0)
ytest = signal + rng.normal(0, sigma, (2000, len(x_grid)))
# Un test independiente para cada predicción y repetición de ruido.
mse = np.mean((pred[:,None,:] - ytest[None,:,:])**2, axis=(0,1))
return bias2, var, mse
for kind, factory in [('poly', lambda: make_pipeline(PolynomialFeatures(5), LinearRegression())),
('knn', lambda: KNN(5))]:
bias, var, mse = bias_variance(factory, sampler, grid, B)
print(kind, 'sesgo²', round(bias.mean(),4), 'varianza', round(var.mean(),4),
'suma', round((bias+var+sigma**2).mean(),4), 'test', round(mse.mean(),4))
plt.plot(grid, bias+var+sigma**2, label=f'{kind}: suma')
plt.plot(grid, mse, '--', alpha=.6, label=f'{kind}: test')
plt.legend(); plt.xlabel('x'); plt.ylabel('error cuadrático'); plt.show()The test check has Monte Carlo noise, so the numbers do not match exactly. The empirical band in the figure uses the same 50 replicates per method and does not claim to be the exact population variance.
With finite , squaring the difference between the empirical mean prediction and the signal overestimates population squared bias in expectation by an amount proportional to . Variance with divisor underestimates population variance by the same amount, so the two pieces compensate in the finite sum. Using corrects the variance bias under independent repetitions, but does not itself make estimated squared bias unbiased. These differences matter when comparing small components with few replicates.
The second lab checks ridge with fixed design and compares trees with bagging on fresh samples. Bagging averages trees fitted to resamples of each sample; its components remain correlated. Therefore reducing variance is not guaranteed in every problem, and bias can change too. In this experiment it is measured, not assumed.
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import BaggingRegressor
rng = np.random.default_rng(1304)
x = np.sqrt(10) * np.ones((1, 1))
beta, lam, sigma, B = 2., 5., 1., 500
coefs = []
for _ in range(B):
y = x[:,0]*beta + rng.normal(0, sigma, 1)
coefs.append(Ridge(alpha=lam, fit_intercept=False).fit(x,y).coef_[0])
coefs = np.array(coefs)
print('ridge: sesgo²', round((coefs.mean()-beta)**2,4), 'varianza', round(coefs.var(),4))
print('teoría: sesgo²', round((lam*beta/(10+lam))**2,4), 'varianza', round(sigma**2*10/(10+lam)**2,4))
grid = np.linspace(-1,1,80); truth = np.sin(np.pi*grid)
preds = {'árbol': [], 'bagging': []}
for seed in range(30):
x = rng.uniform(-1,1,100); y = np.sin(np.pi*x)+rng.normal(0,.3,100)
tree = DecisionTreeRegressor(random_state=seed)
bag = BaggingRegressor(estimator=DecisionTreeRegressor(), n_estimators=15, random_state=seed, n_jobs=1)
for name, model in [('árbol',tree), ('bagging',bag)]:
preds[name].append(model.fit(x[:,None],y).predict(grid[:,None]))
for name, values in preds.items():
values = np.array(values)
print(name, 'sesgo²', round(np.mean((values.mean(axis=0)-truth)**2),4),
'varianza', round(np.mean(values.var(axis=0)),4))Exercises
Step 1 of 2. Why does the term containing test noise and the fitted prediction vanish?
Step 1 of 2. What is the variance of the sum of k noise terms?
def bias_variance_mc(fit_predict, sample_dataset, x0, B):
pass