Compute the Bayesian linear regression posterior

HardRegressionPro

Why it matters Uncertainty-aware heads for active learning and bandits use this exact closed form.

Bayesian linear regression gives a mean and an uncertainty for every weight.

Write blr_posterior(X, y, alpha, beta). Prior w ~ N(0, I / alpha), noise precision beta. Return (m, S) where S = inv(alpha I + beta X^T X) and m = beta S X^T y.

Signaturedef blr_posterior(X, y, alpha, beta)

Example

X = [[1]], y = [2], alpha = 1, beta = 1 gives S = [[0.5]] and m = [1.0].

Understand the idea

Ordinary least squares gives you one best weight vector. Bayesian linear regression keeps a whole Gaussian belief over the weights instead: a mean m (your best guess) and a covariance S (how unsure you still are). The prior says the weights sit near zero with precision alpha, and every data point adds information scaled by the noise precision beta. Worked example: X = [[1], [1]], y = [2, 4], alpha = 1, beta = 1. X^T X = 2, so the posterior precision is 1 + 1 * 2 = 3 and S = [[1/3]]. X^T y = 6, so m = 1 * (1/3) * 6 = 2. The data average is 3, but the prior pulls the mean down to 2. Rule: A = alpha * I + beta * X^T X, S = inverse(A), m = beta * S * X^T y. Keep the beta in the mean; dropping it is only correct when beta is 1. Used in: Bayesian optimisation, uncertainty-aware last layers on top of neural features, and active learning, where S shows which inputs the model is least sure about.

Shapes and data flow

X^T X (d, d) + alpha I (d, d) -> precision (d, d)
S (d, d) @ X^T (d, n) @ y (n,) -> m (d,)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampleblr_posterior([[1]], [2], 1.0, 1.0)
  • Sample 2: strong priorblr_posterior(_X, _y, 50.0, 4.0)