TExcelTAD
Home › Math for Machine Learning › Bayesian Linear Regression

Bayesian Linear Regression

A point estimate says "the slope is 0.7". A Bayesian model says "the slope is probably between 0.6 and 0.8, and here is how sure I am at every input". Bayesian linear regression keeps the full posterior over parameters, which is Gaussian in closed form, and turns it into predictions with error bars that grow where data is scarce.

Prior, likelihood, posterior

Prior p(θ)=N(m0,S0)p(\boldsymbol{\theta}) = \mathcal{N}(\mathbf{m}_0, S_0), likelihood p(y∣X,θ)=N(Φθ,σ2I)p(\mathbf{y} \mid X, \boldsymbol{\theta}) = \mathcal{N}(\Phi\boldsymbol{\theta}, \sigma^2I). Both are Gaussian in θ\boldsymbol{\theta}, so the posterior is Gaussian (conjugacy):

p(θ∣X,y)=N(θ∣mN,SN)SN=(S0−1+σ−2ΦTΦ)−1mN=SN(S0−1m0+σ−2ΦTy)\begin{aligned} p(\boldsymbol{\theta} \mid X, \mathbf{y}) &= \mathcal{N}(\boldsymbol{\theta} \mid \mathbf{m}_N, S_N) \\ S_N &= \left(S_0^{-1} + \sigma^{-2}\Phi^T\Phi\right)^{-1} \\ \mathbf{m}_N &= S_N\left(S_0^{-1}\mathbf{m}_0 + \sigma^{-2}\Phi^T\mathbf{y}\right) \end{aligned}

Precisions (inverse covariances) add: prior precision plus data precision. With m0=0\mathbf{m}_0 = \mathbf{0} and S0=b2IS_0 = b^2I, the posterior mean is exactly the ridge / MAP estimate with λ=σ2/b2\lambda = \sigma^2/b^2. The new information is SNS_N.

The predictive distribution

For a new input x∗\mathbf{x}_* with features ϕ∗\boldsymbol{\phi}_*, average the prediction over the posterior:

p(y∗∣x∗,X,y)=N ⁣(ϕ∗TmN, ϕ∗TSNϕ∗+σ2)p(y_* \mid \mathbf{x}_*, X, \mathbf{y}) = \mathcal{N}\!\left(\boldsymbol{\phi}_*^T\mathbf{m}_N,\ \boldsymbol{\phi}_*^TS_N\boldsymbol{\phi}_* + \sigma^2\right)

The variance has two parts: parameter uncertainty ϕ∗TSNϕ∗\boldsymbol{\phi}_*^TS_N\boldsymbol{\phi}_*, which shrinks with more data, and noise σ2\sigma^2, which never does.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
x = np.concatenate([rng.uniform(-3, -1, 8), rng.uniform(1, 2, 8)])     # a gap in (-1, 1), nothing beyond 2
y = 0.5 * x - 0.3 * x**2 + 0.3 * rng.normal(size=16)
Phi = lambda x: np.column_stack([np.ones_like(x), x, x**2])
sigma2, b2 = 0.3**2, 4.0
S0_inv = np.eye(3) / b2
SN = np.linalg.inv(S0_inv + Phi(x).T @ Phi(x) / sigma2)
mN = SN @ (Phi(x).T @ y / sigma2)
print("posterior mean:", np.round(mN, 3))
print("posterior std: ", np.round(np.sqrt(np.diag(SN)), 3))
for xs in (-2.0, 0.0, 1.5, 4.0):
    p = Phi(np.array([xs]))[0]
    print(f"x*={xs:4}: mean {p @ mN:7.3f}   std {np.sqrt(p @ SN @ p + sigma2):.3f}   (parameter part {np.sqrt(p @ SN @ p):.3f})")
posterior mean: [-0.038  0.466 -0.295]
posterior std:  [0.148 0.05  0.039]
x*=-2.0: mean  -2.148   std 0.319   (parameter part 0.107)
x*= 0.0: mean  -0.038   std 0.334   (parameter part 0.148)
x*= 1.5: mean  -0.002   std 0.317   (parameter part 0.104)
x*= 4.0: mean  -2.890   std 0.712   (parameter part 0.646)

