Module contents
Lesson 3 of 20Core 90 min

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 xx and write Y=f(x)+ϵY=f(x)+\epsilon, where f(x)=E[Y∣X=x]f(x)=\E[Y\mid X=x], E[ϵ∣X=x]=0\E[\epsilon\mid X=x]=0 and Var⁡(ϵ∣X=x)=σ2(x)\Var(\epsilon\mid X=x)=\sigma^2(x). Training sample SS is independent of the test observation. Denote fˉ(x)=ES[f^S(x)]\bar f(x)=\E_S[\hat f_S(x)]. If the second moments exist,

ES,Y∣x ⁣[(Y−f^S(x))2]=σ2(x)⏟ruido+(fˉ(x)−f(x))2⏟sesgo2+ES[(f^S(x)−fˉ(x))2]⏟varianza.\E_{S,Y\mid x}\!\left[(Y-\hat f_S(x))^2\right] =\underbrace{\sigma^2(x)}_{\text{ruido}}+\underbrace{(\bar f(x)-f(x))^2}_{\text{sesgo}^2}+\underbrace{\E_S[(\hat f_S(x)-\bar f(x))^2]}_{\text{varianza}}.

To prove it, insert the mean: Y−f^S=(Y−f)+(f−fˉ)+(fˉ−f^S)Y-\hat f_S=(Y-f)+(f-\bar f)+(\bar f-\hat f_S). On expanding the square, E[Y−f∣x]=0\E[Y-f\mid x]=0 and ES[fˉ−f^S]=0\E_S[\bar f-\hat f_S]=0. 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 XX gives the mean risk decomposition; expectations must not be interchanged without integrability.

Variance describes variation of the algorithm as SS changes, not label dispersion or uncertainty calculated from one sample. Predictor bias is fˉ−f\bar f-f, 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 SS and YY conditional on xx; the integrated version adds an average over XX. 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 f^\hat f approaches ff when information increases; it limits prediction of a new label. For example, if f^=f\hat f=f on every sample, predictor bias and variance are zero, yet expected error against YY remains σ2(x)\sigma^2(x). 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 X∼Unif⁡[−1,1]X\sim\Unif[-1,1], Y=sin⁡(πX)+ϵY=\sin(\pi X)+\epsilon and ϵ∼N(0,0.32)\epsilon\sim\Normal(0,0.3^2). Polynomials use unregularized least squares and k-NN averages the kk 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.

InteractiveFifty fits and their mean
−113.5−3.5
x-axis: −1 to 1; prediction axis: −3.5 to 3.5
  • 50 fits and mean ± deviation
  • true signal
Error composition at x₀ (normalized bar)
  • bias²
  • variance
  • noise
Method
3
0.00
Squared bias0.0002
Prediction variance0.0045
Test noise0.0900
Estimated sum0.0947
Compare degree and k. Drag the line to the edge: the polynomial fit can vary greatly where there are fewer neighboring data. The three terms are calculated at that x₀.

k-NN: a formula with fixed design

Suppose positions x1,…,xnx_1,\ldots,x_n are fixed, training noises are independent with zero mean and common variance σ2\sigma^2, and Nk(x)N_k(x) contains the kk neighbors of xx with deterministic tie-breaking. Then

f^k(x)=1k∑i∈Nk(x)Yi,sesgo⁡(x)=1k∑i∈Nk(x)f(xi)−f(x),Var⁡(f^k(x))=σ2k.\hat f_k(x)=\frac1k\sum_{i\in N_k(x)}Y_i,\quad \operatorname{sesgo}(x)=\frac1k\sum_{i\in N_k(x)}f(x_i)-f(x),\quad \Var(\hat f_k(x))=\frac{\sigma^2}{k}.

The last equality sums kk independent variances and divides by k2k^2. Correlated noise adds covariances; unequal variances give their sum divided by k2k^2. As kk 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 kk 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 σ2/k\sigma^2/k exactly.

Ridge along spectral directions

For Y=Xβ+ϵY=X\beta+\epsilon, with fixed XX and Cov⁡(ϵ)=σ2I\Cov(\epsilon)=\sigma^2 I, minimize ∥Y−Xb∥2+λ∥b∥2\|Y-Xb\|^2+\lambda\|b\|^2. If XTX=Vdiag⁡(μi)VTX^TX=V\operatorname{diag}(\mu_i)V^T and βi\beta_i is the coefficient in direction viv_i, for λ>0\lambda>0 or μi>0\mu_i>0,

E[β^i]=μiμi+λβi,sesgo⁡i2=λ2βi2(μi+λ)2,Var⁡(β^i)=σ2μi(μi+λ)2.\E[\hat\beta_i]=\frac{\mu_i}{\mu_i+\lambda}\beta_i,\qquad \operatorname{sesgo}_i^2=\frac{\lambda^2\beta_i^2}{(\mu_i+\lambda)^2},\qquad \Var(\hat\beta_i)=\frac{\sigma^2\mu_i}{(\mu_i+\lambda)^2}.

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 μi=0\mu_i=0, λ>0\lambda>0 sets that component to zero and its variance is zero; with λ=0\lambda=0 one must specify which of the nonunique solutions is chosen. If the objective is divided by nn, the equivalent penalty under this convention changes by a factor of nn. No separate intercept is penalized here: the model does not include one.

The derivation projects the solution β^=(XTX+λI)−1XTY\hat\beta=(X^TX+\lambda I)^{-1}X^TY onto viv_i. The signal term is multiplied by μi/(μi+λ)\mu_i/(\mu_i+\lambda), while the random term has variance σ2μi/(μi+λ)2\sigma^2\mu_i/(\mu_i+\lambda)^2. With λ=0\lambda=0 and μi>0\mu_i>0, variance is σ2/μi\sigma^2/\mu_i: a poorly observed direction amplifies noise. Shrinkage reduces that amplification at the cost of moving the mean away from βi\beta_i. To choose λ\lambda it is not enough to see one component fall: their sum under the loss of interest matters.

