04 / 15 · Bayesian Linear Models
Bayesian linear regression
A Gaussian prior on the weights of a linear model gives a Gaussian posterior whose mean is the ridge estimate, a predictive with error bars, and an evidence that sets both precisions without a validation set.
Bayesian model selection · Regularization · The multivariate Gaussian
On this page 8
Fit a cubic to eight noisy points of , all of them in . Ridge regression returns one curve. At , among the data, its prediction is good; at , beyond the last point, it is a guess. Ridge reports both with the same confidence, and its penalty must still be chosen by cross-validation, refitting over a grid of values on many splits.
Keep the whole posterior over the weights instead of its mode, and both problems have exact answers. With the true noise level known, the predictive standard deviation is at and at : eleven times larger where the model knows less. The penalty follows from the evidence, the quantity the previous note used to compare models. Everything is exact because everything is Gaussian: the noise, the prior, and therefore the posterior, the predictive and the evidence.
The model: a Gaussian prior over the weights#
The data are inputs with real targets . A fixed feature map , for example , turns each input into a feature vector, and the design matrix has as its -th row. The likelihood says that each target is the linear prediction plus independent Gaussian noise; the prior says that the weights are independently Gaussian around zero:
The model needs to be linear only in . The features can be any fixed functions, polynomials, splines or the Gaussian bumps of the kernels note, and everything below holds unchanged.
The prior pulls every weight towards zero, including the weight of the constant feature 1, the intercept. That makes the fit depend on where the origin of lies. With the constant feature alone and points, the posterior below gives the intercept the mean , with the mean target; for three points, and , that is , so adding 100 to every target moves the prediction by only . An unpenalized intercept, as ridge regression recommends, gets its own prior with , a flat prior. Everything below then holds with in place of , as in the relevance vector machine. The posterior stays proper as long as the data determine the intercept, but the evidence goes to zero with , so it cannot then compare models.
The two precisions are hyperparameters. is the noise variance. is the prior variance of each weight, which says how large we expect the weights to be before seeing the data. Both are fixed until the last section, which estimates them.
Tools: matrix derivatives and Gaussian identities#
Six facts carry every derivation of this section of the course. Each is a standard identity or follows in one line.
1. Gradients of linear and quadratic forms#
For a vector and a matrix ,
which is for symmetric ; the matrix calculus note of the Mathematics course derives both. Expanding the squared error,
2. Derivatives of a log-determinant#
For a symmetric positive definite matrix that depends on a scalar ,
The log-determinant section of the same note derives it for any invertible matrix. As a check, take with fixed and eigenvalues . Then , and its derivative in is , the formula with .
3. Completing the square#
If a density over has the logarithm
with symmetric positive definite, then . The proof is one line:
and the last term is a constant. The matrix of the quadratic term is the precision, and the mean is the precision’s inverse times the linear term.
4. The Gaussian integral#
For the same and ,
because the integrand is times an unnormalized , whose normalizing constant is (the density).
5. The linear-Gaussian marginal#
If and, given , with independent noise , then
is an affine map of a Gaussian, Gaussian with mean and covariance ; adding independent Gaussian noise keeps it Gaussian and adds the covariances.
6. Woodbury and the determinant lemma#
For an invertible matrix , an invertible matrix and matrices , ,
The first, the Woodbury identity of the matrices note, is checked by multiplying the right side by and simplifying to . The second follows from the two block factorizations of . Eliminating the lower-left block first, and the upper-right block first, its determinant is
the product of a diagonal block and its Schur complement either way; multiplying by gives the lemma. When is easy, a multiple of say, and , they turn the inverse and the determinant of an matrix into those of an one, or the other way round.
Facts 3–5 are the Gaussian computations of the multivariate Gaussian note written as recipes.
The posterior over the weights#
By Bayes’ formula the log-posterior is the log-likelihood plus the log-prior, up to a constant. We drop and the normalizing constants, expand , drop , which does not contain , and group the quadratic and linear terms:
This is the form of fact 3, with precision and linear term :
is positive semidefinite, so is positive definite for any , and exists even with more features than points.
Because the precision is a sum over points, the data can be processed one point at a time. With the posterior after points used as the prior for point ,
and the end result is the posterior of all the points at once. The added matrix is positive semidefinite, so , and since inversion reverses the order of positive definite matrices, : a new point can only reduce the uncertainty about the weights, in every direction.
Fit a line, , through three points , , with and , a noise standard deviation of . The inputs are centred, so every matrix is diagonal:
Least squares gives . The posterior mean shrinks the intercept by and the slope by , more where the data carry less precision. The posterior standard deviations are for the intercept and for the slope.
Bayesian linear regression from the prior to the prediction
The posterior mean is the ridge estimate#
The mode of a Gaussian is its mean, so the MAP estimate and the posterior mean coincide. Dividing the precision and the linear term by ,
This is the ridge estimate with penalty : the noise variance divided by the prior variance, as in the MAP section of the probability course. In the worked example, , and ridge gives , the same vector. A noisier problem (smaller ) or a tighter prior (larger ) is a stronger penalty. The two limits recover the extremes: as , tends to the least-squares solution when is invertible, and as , the posterior collapses onto .
The Bayesian reading adds everything except the mean. The covariance , which the Bayesian reading of ridge mentions in passing, gives an error bar for every weight and, below, for every prediction. The ridge shrinkage factors of the regularization note, whose sum is the effective degrees of freedom, reappear in the evidence, now with a formula for the best .
The predictive distribution#
A new target at an input , with feature vector , is . Here is distributed as the posterior, and the fresh noise is independent of it. Fact 5 with the single row in place of , mean and covariance gives the predictive distribution:
The same result needs no integral. Write the posterior weights as with . Then is a constant plus two independent zero-mean Gaussians, so it is Gaussian by fact 5. Its mean is . Variances of independent terms add, and the linear map has the variance , so the variance is .
The variance has two parts. is the noise in the new target, which no amount of data removes. is the uncertainty about the weights, seen through the feature vector of the new input.
The noise-free value of the regression function, , is the same decomposition without , so its posterior has only the second part:
A band for the curve uses this variance, a band for a new observation adds . A plug-in prediction at keeps the and loses .
Why the uncertainty grows away from the data#
Let be the eigenvalues of and its eigenvectors. Then , so has the same eigenvectors, with eigenvalues , and
measures how much the training inputs vary along . A new input whose feature vector lies along well-measured directions, with large , costs little. Components along poorly measured directions are divided by little more than .
For the line with centred inputs the eigenvectors are the axes, and
a parabola in with its minimum at the centre of the data: the error in the slope is multiplied by the distance from the centre. In the worked example, the variance is :
| predictive mean | predictive variance | |
|---|---|---|
| 0 | 0.462 | 0.327 |
| 1 | 1.795 | 0.438 |
| 3 | 4.462 | 1.327 |
At , three times as far from the centre as the farthest training point, the weight uncertainty is more than four times the noise variance.
For polynomial features the same happens faster, because the high powers of grow quickly outside the range of the data. The figure fits a cubic to the first 2, 8 and 32 of 32 noisy points:
The predictive band narrows as the data grow
As the data grow, falls towards zero wherever the data are dense, and falls to the noise floor and no lower. Away from the data the band stays open.
Evidence maximization for the hyperparameters#
The evidence, or marginal likelihood, is the probability of the targets with the weights integrated out:
It is a function of the hyperparameters only. Choosing them by maximizing it is type-II maximum likelihood, or empirical Bayes: maximum likelihood one level up, with the weights integrated out instead of fitted. The model selection note explains why maximizing over as well would fail, and maximizes the evidence numerically. Here the posterior gives the evidence a form that explains what it trades off, and a fast iteration for its maximum.
The evidence in two forms#
Fact 5 with the prior mean and covariance gives the evidence directly as a Gaussian over , the form of the model selection note:
This form needs the inverse and the determinant of an matrix. A second form needs only ones. Write the integrand as , with
is quadratic in . Its gradient vanishes at the posterior mean , and its Hessian is , so its Taylor expansion around is exact:
The remaining integral is fact 4, . Taking the logarithm,
This is the route of Bishop (2006, Section 3.5.1) and of Vetrov and Kropotov’s lecture 4. The Code section checks that the two forms agree.
Fit times an Occam factor#
Regroup the boxed formula. With and , the two terms below add up to it, the cancelling:
The first term is the best fit the model achieves. The second multiplies the prior density at the posterior mean by the volume of the posterior. It is the fraction of the prior’s probability that lands on the weights the data allow, and it is small when the prior is much broader than the posterior (MacKay, 2003, Chapter 28). This is the coin’s peak-times-width argument, now exact. A very broad prior (small ) does not improve the fit any further but makes the Occam factor tiny, and the evidence prefers the prior that is just broad enough:
The evidence as a function of the prior precision
The fixed point#
Differentiate the boxed formula with respect to . depends on , but is minimized at , so its derivative through vanishes and only the explicit counts. Fact 2 gives . Setting the derivative to zero and multiplying by ,
For , the explicit dependence is in and in . The eigenvalues are proportional to , so , and
Setting the derivative to zero gives . Together these are the fixed-point equations of MacKay (1992, Section 4):
They are not closed-form solutions, because and depend on and . They are iterated: compute and for the current values, then , then the new and , and repeat. The eigenvalues of are computed once and rescaled by .
The effective number of parameters#
The quantity is the effective number of parameters. Each term lies between 0 and 1. It is close to 1 when the data determine the weight along (), and close to 0 when the prior does (Bishop, 2006, Section 3.5.3). The terms are the ridge shrinkage factors of the previous section.
The two updates then read naturally. The noise estimate divides the residual sum of squares by , just as the unbiased variance estimate of least squares divides by : degrees of freedom were spent on fitting. The prior variance is the mean squared weight over the well-determined directions. With many more points than features, every , , and the updates need no eigenvalues: and .
For the 32 points and cubic features of the figures, starting from , the iteration converges to:
| Quantity | Value |
|---|---|
| , and the noise sd | , (true ) |
| , of | |
| log evidence at , | |
| log evidence at the maximum |
Almost all four parameters are well determined. scikit-learn’s BayesianRidge, which runs the same iteration with nearly flat gamma priors on the two precisions, returns the same values.
The same maximum can be found with the EM algorithm, treating as a latent variable. Its E-step is the posterior above. Its M-step maximizes the expected log-prior , with under the posterior, and gives . Since , a stationary point of this update is a stationary point of . The relevance vector machine compares the two iterations.
Why the two forms of the evidence agree#
Optional depth: the matrix identities behind the two forms. The rest of the note does not depend on it.
Apply the determinant lemma to , with , , and as the middle matrix:
This matches the terms . Woodbury gives , and with ,
so the quadratic forms match as well.
Where it breaks: confident far from the data#
The growth of the error bars away from the data comes from the features. Replace the cubic by localized features: nine Gaussian bumps with centres evenly spaced on . Fit both models to the same 32 points, with and :
| truth | bumps: mean ± sd | cubic: mean ± sd | |
|---|---|---|---|
| 0 | 0.000 | −0.144 ± 0.218 | −0.066 ± 0.206 |
| 1.5 | −0.572 | 0.069 ± 0.206 | −1.368 ± 0.668 |
| 2 | −0.959 | 0.000 ± 0.200 | −6.721 ± 1.641 |
| 3 | 0.938 | 0.000 ± 0.200 | −31.324 ± 5.790 |
Far from every centre, , so , and the predictive variance falls to the noise floor . At the bump model predicts , exactly the noise level, and the truth lies 4.8 standard deviations away. The model is most confident exactly where it knows least (Bishop, 2006, Section 3.3.2). The cubic’s mean is far worse, but its band at least widens.
The cure is to stop fixing the features. A Gaussian process is this model with infinitely many features, and its predictive variance returns to the prior variance away from the data. The relevance vector machine keeps bumps on the training inputs and inherits the flaw.
Other limits come from the same assumptions. The closed forms need Gaussian noise and a linear model: outliers or classification targets break conjugacy, and the Laplace approximation takes over. The posterior costs the inverse of an matrix, , which is expensive for tens of thousands of features. And type-II maximum likelihood plugs in point values of and ; with two hyperparameters and many points this costs little.
What you should remember#
- Prior , noise precision : the posterior is with and . Precisions add.
- The posterior mean is the ridge estimate with .
- The predictive is : noise plus weight uncertainty, small along the directions the data measure.
- Log evidence = fit at + log Occam factor; exact here, because is quadratic.
- MacKay’s fixed point: , , ; counts the well-determined parameters.
- With localized features the error bars collapse to the noise level far from the data.
Code#
The worked example, the agreement with ridge, the predictive standard deviation of the cubic model as the data grow, the two forms of the evidence, MacKay’s fixed point against scikit-learn’s BayesianRidge, and localized features far from the data. The script runs in about a second; exact numbers can differ in the last digit across platforms and library versions.
import numpy as np
from scipy.stats import multivariate_normal
from sklearn.linear_model import BayesianRidge
def posterior(Phi, t, alpha, beta):
"""Posterior N(mu, S) of the weights under the prior N(0, I/alpha) and noise precision beta."""
S = np.linalg.inv(alpha * np.eye(Phi.shape[1]) + beta * Phi.T @ Phi)
return beta * S @ Phi.T @ t, S
def predictive(phi, mu, S, beta):
"""Predictive mean and variance at the feature vectors in the rows of phi."""
return phi @ mu, 1 / beta + np.einsum('ij,jk,ik->i', phi, S, phi)
def log_evidence(Phi, t, alpha, beta):
n, m = Phi.shape
mu, S = posterior(Phi, t, alpha, beta)
E = beta / 2 * np.sum((t - Phi @ mu) ** 2) + alpha / 2 * mu @ mu
return m / 2 * np.log(alpha) + n / 2 * np.log(beta) - E + 0.5 * np.linalg.slogdet(S)[1] - n / 2 * np.log(2 * np.pi)
# the worked example: a line through three points, alpha = 1, beta = 4
Phi = np.array([[1, -1], [1, 0], [1, 1.0]])
t = np.array([-1, 0.5, 2.0])
mu, S = posterior(Phi, t, alpha=1.0, beta=4.0)
print(mu.round(4), np.diag(S).round(4)) # [0.4615 1.3333] [0.0769 0.1111]
print(np.linalg.solve(Phi.T @ Phi + 0.25 * np.eye(2), Phi.T @ t).round(4)) # [0.4615 1.3333]: ridge with lambda = alpha/beta
m, v = predictive(np.array([[1, 0], [1, 1], [1, 3.0]]), mu, S, beta=4.0)
print(m.round(3), v.round(3)) # [0.462 1.795 4.462] [0.327 0.438 1.327]
# 32 noisy points of sin(2.5 x), cubic features, alpha = 1 and the true noise precision beta = 25
rng = np.random.default_rng(3)
x = rng.uniform(-1, 1, 32).round(3)
t = (np.sin(2.5 * x) + 0.2 * rng.normal(size=32)).round(3)
feat = lambda x: np.vander(np.atleast_1d(x), 4, increasing=True)
grid = np.array([-1.5, -1.0, 0.0, 1.0, 1.5])
for n in (2, 8, 32): # predictive standard deviation at x = -1.5, -1, 0, 1, 1.5
mu, S = posterior(feat(x[:n]), t[:n], 1.0, 25.0)
print(n, np.sqrt(predictive(feat(grid), mu, S, 25.0)[1]).round(3))
# 2 [1.786 0.435 0.488 1.831 4.163] | 8 [1.585 0.364 0.228 0.747 2.501] | 32 [0.594 0.234 0.206 0.255 0.668]
# the evidence: the m x m form against the Gaussian N(0, I/beta + Phi Phi^T/alpha) over t
Phi = feat(x)
C = np.eye(32) / 25.0 + Phi @ Phi.T / 1.0
print(round(log_evidence(Phi, t, 1.0, 25.0), 4), round(multivariate_normal(np.zeros(32), C).logpdf(t), 4)) # -6.9188 -6.9188
# MacKay's fixed point for alpha and beta
alpha, beta = 1.0, 1.0
eig = np.linalg.eigvalsh(Phi.T @ Phi)
for _ in range(200):
mu, S = posterior(Phi, t, alpha, beta)
lam = beta * eig
gamma = np.sum(lam / (lam + alpha))
alpha, beta = gamma / (mu @ mu), (32 - gamma) / np.sum((t - Phi @ mu) ** 2)
print(round(alpha, 4), round(beta, 3), round(gamma, 3), round(log_evidence(Phi, t, alpha, beta), 4)) # 0.5551 22.294 3.945 -6.4286
br = BayesianRidge(fit_intercept=False, tol=1e-10, max_iter=1000).fit(Phi, t)
print(round(br.lambda_, 4), round(br.alpha_, 3)) # 0.5551 22.294: scikit-learn's lambda_ is the weight precision, alpha_ the noise precision
# localized features: nine Gaussian bumps of width 0.25 on [-1, 1], against the cubic, far from the data
centres = np.linspace(-1, 1, 9)
bumps = lambda z: np.exp(-(np.atleast_1d(z)[:, None] - centres) ** 2 / (2 * 0.25 ** 2))
far = np.array([0.0, 1.5, 2.0, 3.0])
for f in (bumps, feat):
mu, S = posterior(f(x), t, 1.0, 25.0)
m, v = predictive(f(far), mu, S, 25.0)
print(m.round(3), np.sqrt(v).round(3))
# [-0.144 0.069 0. 0. ] [0.218 0.206 0.2 0.2 ]: the bumps fall back to the noise level 0.2
# [ -0.066 -1.368 -6.721 -31.324] [0.206 0.668 1.641 5.79 ]
Next#
One precision for all weights shrinks them all alike and keeps every feature in the model. Giving each weight its own precision, and maximizing the evidence over all of them, has a surprising effect: most precisions go to infinity, their weights are pinned at zero, and the model keeps only a few features. The next note derives this automatic relevance determination and applies it to kernel features, where it gives the relevance vector machine, a sparse alternative to the support vector machine with predictive variances.
References#
- D. P. Vetrov, D. A. Kropotov. Bayesian Methods in Machine Learning (in Russian). Lecture course, Moscow State University, 2015. Lecture 4, slides (the matrix identities, Bayesian linear regression, the evidence by an exact Taylor expansion, the evidence updates).
- Bayesian Methods in Machine Learning (in Russian). Lecture course, HSE University, 2021. Lecture notes, lecture 4 (matrix derivatives, the posterior of linear regression through its mode, the limits of the prior precision).
- Конспект курса «Байесовские методы в анализе данных», 2026, github.com/bmml-team/bmml_ftda, лекция 2.
- C. M. Bishop. Pattern Recognition and Machine Learning. Springer, 2006. Section 3.3 (Bayesian linear regression; 3.3.2, the predictive distribution and localized basis functions), Section 3.5 (the evidence approximation; 3.5.1, the evidence; 3.5.3, the effective number of parameters).
- D. J. C. MacKay. Bayesian Interpolation. Neural Computation, 4(3), 415–447, 1992. Section 4 (choosing and , the number of good parameter measurements).
- D. J. C. MacKay. Information Theory, Inference, and Learning Algorithms. Cambridge University Press, 2003. Chapter 28 (model comparison and Occam’s razor).
- K. P. Murphy. Probabilistic Machine Learning: Advanced Topics. MIT Press, 2023. Section 15.2.2 (conjugate priors for linear regression, the posterior predictive).
- Cambridge 4F13 Probabilistic Machine Learning, 2025/26. Lecture “Bayesian inference and prediction in finite regression models”.