Skip to content

Bayesian Linear Regression

Overview

Bayesian linear regression places priors on the coefficients of a linear model and conditions on observed responses:

\[ \sigma \sim \mathrm{HalfCauchy}(2),\quad \beta_0 \sim \mathcal{N}(0, 5),\quad \beta_1 \sim \mathcal{N}(0, 2),\quad y_n \mid x_n \sim \mathcal{N}(\beta_0 + \beta_1\,x_n,\ \sigma). \]

Here each Normal is parameterized by its mean and standard deviation. The predictor \(x\) is exogenous input data provided alongside the response at fit time. The runtime binds free identifiers in let expressions from undeclared keys in the observations mapping.

QVR source

# Bayesian Linear Regression
#
# A two-parameter linear model with a HalfCauchy prior on the
# noise scale and Normal priors on the regression coefficients.
# Exercises the core sample / let / observe pattern that every
# richer model in the gallery composes from.
#
# Generative structure:
#
#   sigma   ~ HalfCauchy(2)              noise scale
#   beta_0  ~ Normal(0, 5)               intercept
#   beta_1  ~ Normal(0, 2)               slope
#   y_n     ~ Normal(beta_0 + beta_1 * x_n, sigma)
#
# The predictor x is exogenous data: an (N,) tensor provided at
# fit time via the observations dict alongside the response y.
# The runtime's host-data channel binds free variables in let
# expressions from undeclared keys in the observations dict.

object Resp : FinSet 64
object Val : Real 1

program bayesian_regression : Resp -> Val
    let sigma <- sample HalfCauchy(scale=2.0)
    let beta_0 <- sample Normal(loc=0.0, scale=5.0)
    let beta_1 <- sample Normal(loc=0.0, scale=2.0)

    let mu = beta_0 + beta_1 * x

    observe y : Resp <- Normal(loc=mu, scale=sigma)
    return y

export bayesian_regression

Understanding the model

Suppose x is study time and y is a test score. The intercept describes the expected score at zero study time, the slope describes its change per unit of study time, and sigma describes variation around the line. The model puts distributions on all three because finite data leave them uncertain.

Each posterior draw specifies a possible line and noise level. Comparing slopes across draws gives uncertainty about the association. Generating a new response adds observation noise as well. An interval for a future score is thus different from an interval for the mean line. Neither calculation alone establishes a causal effect of study time.

Walkthrough

Resp : FinSet 64 indexes the 64 observed responses. The Normal family determines their real-valued type, and return y returns those responses. Val : Real 1 records the scalar type in the declared output annotation. The program guide explains how index annotations and value types differ.

The three sample lines draw the prior parameters as global scalars: let sigma <- sample HalfCauchy(scale=2.0) puts a heavy-tailed positive prior on the noise scale, and let beta_0 <- sample Normal(loc=0.0, scale=5.0), let beta_1 <- sample Normal(loc=0.0, scale=2.0) give the intercept and slope independent Gaussian priors with a wider spread on the intercept than on the slope.

let mu = beta_0 + beta_1 * x builds the linear predictor. x is not declared as a sample site or a program parameter. It is a free identifier resolved at run time from the host-data channel (the observations dict).

observe y : Resp <- Normal(loc=mu, scale=sigma) scores the observed response under the Gaussian likelihood, accumulating \(\log p(y \mid \mu, \sigma)\) into the program's score effect. return y projects the program's joint kernel onto the response site, and export bayesian_regression makes the program addressable from the loader.

DSL features

  • program keyword: Declares a probabilistic program with a type signature (InputType -> OutputType) and a monadic body.
  • <- (bind): Samples a random variable from a distribution. Subsequent statements can depend on the sampled value.
  • Distribution constructors: Normal, HalfCauchy, Exponential, Beta, Categorical, etc.
  • let: Deterministic computation over random variables. The result is a derived random variable.
  • observe: Scores provided data, multiplying the unnormalized model weight by the observation likelihood. Inference approximates the normalized posterior.
  • return: Designates the program's output value.
  • Arithmetic on random variables: +, -, *, / are supported directly.

Try it

The blocks below simulate from the model, check the compiled log joint against a hand-written density, and then recover the parameters with SVI (stochastic variational inference) and NUTS (No-U-Turn Sampler). The input x_in has one row, representing one run over the full data set.

Generating synthetic data

import torch
from quivers.dsl import load

torch.manual_seed(0)
prog = load("docs/examples/source/bayesian_regression.qvr")
model = prog.morphism

N = 64
true_sigma = torch.tensor(0.5)
true_beta_0 = torch.tensor(1.5)
true_beta_1 = torch.tensor(2.0)

x = torch.randn(N)
y = torch.distributions.Normal(true_beta_0 + true_beta_1 * x, true_sigma).sample()
observations = {"x": x, "y": y}
x_in = torch.zeros(1, 1)

Checking the log joint