InteractiveRidge as shrinkage by direction
μ = 10.20 / 0.64 / 0.04μ = 40.50 / 0.25 / 0.06μ = 160.80 / 0.04 / 0.04μ = 640.94 / 0.00 / 0.01Height: common scale from 0 to 1
  • shrinkage
  • bias²
  • variance
4
Total coefficient bias²0.933
Total coefficient variance0.156
Total squared error1.090
Increase λ. Shrinkage factors and coefficient bias² and variance contributions are shown for μ = 1, 4, 16 and 64; βᵢ = σ² = 1.

A U-curve, not a universal law

The classical U-curve summarizes a situation in which more complexity reduces bias and increases variance, with nn 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 n=30n=30, 28 independent Gaussian covariates of variance 1, βj=1/j\beta_j=1/j and noise variance 0.320.3^2. A linear fit uses the first pp variables. The sum of omitted βj2\beta_j^2 is integrated prediction bias and also contributes effective noise to the included regression. For p<n−1p<n-1, mean prediction variance is (σ2+sesgo2)p/(n−p−1)(\sigma^2+\text{sesgo}^2)p/(n-p-1) by the expectation of an inverse Wishart matrix. The figure ends at p=27p=27: the expectation used ceases to be finite as it approaches n−1n-1. The line p=np=n 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.

InteractiveBuild the U-curve
  • bias²
  • variance
  • sum
5
Bias² from omitted coordinates0.146
Estimated variance0.049
Excess error0.195
Move p with fixed n. The sum excludes irreducible noise and is truncated before the point where the inverse expectation ceases to exist.

When the loss is 0-1

The squared-error identity does not transfer unchanged to classification. At a point, write η=P(Y=1∣x)\eta=\Pr(Y=1\mid x) and q=PS(h^S(x)=1)q=\Pr_S(\hat h_S(x)=1), with training independent of the test label. The expected error is

η(1−q)+(1−η)q.\eta(1-q)+(1-\eta)q.

If η=0.8\eta=0.8 and the main prediction is 0 because q=0.2q=0.2, the error is 0.68. Raising qq 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 η=1/2\eta=1/2 both labels have equal risk. The 0-1 decomposition requires defining bias and variance for discrete decisions.

Domingos defines main prediction mm as the most frequent label over training runs, B=1{m≠h∗}B=\mathbf1\{m\ne h^*\}, V=PS(h^S≠m)V=\Pr_S(\hat h_S\ne m) and N=min⁡(η,1−η)N=\min(\eta,1-\eta). In the binary case, with tie-breaking specified,

E[1{h^S≠Y}]=(1−2B)(1−2V)N+B+(1−2B)V.\E[\mathbf1\{\hat h_S\ne Y\}]=(1-2B)(1-2V)N+B+(1-2B)V.

The explicit coefficient of VV is +1+1 when the main prediction matches Bayes and −1-1 otherwise. The noise term also depends on BB and VV: collecting terms, the total coefficient of VV is (1−2B)(1−2N)(1-2B)(1-2N). 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 η=0.8\eta=0.8 and q=0.2q=0.2, N=0.2N=0.2, B=1B=1 and V=0.2V=0.2: the formula gives −(1−0.4)0.2+1−0.2=0.68-(1-0.4)0.2+1-0.2=0.68, 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.

InteractiveWhen variance helps

Predicts 0: 0.70; predicts 1: 0.30

The main prediction differs from Bayes: increasing variation toward Bayes can reduce the error.
0.80
0.30
Main prediction / Bayes0 / 1
Noise N0.20
Bias B (disagreement)1
Variance V (disagreement)0.30
Expected error0.620
Change η and the frequency q of predicting 1. Observe error when the main label differs from Bayes and when it agrees.

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 BB to decompose the finite average of squares exactly; an unbiased population variance would use B−1B-1. 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.

[ ]Bias and variance by Monte CarloBrowser
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 BB, squaring the difference between the empirical mean prediction and the signal overestimates population squared bias in expectation by an amount proportional to Var⁡(f^S)/B\Var(\hat f_S)/B. Variance with divisor BB underestimates population variance by the same amount, so the two pieces compensate in the finite sum. Using B−1B-1 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.

[ ]Ridge and baggingBrowser
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

Proof
Prove: Prove the squared-error identity at a point x.
0
Insert f(x) and the mean over samples, and assume training is independent of test noise.

Step 1 of 2. Why does the term containing test noise and the fitted prediction vanish?

Proof
Prove: Derive k-NN variance with fixed design and independent noise of variance σ².
0
The neighbors are fixed and the estimator is their average label.

Step 1 of 2. What is the variance of the sum of k noise terms?

Numeric
With design sum of squares 10, β=2, σ²=1 and ridge λ=5, calculate the coefficient mean squared error.
Quiz
With fixed design and this lesson’s formulas, which action increases ridge variance in a direction with μ>0?
CodeBias and variance by repetition
Implement bias_variance_mc(fit_predict, sample_dataset, x0, B), with B > 0. Each call to sample_dataset() returns X, y, f0, where f0 is the true signal at x0, equal across repetitions. fit_predict(X, y, x0) returns a scalar prediction. Return squared bias relative to f0 and variance with divisor B.
def bias_variance_mc(fit_predict, sample_dataset, x0, B):
  pass
Shift+Enter to run

Summary

Key idea
Under squared loss and independence, risk separates into noise, bias² and variance across training samples. The k-NN and ridge formulas depend on their design and assumptions; with 0-1 loss, variation can help when the main prediction is wrong.