Simple Algorithm
Machine Learning · Convergence · 28 min

Bayesian Linear Regression

Posterior predictive variance and the evidence.

Ridge regression gives you one line. Bayesian linear regression gives you a distribution over lines, and with it three things ridge cannot: error bars that widen where data are scarce, a way to choose the regularization strength from the training data alone, and models that switch off their own useless features.

What you’ll learn

  • Derive the Gaussian posterior N(mN,SN)\mathcal N(\mathbf m_N, S_N) over the weights, and identify its mean with ridge regression at λ=α/β\lambda = \alpha/\beta.
  • Derive the predictive variance 1/β+ϕ⊤SNϕ1/\beta + \boldsymbol\phi^\top S_N\boldsymbol\phi, separate its two sources, and describe the equivalent kernel and the function-space view.
  • Derive the log evidence and MacKay's fixed-point updates for α\alpha and β\beta, and interpret γ\gamma as an effective number of parameters.
  • Explain automatic relevance determination and the relevance vector machine, including how they fail.

The posterior over weights

Model the targets as yi=w⊤ϕ(xi)+εiy_i = \mathbf w^\top\boldsymbol\phi(\mathbf x_i) + \varepsilon_i with fixed basis functions ϕ:Rd→RM\boldsymbol\phi : \R^d \to \R^M and Gaussian noise εi∼N(0,β−1)\varepsilon_i \sim \mathcal N(0, \beta^{-1}); β\beta is the noise precision, the inverse variance. Stack the features into the N×MN \times M matrix Φ\Phi with rows ϕ(xi)⊤\boldsymbol\phi(\mathbf x_i)^\top, and put an isotropic Gaussian prior on the weights, w∼N(0,α−1I)\mathbf w \sim \mathcal N(\mathbf 0, \alpha^{-1}I). This is the notation of Bishop (2006, chapter 3).

DerivationCompleting the square
  1. log⁡p(w∣y)=−β2∥y−Φw∥2−α2∥w∥2+const=−12w⊤(αI+βΦ⊤Φ)w+β w⊤Φ⊤y+const\log p(\mathbf w \mid \mathbf y) = -\frac\beta2\norm{\mathbf y - \Phi\mathbf w}^2 - \frac\alpha2\norm{\mathbf w}^2 + \text{const} = -\frac12\mathbf w^\top\big(\alpha I + \beta\Phi^\top\Phi\big)\mathbf w + \beta\,\mathbf w^\top\Phi^\top\mathbf y + \text{const}

    The log-posterior is the log-likelihood plus the log-prior, a quadratic in w\mathbf w:

  2. w∣y∼N(mN,SN),SN−1=αI+β Φ⊤Φ,mN=β SNΦ⊤y\mathbf w \mid \mathbf y \sim \mathcal N(\mathbf m_N, S_N),\qquad S_N^{-1} = \alpha I + \beta\,\Phi^\top\Phi,\qquad \mathbf m_N = \beta\,S_N\Phi^\top\mathbf y

    A quadratic log-density is a Gaussian: read off the precision matrix from the quadratic term and the mean from the linear term.

  3. mN=(Φ⊤Φ+αβI)−1Φ⊤y\mathbf m_N = \Big(\Phi^\top\Phi + \frac\alpha\beta I\Big)^{-1}\Phi^\top\mathbf y

    The mean is also the mode, and dividing through by β\beta shows it is ridge regression with λ=α/β\lambda = \alpha/\beta (Ridge Regression in Depth proves the posterior-mean property). As α→0\alpha \to 0 it tends to least squares.

  4. SN−1=S0−1+β Φ⊤Φ,mN=SN(S0−1m0+β Φ⊤y)S_N^{-1} = S_0^{-1} + \beta\,\Phi^\top\Phi,\qquad \mathbf m_N = S_N\big(S_0^{-1}\mathbf m_0 + \beta\,\Phi^\top\mathbf y\big)

    With a general prior N(m0,S0)\mathcal N(\mathbf m_0, S_0) the same algebra gives the update below. Applied batch after batch, the posterior from one batch is the prior for the next: Bayesian linear regression learns online, exactly.

