Regularisation Mathematical Deep Dive

P6.dl-architectures.06 · Audience: it-ml · Prerequisites: Regularisation and Normalisation

Mathematical derivation of the bias-variance decomposition, the ridge regression closed-form solution, LASSO sparsity, dropout as approximate Bayesian inference, and LayerNorm. Step through the five derivations one at a time (keep a pencil at hand), then work the pencil-and-paper exercises, NumPy programming tasks, and 5-question self-test below.

Prerequisite: Regularisation and Normalisation. This page assumes familiarity with basic probability, linear algebra, and calculus (partial derivatives, matrix inverse). All derivations are self-contained.

Step 1 / 5Bias-Variance Decomposition

Goal: derive the expected squared error of a predictor y^=f^(x)\hat{y} = \hat{f}(x) trained on a random dataset, with true target y=f(x)+εy = f(x) + \varepsilon.

Setup. Assume:

  • True function: f(x)f(x)
  • Noise: εN(0,σε2)\varepsilon \sim \mathcal{N}(0, \sigma^2_\varepsilon), independent of xx
  • Predictor: f^(x)\hat{f}(x) — a random variable over different training sets

Decomposition (for a fixed xx). Insert and subtract ff and E[f^]\mathbb{E}[\hat{f}]:

E[(yf^)2]=E[(yf+fE[f^]+E[f^]f^)2]\mathbb{E}\big[(y - \hat{f})^2\big] = \mathbb{E}\big[(y - f + f - \mathbb{E}[\hat{f}] + \mathbb{E}[\hat{f}] - \hat{f})^2\big]

Expanding using the identity E[(A+B+C)2]=E[A2]+E[B2]+E[C2]+cross terms\mathbb{E}[(A + B + C)^2] = \mathbb{E}[A^2] + \mathbb{E}[B^2] + \mathbb{E}[C^2] + \text{cross terms}, where the cross terms vanish under independence and zero-mean noise:

E[(yf^)2]=σε2noise+(fE[f^])2Bias2+E[(f^E[f^])2]Variance\mathbb{E}\big[(y - \hat{f})^2\big] = \underbrace{\sigma^2_\varepsilon}_{\text{noise}} + \underbrace{(f - \mathbb{E}[\hat{f}])^2}_{\text{Bias}^2} + \underbrace{\mathbb{E}\big[(\hat{f} - \mathbb{E}[\hat{f}])^2\big]}_{\text{Variance}}

Bias =f(x)E[f^(x)]= f(x) - \mathbb{E}[\hat{f}(x)]: how much the average prediction misses the true function. A simple model (few parameters) has high bias — it cannot fit the data.

Variance =E[(f^(x)E[f^(x)])2]= \mathbb{E}[(\hat{f}(x) - \mathbb{E}[\hat{f}(x)])^2]: how much the prediction varies across different training sets. A complex model (many parameters) has high variance — it memorises each training set differently.

Irreducible noise =σε2= \sigma^2_\varepsilon: cannot be reduced by any model — it is measurement noise in the data itself. ∎

ⓘ Concept — bias-variance for neural networks
Neural networks with many parameters are inherently high-variance: a large model trained on different random subsets of the training data can produce very different predictions. Regularisation (dropout, weight decay, early stopping) reduces variance at the cost of slightly increasing bias — the right trade-off keeps the total error low.
E[(yf^)2]=σε2noise+(fE[f^])2Bias2+E[(f^E[f^])2]Variance\mathbb{E}\left[(y - \hat{f})^2\right] = \underbrace{\sigma^2_\varepsilon}_{\text{noise}} + \underbrace{(f - \mathbb{E}[\hat{f}])^2}_{\text{Bias}^2} + \underbrace{\mathbb{E}[(\hat{f} - \mathbb{E}[\hat{f}])^2]}_{\text{Variance}}

Part 2 — Exercises

Work these on paper or in the scratch console at the bottom of the page. Each exercise carries its worked solution behind a reveal, so check yourself as you go.

Maths exercises (pencil and paper)

M1 — Bias and variance of a constant predictor. Consider a predictor that always predicts the training mean: f^(x)=yˉ=1niyi\hat{f}(x) = \bar{y} = \frac{1}{n} \sum_i y_i, independent of xx. Assume the true function is f(x)=3xf(x) = 3x and noise εN(0,σ2)\varepsilon \sim \mathcal{N}(0, \sigma^2).

  1. What is E[f^(x)]\mathbb{E}[\hat{f}(x)] in terms of f(x)f(x) values seen during training?
  2. What is the Bias² of this predictor at x=1x = 1 if f(1)=3f(1) = 3 and the training data has E[yˉ]=2\mathbb{E}[\bar{y}] = 2?
  3. Is the variance of this predictor zero? Explain.
  4. What can you say about the bias-variance trade-off for this predictor?