D = torch.distributions
truth = {"sigma": true_sigma, "beta_0": true_beta_0, "beta_1": true_beta_1}
oracle = (
    D.HalfCauchy(2.0).log_prob(true_sigma)
    + D.Normal(0.0, 5.0).log_prob(true_beta_0)
    + D.Normal(0.0, 2.0).log_prob(true_beta_1)
    + D.Normal(true_beta_0 + true_beta_1 * x, true_sigma).log_prob(y).sum()
)
compiled = model.log_joint(x_in, {**truth, **observations}).sum()
print(f"compiled log joint: {float(compiled):.4f}")
print(f"torch log joint:    {float(oracle):.4f}")
assert torch.allclose(compiled, oracle, rtol=1e-5)

Fit through the checked interface

The same data can be bound without listing observed names or constructing a guide. For an inferred row count, replace object Resp : FinSet 64 with object Resp : FinSet _ in the source, then inspect bound.schema before inference. The binding guide gives a full source example.

from pathlib import Path
from quivers.modeling import Model, VariationalMethod

specification = Model(Path("docs/examples/source/bayesian_regression.qvr").read_text())
bound = specification.bind(observations)
fit = bound.infer(VariationalMethod(num_steps=2000, seed=7))
posterior = fit.draws(num_samples=500)
replicated = fit.predict(num_samples=100)

The following sections expose the guide and sampler components for the numerical checks used by this example.

SVI fit

A mean-field AutoNormalGuide is fit by SVI. With 64 rows and noise scale 0.5, the coefficients' standard errors are near 0.5 / sqrt(64) = 0.0625 and the noise scale's near 0.5 / sqrt(128) = 0.044, so the tolerances are four standard errors: 0.25 for each coefficient and 0.18 for sigma.

from quivers.inference import AutoNormalGuide, ELBO, SVI

tolerance = {"beta_0": 0.25, "beta_1": 0.25, "sigma": 0.18}

torch.manual_seed(1)
guide = AutoNormalGuide(model, observed_names={"x", "y"})
optim = torch.optim.Adam(guide.parameters(), lr=5e-2)
svi = SVI(model, guide, optim, ELBO(num_particles=1))
for _ in range(1500):
    svi.step(x_in, observations)

with torch.no_grad():
    draws = [guide.rsample(x_in) for _ in range(500)]
post = {k: float(torch.stack([d[k] for d in draws]).mean()) for k in tolerance}
for k, tol in tolerance.items():
    print(f"{k:>8}: posterior mean {post[k]:.3f}, truth {float(truth[k]):.3f}")
    assert abs(post[k] - float(truth[k])) < tol

NUTS posterior

NUTSKernel samples the same posterior over all 64 rows. Its posterior means should meet the same tolerances and agree with the SVI means to within half of each tolerance.

from quivers.inference import MCMC, NUTSKernel

torch.manual_seed(2)
kernel = NUTSKernel(step_size=0.05, max_tree_depth=4, target_accept=0.8)
mc = MCMC(kernel, num_warmup=100, num_samples=100, num_chains=1)
result = mc.run(model, x_in, observations)

for k, tol in tolerance.items():
    mean = float(result.samples[k].mean())
    print(f"{k:>8}: posterior mean {mean:.3f}, truth {float(truth[k]):.3f}")
    assert abs(mean - float(truth[k])) < tol
    assert abs(mean - post[k]) < tol / 2
print(f"divergences: {int(result.divergence_counts.sum())}")

Categorical perspective

A probability kernel assigns a probability distribution to each input. Such kernels compose by integration in the Kleisli category of the Giry monad (Giry, 1982). Writing \(T B\) for the space of probability measures on \(B\), sampling from \(f : A \to T B\) and then from \(g : B \to T C\) gives their composite \(g \circ_K f : A \to T C\). The prior draws of \(\beta_0\), \(\beta_1\), and \(\sigma\) compose with the Normal response kernel to define a joint distribution over parameters and observations.

Observing data weights this sampling distribution by a likelihood. The resulting measure need not have total mass one, so the scored program uses weighted-measure semantics (Staton, 2017). Bayes' rule defines the posterior \(P(\theta \mid y) \propto P(y \mid \theta)P(\theta)\) when the normalizing constant is finite and positive. Executing observe does not compute that constant. Variational inference and MCMC approximate quantities under this posterior.

Graphical-model view

A probabilistic program is a procedural encoding of a graphical model. Each <- statement is a node. Each observe statement is an observed variable. In this example: \(\beta_0\), \(\beta_1\), and \(\sigma\) are root nodes (no parents), \(\mu\) is computed from \(\beta_0\), \(\beta_1\), and \(x\), and \(y\) depends on \(\mu\) and \(\sigma\).

The same model specification can be fitted with SVI, HMC, or NUTS.

Extensions

Additional predictor variables and coefficients give a multivariable regression. Parametric program templates and plated group effects give hierarchical variants. A GP prior on the regression function gives a nonparametric variant.

See also

Cited sources

Michèle Giry. A Categorical Approach to Probability Theory. In B. Banaschewski, editor, Categorical Aspects of Topology and Analysis, volume 915 of Lecture Notes in Mathematics, pages 68–85. Springer, 1982. URL: https://link.springer.com/chapter/10.1007/BFb0092872, doi:10.1007/BFb0092872.

Sam Staton. Commutative Semantics for Probabilistic Programming. In Programming Languages and Systems (ESOP 2017), Lecture Notes in Computer Science, 855–879. Springer, 2017. doi:10.1007/978-3-662-54434-1_32.