Predictions with honest error bars

DerivationThe predictive distribution
  1. p(y∗∣x∗,y)=∫p(y∗∣w) p(w∣y) dw=N(y∗∣mN⊤ϕ∗, σN2(x∗))p(y_* \mid \mathbf x_*, \mathbf y) = \int p(y_* \mid \mathbf w)\,p(\mathbf w \mid \mathbf y)\,d\mathbf w = \mathcal N\big(y_* \mid \mathbf m_N^\top\boldsymbol\phi_*,\ \sigma_N^2(\mathbf x_*)\big)

    A new target is y∗=w⊤ϕ∗+εy_* = \mathbf w^\top\boldsymbol\phi_* + \varepsilon with ϕ∗=ϕ(x∗)\boldsymbol\phi_* = \boldsymbol\phi(\mathbf x_*), where w∼N(mN,SN)\mathbf w \sim \mathcal N(\mathbf m_N, S_N) and the noise is independent. A linear function of Gaussians is Gaussian:

  2. σN2(x∗)=1β⏟noise+ϕ∗⊤SN ϕ∗⏟parameter uncertainty\sigma_N^2(\mathbf x_*) = \underbrace{\frac1\beta}_{\text{noise}} + \underbrace{\boldsymbol\phi_*^\top S_N\,\boldsymbol\phi_*}_{\text{parameter uncertainty}}

    The variance has two parts: noise, which no amount of data removes, and uncertainty about the weights, which shrinks as data arrive (adding a data point never increases it).

  3. mN⊤ϕ(x)=∑i=1Nk(x,xi) yi\mathbf m_N^\top\boldsymbol\phi(\mathbf x) = \sum_{i=1}^N k(\mathbf x, \mathbf x_i)\,y_i

    The predictive mean is a weighted sum of the training targets, with the equivalent kernel k(x,x′)=β ϕ(x)⊤SNϕ(x′)k(\mathbf x, \mathbf x') = \beta\,\boldsymbol\phi(\mathbf x)^\top S_N\boldsymbol\phi(\mathbf x') as weights: the prediction is linear in the targets, as for least squares and ridge, and nearby training points get the largest weights.

Predict before you look

One feature, no intercept: y=wx+εy = wx + \varepsilon with prior precision α=1\alpha = 1 and noise precision β=4\beta = 4. You observe targets at x=1x = 1 and x=2x = 2. What is the predictive variance at x∗=3x_* = 3?

Show the answer

0.68

Φ⊤Φ=12+22=5\Phi^\top\Phi = 1^2 + 2^2 = 5, so SN−1=1+4⋅5=21S_N^{-1} = 1 + 4\cdot5 = 21 and SN=1/21S_N = 1/21. Then σ2(3)=14+32⋅121≈0.25+0.43=0.68\sigma^2(3) = \frac14 + 3^2\cdot\frac{1}{21} \approx 0.25 + 0.43 = 0.68. At x∗=3x_* = 3, beyond the data, parameter uncertainty already exceeds the noise: the uncertainty about the slope is multiplied by x∗2x_*^2.