Show answer — M1
  1. E[f^(x)]=E[yˉ]\mathbb{E}[\hat{f}(x)] = \mathbb{E}[\bar{y}] = mean of the training targets — does not depend on xx.
  2. Bias² =(f(1)E[yˉ])2=(32)2=1= (f(1) - \mathbb{E}[\bar{y}])^2 = (3 - 2)^2 = 1.
  3. Not zero: f^\hat{f} varies across different training sets because yˉ\bar{y} depends on which samples are drawn. Variance =Var[yˉ]=σ2/n= \mathrm{Var}[\bar{y}] = \sigma^2 / n.
  4. The constant predictor has high bias (it ignores xx) but relatively low variance (the average is stable). It is the extreme underfitting case.

M2 — Ridge regression limit as λ → ∞. Show algebraically that as λ\lambda \to \infty, the ridge regression solution w0w^* \to 0.

  1. Start from w=(XX+λI)1Xyw^* = (X^\top X + \lambda I)^{-1} X^\top y.
  2. Factor out λ\lambda: w=1λ(XX/λ+I)1Xyw^* = \frac{1}{\lambda}(X^\top X / \lambda + I)^{-1} X^\top y.
  3. Apply the matrix limit as λ\lambda \to \infty.
  4. Interpret: what does a model with w0w^* \to 0 predict for every input?
Show answer — M2
  1. w=(XX+λI)1Xyw^* = (X^\top X + \lambda I)^{-1} X^\top y.
  2. Factor: w=1λ(I+XX/λ)1Xyw^* = \frac{1}{\lambda}\big(I + X^\top X / \lambda\big)^{-1} X^\top y.
  3. As λ\lambda \to \infty, XX/λ0X^\top X / \lambda \to 0, so (I+XX/λ)1I(I + X^\top X/\lambda)^{-1} \to I. Therefore w1λIXy=Xy/λ0w^* \to \frac{1}{\lambda} \cdot I \cdot X^\top y = X^\top y / \lambda \to 0. ∎
  4. With w=0w = 0, y^=Xw=0\hat{y} = Xw = 0 for all inputs — the model predicts zero (or the bias/intercept only). Infinite regularisation kills all learned signal.

M3 — Soft-thresholding: LASSO solution in 1D. In the 1D LASSO problem, the objective (after orthonormal XX) is:

minw  (wc)2+λw\min_w \; (w - c)^2 + \lambda |w|

where cc is the OLS estimate.

  1. For c=3.0c = 3.0, λ=2.0\lambda = 2.0: compute the LASSO solution ww^*. (Soft-thresholding: w=sign(c)max(cλ/2,0)w^* = \mathrm{sign}(c) \cdot \max(|c| - \lambda/2, 0).)
  2. For c=0.8c = 0.8, λ=2.0\lambda = 2.0: compute ww^*. Is it zero?
  3. What is the threshold on c|c| below which w=0w^* = 0?
Show answer — M3
  1. c=3.0>λ/2=1.0|c| = 3.0 > \lambda/2 = 1.0w=sign(3.0)(3.01.0)=2.0w^* = \mathrm{sign}(3.0) \cdot (3.0 - 1.0) = 2.0. LASSO shrinks the OLS estimate from 3.0 to 2.0.
  2. c=0.8<λ/2=1.0|c| = 0.8 < \lambda/2 = 1.0w=0w^* = 0. LASSO sets this coefficient to exactly zero — the feature is excluded.
  3. w=0w^* = 0 when cλ/2|c| \le \lambda/2. Sparsity threshold =λ/2= \lambda/2: any OLS estimate smaller than this is zeroed out.

Programming exercises (NumPy)

P1 — Ridge regression closed-form vs OLS. Fill in the stub to implement ridge regression and compare with OLS (λ = 0):

import numpy as np

np.random.seed(42)
n, d = 20, 5
X = np.random.randn(n, d)
w_true = np.array([3.0, -1.5, 0.0, 0.5, 2.0])
y = X @ w_true + 0.5 * np.random.randn(n)

lam = 1.0

# STUB: compute the ridge regression solution
w_ridge = ___

# OLS (lambda = 0): may be ill-conditioned if n < d
w_ols = np.linalg.lstsq(X, y, rcond=None)[0]

print('True w:  ', w_true.round(3))
print('OLS w:   ', w_ols.round(3))
print('Ridge w: ', w_ridge.round(3))
print('OLS  MSE:', ((X @ w_ols  - y)**2).mean().round(4))
print('Ridge MSE:', ((X @ w_ridge - y)**2).mean().round(4))
Show solution — P1
w_ridge = np.linalg.solve(X.T @ X + lam * np.eye(d), X.T @ y)

Expected output — True w: [3.0, -1.5, 0.0, 0.5, 2.0]; OLS w: [3.119, -1.327, 0.035, 0.365, 1.984]; Ridge w: [2.863, -1.278, 0.016, 0.405, 1.887]; OLS MSE: 0.2147; Ridge MSE: 0.2629.