Inside the data the predictive standard deviation is close to the noise level 0.3; in the gap it grows a little, and far outside the data (at x=4x = 4) the parameter uncertainty dominates. A plain least-squares fit would give no warning at all.

Sequential learning

Because the posterior is Gaussian, today's posterior is tomorrow's prior: feeding data in batches and updating (m,S)(\mathbf{m}, S) each time gives exactly the same result as using all data at once.

python · try it yourself
import numpy as np

rng = np.random.default_rng(1)
x = rng.uniform(-1, 1, 40); y = 1.0 + 2.0 * x + 0.2 * rng.normal(size=40)
Phi = np.column_stack([np.ones_like(x), x]); s2 = 0.04
def update(m, S, P, t):
    S_new = np.linalg.inv(np.linalg.inv(S) + P.T @ P / s2)
    return S_new @ (np.linalg.inv(S) @ m + P.T @ t / s2), S_new
m, S = np.zeros(2), np.eye(2) * 10
for k in range(0, 40, 10):
    m, S = update(m, S, Phi[k:k + 10], y[k:k + 10])
m_all, S_all = update(np.zeros(2), np.eye(2) * 10, Phi, y)
print("sequential:", np.round(m, 6), " all at once:", np.round(m_all, 6), " same:", np.allclose(m, m_all) and np.allclose(S, S_all))
sequential: [0.97368  1.932839]  all at once: [0.97368  1.932839]  same: True

In software

  • sklearn.linear_model.BayesianRidge and ARDRegression also learn σ2\sigma^2 and the prior scale from the data (by maximizing the evidence).
  • Gaussian processes are Bayesian linear regression with infinitely many features.
  • Bandits and active learning query where the predictive variance is large.

Exercises

Exercise 1: One parameter

Model y=θx+ϵy = \theta x + \epsilon, prior θ∼N(0,1)\theta \sim \mathcal{N}(0, 1), σ2=1\sigma^2 = 1, one data point (x,y)=(2,3)(x, y) = (2, 3). Find the posterior.

Answer

N(1.2,0.2)\mathcal{N}(1.2, 0.2).

Solution

SN=(1+4)−1=0.2S_N = (1 + 4)^{-1} = 0.2, mN=0.2⋅(2⋅3)=1.2m_N = 0.2 \cdot (2 \cdot 3) = 1.2. The ML estimate would be 3/2=1.53/2 = 1.5; the prior pulls it towards 0.

Exercise 2: Never below the noise

Can the predictive variance ever be smaller than σ2\sigma^2?

Answer

No.

Solution

It is ϕ∗TSNϕ∗+σ2\boldsymbol{\phi}_*^TS_N\boldsymbol{\phi}_* + \sigma^2 and SNS_N is positive semidefinite, so the first term is ≥0\ge 0. Infinite data can remove parameter uncertainty, not noise.

Exercise 3: Posterior shrinks with data (code)

For y=θx+ϵy = \theta x + \epsilon with prior N(0,1)\mathcal{N}(0, 1) and σ2=1\sigma^2 = 1, print the posterior standard deviation of θ\theta after N=1,10,100N = 1, 10, 100 points with x=1x = 1.

Answer

1/N+11/\sqrt{N + 1}: about 0.7070.707, 0.3020.302, 0.09950.0995.

Solution

SN=(1+N)−1S_N = (1 + N)^{-1} because each point adds precision x2/σ2=1x^2/\sigma^2 = 1.

python · try it yourself
for N in (1, 10, 100):
    print(N, round((1 / (1 + N)) ** 0.5, 4))
1 0.7071
10 0.3015
100 0.0995

Test yourself

With prior N(0,b2I)\mathcal{N}(\mathbf{0}, b^2I), the posterior mean of Bayesian linear regression equals…

  1. the ML estimate
  2. the ridge (MAP) estimate with λ=σ2/b2\lambda = \sigma^2/b^2
  3. zero
  4. the data mean

The predictive variance is largest…

  1. where training data is dense
  2. far from the training data
  3. at the origin always
  4. it is constant

In the posterior covariance formula, the precision of the posterior is…

  1. the prior precision minus the data precision
  2. the prior precision plus the data precision σ−2ΦTΦ\sigma^{-2}\Phi^T\Phi
  3. always the identity
  4. the data precision only