The function-space view removes the weights altogether. If w∼N(0,α−1I)\mathbf w \sim \mathcal N(\mathbf 0, \alpha^{-1}I), then f(x)=w⊤ϕ(x)f(\mathbf x) = \mathbf w^\top\boldsymbol\phi(\mathbf x) is a Gaussian process with covariance α−1ϕ(x)⊤ϕ(x′)\alpha^{-1}\boldsymbol\phi(\mathbf x)^\top\boldsymbol\phi(\mathbf x'), and the predictive equations above are exactly the Gaussian process regression equations for that kernel (Rasmussen & Williams, 2006, chapter 2). The widget below is a GP with the linear kernel k(x,x′)=σf2(1+xx′/ℓ2)k(x, x') = \sigma_f^2(1 + xx'/\ell^2): Bayesian linear regression on the features (1,x)(1, x), with intercept prior variance σf2\sigma_f^2 and slope prior variance σf2/ℓ2\sigma_f^2/\ell^2.

Choosing α and β by the evidence

Cross-validation can choose λ=α/β\lambda = \alpha/\beta, but the Bayesian model offers a criterion computed from the training data alone. Integrating out the weights, y=Φw+ε\mathbf y = \Phi\mathbf w + \boldsymbol\varepsilon is Gaussian with covariance β−1I+α−1ΦΦ⊤\beta^{-1}I + \alpha^{-1}\Phi\Phi^\top, and its density at the observed y\mathbf y is the evidence, or marginal likelihood, p(y∣α,β)p(\mathbf y \mid \alpha, \beta). Maximizing it over the hyperparameters is empirical Bayes, also called type-II maximum likelihood (MacKay, 1992).

DerivationThe log evidence and its fixed point
  1. log⁡p(y∣α,β)=M2log⁡α+N2log⁡β−E(mN)−12log⁡det⁡SN−1−N2log⁡2π\log p(\mathbf y \mid \alpha, \beta) = \frac M2\log\alpha + \frac N2\log\beta - E(\mathbf m_N) - \frac12\log\det S_N^{-1} - \frac N2\log 2\pi

    Write E(w)=β2∥y−Φw∥2+α2∥w∥2=E(mN)+12(w−mN)⊤SN−1(w−mN)E(\mathbf w) = \frac\beta2\norm{\mathbf y - \Phi\mathbf w}^2 + \frac\alpha2\norm{\mathbf w}^2 = E(\mathbf m_N) + \frac12(\mathbf w - \mathbf m_N)^\top S_N^{-1}(\mathbf w - \mathbf m_N), and integrate the Gaussian in w\mathbf w:

  2. ∂∂αlog⁡p=M2α−12∥mN∥2−12∑i=1M1α+λi=0\frac{\partial}{\partial\alpha}\log p = \frac{M}{2\alpha} - \frac12\norm{\mathbf m_N}^2 - \frac12\sum_{i=1}^M\frac{1}{\alpha + \lambda_i} = 0

    Let λ1,…,λM\lambda_1, \dots, \lambda_M be the eigenvalues of βΦ⊤Φ\beta\Phi^\top\Phi, so det⁡SN−1=∏i(α+λi)\det S_N^{-1} = \prod_i(\alpha + \lambda_i). Differentiate in α\alpha; since mN\mathbf m_N minimizes EE, its own dependence on α\alpha drops out (an envelope argument):

  3. α=γ∥mN∥2,1β=∥y−ΦmN∥2N−γ,γ=∑i=1Mλiα+λi\alpha = \frac{\gamma}{\norm{\mathbf m_N}^2},\qquad \frac1\beta = \frac{\norm{\mathbf y - \Phi\mathbf m_N}^2}{N - \gamma},\qquad \gamma = \sum_{i=1}^M\frac{\lambda_i}{\alpha + \lambda_i}

    Multiply by 2α2\alpha and rearrange. The same steps for β\beta (using ∂λi/∂β=λi/β\partial\lambda_i/\partial\beta = \lambda_i/\beta) give the noise update:

  4. γ=∑jdj2dj2+α/β(dj2 the eigenvalues of Φ⊤Φ)\gamma = \sum_{j}\frac{d_j^2}{d_j^2 + \alpha/\beta}\qquad (d_j^2 \text{ the eigenvalues of } \Phi^\top\Phi)

    Each eigendirection contributes nearly 1 to γ\gamma if the data determine it (λi≫α\lambda_i \gg \alpha) and nearly 0 if the prior does. So γ∈[0,M]\gamma \in [0, M] is the number of well-determined parameters, identical to ridge's effective degrees of freedom at λ=α/β\lambda = \alpha/\beta, and dividing the residual sum of squares by N−γN - \gamma mirrors dividing by n−dn - d in classical regression.

python
import numpy as np

def evidence_fit(Phi, y, alpha=1.0, beta=1.0, iters=100):
    """MacKay's fixed-point updates for the prior precision alpha and the noise precision beta."""
    N, M = Phi.shape
    eig = np.linalg.eigvalsh(Phi.T @ Phi)              # eigenvalues of Phi^T Phi
    for _ in range(iters):
        A = alpha * np.eye(M) + beta * Phi.T @ Phi     # posterior precision S_N^{-1}
        m = beta * np.linalg.solve(A, Phi.T @ y)       # posterior mean m_N
        lam = beta * eig                               # eigenvalues of beta Phi^T Phi
        gamma = np.sum(lam / (alpha + lam))            # number of well-determined parameters
        alpha = gamma / (m @ m)
        beta = (N - gamma) / np.sum((y - Phi @ m) ** 2)
    return m, alpha, beta, gamma

Each iteration costs one M×MM \times M solve. scikit-learn's BayesianRidge runs updates of this kind (with optional Gamma hyperpriors), but mind its naming: its alpha_ is the noise precision and lambda_ the weight precision, the reverse of the notation here.

Relevance determination and the RVM

Give every weight its own prior precision, wj∼N(0,αj−1)w_j \sim \mathcal N(0, \alpha_j^{-1}), and maximize the evidence over all αj\alpha_j. For features the data do not support, the optimum sends αj→∞\alpha_j \to \infty, which pins wjw_j to zero and removes the feature: automatic relevance determination (ARD), developed by MacKay and Neal for neural networks. For one αj\alpha_j with the others fixed the maximization is explicit (Faul & Tipping, 2002): with a "sparsity" sjs_j and a "quality" qjq_j computed from the other features,

αj=sj2qj2−sj  if qj2>sj,αj=∞ (prune) otherwise,\alpha_j = \frac{s_j^2}{q_j^2 - s_j}\ \text{ if } q_j^2 > s_j,\qquad \alpha_j = \infty \text{ (prune) otherwise},

so a feature survives only if its alignment with the unexplained part of y\mathbf y beats its overlap with the features already in the model.

The relevance vector machine (Tipping, 2001) applies ARD to a kernel expansion with one basis function k(x,xi)k(\mathbf x, \mathbf x_i) per training point. Most weights are pruned, leaving a sparse set of "relevance vectors", typically far fewer than an SVM's support vectors, together with predictive variances. Jointly in all the αj\alpha_j the evidence is not concave, so ARD and the RVM can stop at local optima, and the features kept can depend on the starting point.

Check your understanding

An RVM with Gaussian basis functions centered on a few relevance vectors is asked to predict far from all of them. What does its predictive variance do there?

  1. It grows without bound, signaling extrapolation
  2. It falls to roughly the noise variance, so the model looks confident exactly where it has no data
  3. It equals the prior variance of the weights
  4. It is undefined, because no basis function is active
Show the answer

B. It falls to roughly the noise variance, so the model looks confident exactly where it has no data

Far from every center all basis functions are near zero, so ϕ∗⊤SNϕ∗≈0\boldsymbol\phi_*^\top S_N\boldsymbol\phi_* \approx 0 and only 1/β1/\beta remains. Rasmussen & Quiñonero-Candela (2005) traced this to the degenerate, finite-dimensional covariance the RVM implies, and repaired it by adding a basis function centered at the test point. A GP with a stationary kernel instead returns to its prior variance far from data.

Key takeaways

  • With prior N(0,α−1I)\mathcal N(\mathbf 0, \alpha^{-1}I) and noise precision β\beta, the posterior is N(mN,SN)\mathcal N(\mathbf m_N, S_N) with SN−1=αI+βΦ⊤ΦS_N^{-1} = \alpha I + \beta\Phi^\top\Phi and mN=βSNΦ⊤y\mathbf m_N = \beta S_N\Phi^\top\mathbf y; its mean and mode are ridge with λ=α/β\lambda = \alpha/\beta.
  • The predictive variance is 1/β+ϕ∗⊤SNϕ∗1/\beta + \boldsymbol\phi_*^\top S_N\boldsymbol\phi_*: noise plus parameter uncertainty. The second part shrinks with data and grows away from it; in function space the model is a Gaussian process with kernel α−1ϕ⊤ϕ′\alpha^{-1}\boldsymbol\phi^\top\boldsymbol\phi'.
  • Maximizing the evidence gives the fixed point α=γ/∥mN∥2\alpha = \gamma/\norm{\mathbf m_N}^2, 1/β=∥y−ΦmN∥2/(N−γ)1/\beta = \norm{\mathbf y - \Phi\mathbf m_N}^2/(N - \gamma), where γ=∑iλi/(α+λi)\gamma = \sum_i\lambda_i/(\alpha + \lambda_i) counts well-determined parameters and equals ridge's effective degrees of freedom.
  • ARD gives each weight its own precision and prunes features the evidence does not support; the RVM applies it to kernel expansions. Both are non-convex, and localized basis functions make the RVM overconfident far from its relevance vectors.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

In Bayesian linear regression with prior precision α=2\alpha = 2 and noise precision β=10\beta = 10, the posterior mean equals ridge regression with which λ\lambda (in ∥y−Φw∥2+λ∥w∥2\norm{\mathbf y - \Phi\mathbf w}^2 + \lambda\norm{\mathbf w}^2)?

  1. λ=20\lambda = 20
  2. λ=5\lambda = 5
  3. λ=2\lambda = 2
  4. λ=0.2\lambda = 0.2
Show the answer

D. λ=0.2\lambda = 0.2

mN=(Φ⊤Φ+αβI)−1Φ⊤y\mathbf m_N = (\Phi^\top\Phi + \frac\alpha\beta I)^{-1}\Phi^\top\mathbf y, so λ=α/β=0.2\lambda = \alpha/\beta = 0.2. In variances, λ=σ2/τ2\lambda = \sigma^2/\tau^2 with noise variance 1/β=0.11/\beta = 0.1 and prior variance 1/α=0.51/\alpha = 0.5.

Question 2

With fixed features and more and more training data spread over the input range, what does the predictive variance at a typical input approach?

  1. The noise variance 1/β1/\beta
  2. Zero
  3. The prior variance of the function
  4. It keeps growing with NN
Show the answer

A. The noise variance 1/β1/\beta

ϕ⊤SNϕ→0\boldsymbol\phi^\top S_N\boldsymbol\phi \to 0 as the data pin down every direction the features use, but the noise term 1/β1/\beta is a property of the world and stays. Even a perfectly known line cannot predict a noisy target exactly.

Question 3

In MacKay's evidence framework, γ=∑iλi/(α+λi)\gamma = \sum_i \lambda_i/(\alpha + \lambda_i) with λi\lambda_i the eigenvalues of βΦ⊤Φ\beta\Phi^\top\Phi. What happens to γ\gamma when the prior precision α\alpha is much larger than every λi\lambda_i?

  1. γ≈M\gamma \approx M: every parameter is well determined
  2. γ≈N−M\gamma \approx N - M
  3. γ≈0\gamma \approx 0: the prior dominates every direction, and the data determine essentially nothing
  4. γ\gamma does not depend on α\alpha
Show the answer

C. γ≈0\gamma \approx 0: the prior dominates every direction, and the data determine essentially nothing

Each term λi/(α+λi)\lambda_i/(\alpha + \lambda_i) is near 0 when α≫λi\alpha \gg \lambda_i. A very strong prior pins the weights near zero, the model has almost no effective parameters, and the noise estimate divides the residuals by nearly NN.

Further reading

  • C. M. Bishop, Pattern Recognition and Machine Learning (Springer, 2006), sections 3.3–3.5.
  • D. J. C. MacKay, "Bayesian interpolation," Neural Computation 4(3), 415–447 (1992).
  • M. E. Tipping, "Sparse Bayesian learning and the relevance vector machine," Journal of Machine Learning Research 1, 211–244 (2001).
  • C. E. Rasmussen & J. Quiñonero-Candela, "Healing the relevance vector machine through augmentation," Proceedings of the 22nd International Conference on Machine Learning, 689–696 (2005).
  • C. E. Rasmussen & C. K. I. Williams, Gaussian Processes for Machine Learning (MIT Press, 2006), chapter 2.