Ridge shrinks all coefficients toward zero (and trades a little training MSE for stability). np.linalg.solve is preferred over an explicit matrix inverse — it is faster and numerically more stable.

P2 — Compare L1 and L2 regularisation: sparsity. Fill in the stub to apply soft-thresholding (LASSO) and ridge shrinkage to a 1D array of OLS coefficients and compare the results:

import numpy as np

# Simulate OLS estimates (orthonormal X, so w_ols = XᵀY directly)
np.random.seed(7)
c = np.random.uniform(-3, 3, 10)  # 10 OLS estimates
lam = 2.0

# Ridge shrinkage: w_ridge_j = c_j / (1 + lambda)  [when XᵀX = I]
w_ridge = c / (1 + lam)

# STUB: soft-thresholding (LASSO solution when XᵀX = I)
# w_lasso_j = sign(c_j) * max(|c_j| - lam/2, 0)
w_lasso = ___

print('OLS:   ', c.round(3))
print('Ridge: ', w_ridge.round(3), f'  ({(w_ridge == 0).sum()} zeros)')
print('LASSO: ', w_lasso.round(3), f'  ({(w_lasso == 0).sum()} zeros)')
Show solution — P2
w_lasso = np.sign(c) * np.maximum(np.abs(c) - lam / 2, 0)

Expected output — OLS: [-2.542, 1.68, -0.37, 1.341, 2.868, 0.231, 0.007, -2.568, -1.389, -0.001]; Ridge: [-0.847, 0.56, -0.123, 0.447, 0.956, 0.077, 0.002, -0.856, -0.463, -0.0] (0 zeros — shrinks but never zeroes); LASSO: [-1.542, 0.68, -0.0, 0.341, 1.868, 0.0, 0.0, -1.568, -0.389, -0.0] (4 zeros — true sparsity).

Ridge scales every coefficient by 1/(1+λ). LASSO zeroes any coefficient with cjλ/2|c_j| \le \lambda/2 — exactly the feature selection property described in the LASSO step.

P3 — LayerNorm: implement and verify. Fill in the stub to implement LayerNorm and verify mean = 0, variance = 1:

import numpy as np

def layer_norm(x: np.ndarray, eps: float = 1e-5) -> np.ndarray:
    """Normalise x across feature dimension (γ=1, β=0)."""
    # STUB: compute mean and variance, return (x - mean) / sqrt(var + eps)
    return ___

np.random.seed(0)
x = np.random.randn(8) * 5 + 10  # large scale and offset
x_hat = layer_norm(x)

print('Input mean:  ', x.mean().round(4))
print('Input std:   ', x.std().round(4))
print('LN mean:     ', x_hat.mean().round(8))  # should be ~0
print('LN var:      ', x_hat.var().round(8))   # should be ~1
print('LN output:   ', x_hat.round(4))
Show solution — P3
mu = x.mean()
var = x.var()  # population variance: (1/d) Σ (xᵢ - μ)²
return (x - mu) / np.sqrt(var + eps)

Expected output — Input mean: 14.4205, std: 5.1133; LN mean: 4.16e-16 (≈ 0 ✓); LN var: 0.99999962 (≈ 1 ✓); LN output: [0.8604, -0.4732, 0.0925, 1.3267, 0.9617, -1.8201, 0.0645, -1.0125].

LayerNorm removes any mean offset and scales to unit variance — regardless of how large or skewed the inputs are. The learnable γ and β then allow the network to rescale and shift the normalised output to whatever range the next layer needs.

Part 3 — Self-Test

Write your answer before revealing.

Q1 — State the bias-variance decomposition of the expected squared error E[(y − f̂)²] as a sum of three terms. Name each term.

Q2 — Ridge regression is equivalent to MAP estimation with a specific prior on the weights. What is that prior? What does λ correspond to?

Q3 — Explain geometrically why L1 regularisation produces exact zeros in the solution, while L2 only shrinks coefficients without zeroing them.

Q4 — How do you use a dropout-trained network to estimate predictive uncertainty at test time? What kind of uncertainty does this estimate?

Q5 — Numerical: given x = [1.0, −1.0, 2.0, −2.0] with γ = 1, β = 0, ε = 0, compute μ, σ², and the normalised output x̂ (to 4 decimal places), then verify mean(x̂) = 0 and var(x̂) = 1.


Cross-references: Regularisation and Normalisation (base module) · Training Loop and Optimisers — module 03 of this track (AdamW = Adam + L2 weight decay) · The Encoder Block (dropout and LayerNorm in the full architecture).

Ask the mentor about this module

Ask a question about this content. The mentor explains and grounds its answer in what you are studying; asking is recorded as a learning signal, not a grade.

Ctrl/Cmd + Enter to send

Try it yourself

A scratch console for this page's ideas — ungraded, nothing you run here is recorded.

Scratch console

A scratch console with the scientific stack (pandas, numpy, scikit-learn). Runs on the server — no network, resource-limited and measured.

Output appears here.