Operational review: Gaussian algebra, multivariate conjugacy and exponential families
A dense review of the module's prerequisites, including priors, posteriors and predictive distributions (m05), Gaussian conditioning, information form and the linear Gaussian model (m04), and stable Cholesky computation (m09). Two frequently used tools build on this foundation: multivariate conjugate priors (Normal-gamma and Normal-Wishart, with Student t predictive distributions) and moment-matching projection onto an exponential family, the engine of ADF and expectation propagation.
After this lesson you can
- Condition and marginalize Gaussians and apply the linear Gaussian model, recognizing it in Kalman filters, GPs and Bayesian regression.
- Implement multivariate Gaussian log density and sampling with Cholesky without matrix inversion.
- Update a Normal-gamma or Normal-Wishart prior using sufficient statistics and obtain its Student t predictive distribution.
- Prove that minimizing KL(p ‖ q) over an exponential family is equivalent to matching moments of its sufficient statistics.
- Calculate the moment-matched Gaussian for a tilted distribution formed by a Gaussian times a probit or step factor.
Before you start
- 05Prior, likelihood and posteriorPosterior predictive distributionConjugate priorsExponential familyBayes rule and Bayes riskLoss and risk functions
- 04Gaussian conditioningGaussian marginalizationLinear-Gaussian modelGaussian sampling via Cholesky
- 07Forward versus reverse KL
- 02Schur complementSherman-Morrison-Woodbury identity
Model, infer, decide
This module comes down to three verbs. Modeling means writing the joint distribution of what you observe, , and what you cannot see but want to know, or : . Inferring means conditioning: . Deciding means choosing the action that minimizes expected loss under that conditional. The lessons ahead provide ways to perform the second verb when the quotient cannot be calculated by hand: graphs that factorize the joint distribution (lessons 2 to 5), latent-variable models and filters (9 to 15), Gaussian processes (16 and 20), variational approximations (18 and 19), and sampling (21 to 23).
This lesson is an operational review of what the rest assumes you know. “Operational” means you are not reviewing theory for its own sake: you are putting the tools needed to solve almost everything in the module at your fingertips.
- Gaussians. Conditioning and marginalization, information form, the linear Gaussian model and how to compute all of them without inverting matrices. They appear in different guises in the Kalman filter, Bayesian regression and Gaussian processes.
- Multivariate conjugacy. What happens when, besides the mean, the variance or covariance is also unknown: Normal-gamma and Normal-Wishart priors and their Student predictive distribution.
- Moment-matching projection. How to approximate a non-Gaussian distribution by a Gaussian and why the correct answer for divergence is to match means and covariances. This drives assumed-density filtering and expectation propagation.
The reviews of statistics and inference and of probability move faster than the original lessons; the new material, multivariate conjugacy and projection, is covered in full detail.
Posterior, predictive distribution and Bayes action
Recall the three objects of Bayesian inference. A parametric model supplies the likelihood ; a prior supplies ; Bayes’ theorem gives the posterior , where is the evidence. To predict a new observation, rather than using an estimated parameter, average over all parameters considered plausible by the posterior,
which is the posterior predictive distribution. With the known-variance normal from the Bayesian inference lesson (prior , noise , nine observations with mean ), the posterior is and the predictive distribution is : predictive variance combines two sources, observation noise and remaining uncertainty about . Keep this idea in mind: once variance is also unknown, the second source changes the shape of the predictive distribution, not just its width.
Decision closes the cycle. Given a loss , the expected posterior loss of action is , and the Bayes action minimizes it (Bayes decision rule).
Proof
(1) , minimized at . (2) Differentiating under the expectation gives , which changes sign at a median. (3) , minimized where posterior mass is greatest.
∎The practical consequence is that the posterior contains everything needed to decide, while the loss chooses a summary of it. This module therefore focuses on calculating posteriors: the posterior mean for estimation, the predictive distribution for forecasting and the entire posterior for decisions under asymmetric risk.
Conditioning a Gaussian: slice rather than project
This is the most frequently used calculation in the module, and it has a closed form. Partition a Gaussian vector into two blocks, , with mean and covariance , with .
Proof
Define the residual . It is a linear function of , so is jointly Gaussian, and its cross-covariance is . Jointly Gaussian and uncorrelated variables are independent, so conditioning on does not change the law of : it remains with (expand using ). Since , given the only random part is , yielding the stated mean and covariance.
∎The figure reveals a geometric interpretation of the proof. The conditional mean is the orthogonal projection of onto what you know (, the best linear predictor), and is what remains unexplained. The conditional distribution is a renormalized slice of the joint density, rather than its projection onto an axis.
The figure shows the theorem in two dimensions. With ,
- The conditional mean is affine in . It follows the orange line, the regression of on , with slope . With zero correlation the line is vertical: observing moves nothing.
- Conditional variance does not depend on . The orange band has constant width. In the proof, the residual is independent of . This is a property of the Gaussian, not of conditioning generally. For the uniform distribution on a disk, the slice is a segment of length , and the variance of given equals , which does depend on (for a unit radius here).
- Width depends only on the shape of the ellipse. With a circular ellipse (), the slice has the same variance as the marginal. The narrower the ellipse (the higher the correlation), the narrower the slice, with the ratio shown in the figure. In the limit of a degenerate ellipse, the observation almost completely fixes .
This is why, later in the Kalman filter, posterior covariance can be calculated without seeing a single observation.
Information form: precisions add
There is a second way to write a Gaussian, more convenient when multiplying densities. If is the precision and the information vector, then
This is the natural form of the exponential family (with sufficient statistic ), and multiplying densities adds exponents.
The proof takes one line: the log of the product is the sum of the logs, each a quadratic in ; the sum is a quadratic with precision and linear terms added.
Sensor fusion. Two sensors measure the same position: . With a flat prior over , the posterior is the product of the two likelihoods viewed as functions of ( is symmetric in and ), so
The posterior mean is a precision-matrix-weighted average: each sensor pulls harder in directions where it is precise. The scalar case has weights proportional to .
Notice three things in the figure.
- The posterior inherits what each sensor does well. Initially, A fixes most of coordinate and B fixes , and the posterior is a small, nearly circular ellipse, much smaller than either one. Neither sensor alone could locate the point; together they can.
- Precisions add, covariances do not. In any unit direction , (shown live in the panel). Averaging covariances, , is a common error: it gives an ellipse that improves on neither sensor because it ignores accumulating information.
- It never gets worse. If then in the Loewner order. Proof: has all eigenvalues , so , and reversing the change gives . More observations never increase Gaussian uncertainty in any direction.
Information form has another advantage used in lessons 3 and 4: zeros of represent conditional independences, because the precision of the conditional of given the rest is the block , and the conditional mean depends on only through nonzero blocks of . Updating with data is addition, without inversion: this is the information filter.
The linear Gaussian model
Almost everything Gaussian in the module is an instance of one model. If and, given , the observation is an affine function with Gaussian noise, , you have the linear Gaussian model.
Proof
The joint distribution of is Gaussian (everything is affine in Gaussian noise), and gives mean , covariance and cross-covariance . Gain form follows from the conditioning theorem with and . Information form comes from multiplying prior and likelihood: appears in the exponent as , a quadratic whose term quadratic in is and whose linear term is . The two forms coincide by the Woodbury identity.
∎Two consequences are reusable. First, does not depend on , only on , and , the same phenomenon as the constant-width band. Second, the forms have different costs. Gain form inverts, or better factorizes, a matrix sized by the observation, ; information form uses one sized by the unknown, . Choose the smaller: this distinguishes a Kalman filter with few measurements from regression with many parameters and little data, or vice versa.
Where to recognize it:
| When you see | |||
|---|---|---|---|
| Sensor fusion (above) | position | the two stacked measurements | two blocks |
| Bayesian linear regression (lesson 6) | weights | targets | design matrix |
| Kalman filter correction step (lesson 12) | state, using prediction as prior | measurement | observation matrix |
| Regression with Gaussian processes (lesson 16) | function values at training and test points | noisy observed values | a selection of coordinates |
Stable computation: Cholesky instead of inverses
The formulas above write and for clarity; serious code does not calculate them that way. With Cholesky factorization ( lower triangular with positive diagonal), everything reduces to triangular systems:
The log determinant is (because ), the quadratic form is the norm of the solution of by forward substitution, and sampling is a triangular multiplication. Factorize once in roughly operations and reuse the factor.
First, the kit, built from scratch and checked against SciPy. The following lessons will use mvn_logpdf_chol, mvn_sample_chol, condition_gaussian (the theorem above) and linear_gaussian_posterior (gain form, which also returns evidence ).
import numpy as np
from scipy.linalg import cholesky, cho_solve, solve_triangular
from scipy import stats
def mvn_logpdf_chol(x, mu, L):
"""log N(x | mu, L L^T) sin inversas ni determinantes. x puede ser (d,) o (m, d)."""
X = np.atleast_2d(x) - mu
z = solve_triangular(L, X.T, lower=True) # z = L^{-1}(x - mu), una columna por punto
d = L.shape[0]
logdet = 2.0 * np.log(np.diag(L)).sum()
return -0.5 * (d * np.log(2 * np.pi) + logdet + (z ** 2).sum(axis=0))
def mvn_sample_chol(mu, L, size, rng):
return mu + rng.standard_normal((size, len(mu))) @ L.T
def condition_gaussian(mu, Sigma, obs, x_obs):
"""Condicional de las coordenadas libres dadas las observadas (obs: índices)."""
free = np.setdiff1d(np.arange(len(mu)), obs)
Sab = Sigma[np.ix_(free, obs)]
Lb = cholesky(Sigma[np.ix_(obs, obs)], lower=True)
G = cho_solve((Lb, True), Sab.T).T # Sab Sbb^{-1}
m = mu[free] + G @ (x_obs - mu[obs])
C = Sigma[np.ix_(free, free)] - G @ Sab.T # complemento de Schur
return m, 0.5 * (C + C.T)
def linear_gaussian_posterior(m, P, H, b, R, y):
"""x ~ N(m, P), y | x ~ N(Hx + b, R). Devuelve media, covarianza posteriores y log p(y)."""
S = H @ P @ H.T + R
Ls = cholesky(S, lower=True)
K = cho_solve((Ls, True), H @ P).T # ganancia P H^T S^{-1}
mean = m + K @ (y - (H @ m + b))
cov = P - K @ H @ P
return mean, 0.5 * (cov + cov.T), mvn_logpdf_chol(y, H @ m + b, Ls)[0]
rng = np.random.default_rng(0)
d = 5
A = rng.normal(size=(d, d)); Sigma = A @ A.T + d * np.eye(d); mu = rng.normal(size=d)
L = cholesky(Sigma, lower=True)
X = mvn_sample_chol(mu, L, 20000, rng)
ref = stats.multivariate_normal(mu, Sigma).logpdf(X[:5])
print("logpdf: diferencia máxima con scipy =", np.abs(mvn_logpdf_chol(X[:5], mu, L) - ref).max())
print("muestreo: error relativo de la covarianza muestral =", np.abs(np.cov(X.T) - Sigma).max() / np.abs(Sigma).max())
# condicionar: Schur frente a la forma de información (la precisión condicional es un bloque de Λ)
obs = np.array([1, 3]); free = np.array([0, 2, 4]); x_obs = rng.normal(size=2)
m1, C1 = condition_gaussian(mu, Sigma, obs, x_obs)
Lam = np.linalg.inv(Sigma)
C2 = np.linalg.inv(Lam[np.ix_(free, free)])
m2 = mu[free] - C2 @ Lam[np.ix_(free, obs)] @ (x_obs - mu[obs])
print("Schur frente a información: media", np.abs(m1 - m2).max(), " covarianza", np.abs(C1 - C2).max())
print("covarianza condicional con otro dato: cambia en", np.abs(C1 - condition_gaussian(mu, Sigma, obs, x_obs + 3.0)[1]).max())
# modelo lineal gaussiano: ganancia frente a información, y evidencia frente a scipy
dx, dy = 4, 2
P = 2 * np.eye(dx); m0 = rng.normal(size=dx); H = rng.normal(size=(dy, dx)); R = np.diag([0.5, 0.2]); b = np.zeros(dy)
y1 = rng.normal(size=dy)
mean, cov, logev = linear_gaussian_posterior(m0, P, H, b, R, y1)
Pi = np.linalg.inv(np.linalg.inv(P) + H.T @ np.linalg.inv(R) @ H)
mi = Pi @ (np.linalg.inv(P) @ m0 + H.T @ np.linalg.inv(R) @ (y1 - b))
print("ganancia frente a información: media", np.abs(mean - mi).max(), " covarianza", np.abs(cov - Pi).max())
print("evidencia frente a scipy:", logev - stats.multivariate_normal(H @ m0 + b, H @ P @ H.T + R).logpdf(y1))
print("covarianza posterior con otro dato: cambia en", np.abs(cov - linear_gaussian_posterior(m0, P, H, b, R, y1 + 5)[1]).max())All differences are on the order of rounding except sampling, which is statistical, and the posterior covariance does not change however much the observation changes. Now for the question motivating this section: what does Cholesky really gain? We measure it using the matrix that causes most trouble later in the module, a Gaussian (RBF) kernel at very close points, which is nearly singular.
import time
from scipy.linalg import cho_factor
x = np.sort(np.random.default_rng(1).uniform(0, 1, 200))
r = x[:, None] - x[None, :]
print("varianza mínima de f dado el propio f en los mismos puntos, K - K K^{-1} K (en aritmética exacta, 0):")
print(f"{'jitter':>8} {'cond(K)':>10} {'con Cholesky':>14} {'con inversa':>13}")
for jit in (1e-6, 1e-8, 1e-10):
K = np.exp(-0.5 * (r / 0.2) ** 2) + jit * np.eye(200)
w = np.linalg.eigvalsh(K)
Lk = cholesky(K, lower=True)
V = solve_triangular(Lk, K, lower=True) # L^{-1} K
var_chol = np.diag(K) - (V ** 2).sum(axis=0)
var_inv = np.diag(K) - np.einsum('ij,ij->j', K, np.linalg.inv(K) @ K)
print(f"{jit:8.0e} {w[-1] / w[0]:10.1e} {var_chol.min():14.1e} {var_inv.min():13.1e}")
try:
cholesky(np.exp(-0.5 * (r / 0.2) ** 2), lower=True)
print("sin jitter: Cholesky no falla")
except np.linalg.LinAlgError as e:
print("sin jitter, Cholesky avisa:", e)
d = 200
L0 = 1e-2 * np.eye(d)
S0 = L0 @ L0.T
print("\ndet(Σ) =", np.linalg.det(S0), " log(det Σ) =", np.log(np.linalg.det(S0)), " 2 Σ log diag L =", 2 * np.log(np.diag(L0)).sum())
rng = np.random.default_rng(2)
n = 300
M = rng.normal(size=(n, n)); S = M @ M.T + n * np.eye(n); bb = rng.normal(size=n)
t = time.perf_counter()
for _ in range(3): np.linalg.inv(S) @ bb
t_inv = (time.perf_counter() - t) / 3
t = time.perf_counter()
for _ in range(3): cho_solve(cho_factor(S, lower=True), bb)
t_chol = (time.perf_counter() - t) / 3
print(f"n = {n}: razón de tiempos inversa / Cholesky = {t_inv / t_chol:.1f}")Read the output carefully, because it differs from the usual account. The cell conditions vector on its own values: conditional covariance is exactly , so any nonzero value is rounding error. With the explicit inverse it becomes negative and grows with conditioning (, and for , and ), whereas Cholesky stays at , machine epsilon, regardless of . A negative variance in a filter or Gaussian process breaks subsequent calculations such as a square root or log density. However, for solving a single system the accuracy of the explicit inverse is comparable to Cholesky: Druinsky and Toledo (2012, “How accurate is inv(A)*b?”) show that, with a conventionally computed inverse, is as accurate as the solution from the best backward-stable methods. Both lose on the order of digits, because that loss belongs to the problem (its condition number ), not the method. What inversion does not provide is:
- Symmetry and positivity. The computed is not exactly symmetric or positive definite, and products built with it inherit the defect.
- Diagnostics. Cholesky raises an exception when the matrix is not numerically positive definite, precisely what you need to know. Inversion can return garbage without warning.
- The determinant. comes for free from the diagonal; overflows at moderate dimensions, as output with shows.
- Cost. Forming the inverse takes roughly operations versus for Cholesky, and the printed timing ratio confirms it is several times slower (the exact figure varies between runs).
Jitter, adding to the diagonal, shifts every eigenvalue upward, so : that permits factorization. This changes the model (equivalent to observation noise of variance ) and is not an innocuous numerical trick; Cholesky stability and jitter are studied in numerical methods.
In production you would use scipy.linalg.cho_factor and cho_solve (which retain the factor and reuse LAPACK), or scipy.stats.multivariate_normal, which accepts a semidefinite covariance and handles it with an eigendecomposition. They and your kit agree; yours makes each operation visible.
Unknown noise: Normal-gamma
So far the noise variance was known. It almost never is. We want a closed-form joint posterior over weights and noise precision , as with a normal of known variance. The key, as in every conjugate family, is a prior with the same functional form as the likelihood viewed as a function of the parameters.
The likelihood of with design matrix is . As a function of it is (a gamma kernel), and as a function of for fixed it is Gaussian with precision . This suggests a prior in which precision of scales with :
Interpret it as pseudo-observations: noise observations with mean variance , and confidence in measured in units of .
Proof
Multiply likelihood and prior. The powers of are (data), (the prior on ) and (that on ). The exponent is . Expand and group by powers of :
Completing the square yields with as stated. What remains is : a gamma in times a Gaussian of precision in .
∎Look at : term grows when the prior on and the data disagree. Thus, the model learns that noise is larger when the prior does not fit the data; for a sample mean (, , ) this is , with . Since , and only add terms from each observation, update one observation at a time using each posterior as the next prior: sequential and batch updates agree, a property used in all the filters.
Student t: a scale mixture
The marginal posterior of and the predictive distribution are no longer Gaussian. This is a consequence of integrating uncertainty over .
Proof
With , by the gamma integral. Since , , the density of the with .
∎The mixture explains the tails. A is a continuous mixture of Gaussians at different scales, and large-variance components dominate far from the center: density decays as (a power) rather than . With it is Cauchy, with no mean; with there is no variance. When the gamma concentrates, meaning with fixed, the mixing distribution collapses to a point and approaches a Gaussian.
Apply this to regression. Integrating and then (first and then the theorem), the predictive distribution at a point with features is
and the weight marginal is . The degrees of freedom are : each observation contributes one degree, and with little data the tails are heavy because the variance is poorly known. This is why, estimating a mean from five observations with unknown variance, the 95 % interval uses 2.776 ( with 4 degrees) rather than 1.96, as in elementary statistics. In the improper limit , , (the joint prior density is proportional to , flat in ), the posterior is proper if and has degrees: it is the of the classical least-squares prediction interval. We verify this and measure coverage.
import numpy as np
from scipy import stats
def normal_gamma_update(m0, Lam0, a0, b0, Phi, y):
Lamn = Lam0 + Phi.T @ Phi
mn = np.linalg.solve(Lamn, Lam0 @ m0 + Phi.T @ y)
an = a0 + len(y) / 2
bn = b0 + 0.5 * (y @ y + m0 @ Lam0 @ m0 - mn @ Lamn @ mn)
return mn, Lamn, an, bn
def predictive_t(phi, mn, Lamn, an, bn):
"""t con 2 an grados, posición phi.mn y escala^2 = (bn/an)(1 + phi^T Lamn^{-1} phi)."""
return 2 * an, phi @ mn, np.sqrt(bn / an * (1 + phi @ np.linalg.solve(Lamn, phi)))
rng = np.random.default_rng(0)
n = 5
x = np.linspace(-1, 1, n); Phi = np.column_stack([np.ones(n), x])
w_true, sigma = np.array([1.0, 2.0]), 0.5
y = Phi @ w_true + sigma * rng.normal(size=n)
p = 2
m0, Lam0, a0, b0 = np.zeros(p), 1e-6 * np.eye(p), -p / 2, 0.0 # límite impropio (plano en w, 1/sigma^2 en lambda): df = n - p
mn, Lamn, an, bn = normal_gamma_update(m0, Lam0, a0, b0, Phi, y)
phi_star = np.array([1.0, 0.5])
df, loc, sc = predictive_t(phi_star, mn, Lamn, an, bn)
# 1) frente al intervalo de predicción clásico de mínimos cuadrados (t con n - p grados)
w_hat = np.linalg.solve(Phi.T @ Phi, Phi.T @ y); s2 = ((y - Phi @ w_hat) ** 2).sum() / (n - 2)
sc_ols = np.sqrt(s2 * (1 + phi_star @ np.linalg.solve(Phi.T @ Phi, phi_star)))
print(f"bayesiano: df = {df:.3f}, escala = {sc:.4f} MCO: df = {n - 2}, escala = {sc_ols:.4f}")
# 2) frente a Monte Carlo: lambda ~ Gamma(an, tasa bn), w | lambda, y* | w, lambda
N = 200000
lam = rng.gamma(an, 1 / bn, size=N)
Lc = np.linalg.cholesky(np.linalg.inv(Lamn))
w_s = mn + (rng.normal(size=(N, 2)) @ Lc.T) / np.sqrt(lam)[:, None]
y_s = w_s @ phi_star + rng.normal(size=N) / np.sqrt(lam)
q = [0.025, 0.5, 0.975]
print("cuantiles Monte Carlo:", np.round(np.quantile(y_s, q), 3))
print("cuantiles de la t :", np.round(stats.t.ppf(q, df, loc, sc), 3))
# 3) cobertura del intervalo central del 95 %: t frente a gaussiana con la MISMA posición y escala
print("\ncuantil 0.975 de la t:", {nu: round(float(stats.t.ppf(0.975, nu)), 3) for nu in (2, 4, 9, 29, 99)}, " gaussiana: 1.960")
R = 4000
print(f"{'n':>4} {'grados':>7} {'cobertura t':>12} {'cobertura gaussiana':>20} (error típico de Monte Carlo ≈ 0.003)")
for n in (3, 5, 10, 40):
x = np.linspace(-1, 1, n); Phi = np.column_stack([np.ones(n), x])
Lamn = Lam0 + Phi.T @ Phi
G = np.linalg.solve(Lamn, Phi.T) # mn = G y (con m0 = 0)
Y = Phi @ w_true + sigma * rng.normal(size=(R, n))
M = Y @ G.T
an = a0 + n / 2
bn = b0 + 0.5 * ((Y ** 2).sum(1) - np.einsum('ri,ij,rj->r', M, Lamn, M))
sc = np.sqrt(bn / an * (1 + phi_star @ np.linalg.solve(Lamn, phi_star)))
y_new = phi_star @ w_true + sigma * rng.normal(size=R)
err = np.abs(y_new - M @ phi_star)
print(f"{n:4d} {2 * an:7.2f} {np.mean(err <= stats.t.ppf(0.975, 2 * an) * sc):12.3f} {np.mean(err <= 1.96 * sc):20.3f}")The output matches the theory. The improper prior reproduces the classical least-squares prediction interval (3 degrees and scale in both cases), and quantiles match those from mixture simulation to the third digit. A Gaussian interval with the same location and scale covers less than 95 % with little data: 70 % with (one degree of freedom, a Cauchy), 85 % with , 91.5 % with and 94.1 % with , while the interval covers 95 % in every case within Monte Carlo error. The Gaussian with “estimated” variance is not wrong in the limit; it is wrong for the data you have.
Unknown mean and covariance: Normal-Wishart
With a full covariance, precision becomes a matrix and the Wishart takes the gamma’s role. We use Bishop’s convention (2006, §2.3.6), in which is the scale matrix and the mean is .
A model with unknown mean and precision has the following likelihood in terms of sufficient statistics , and . The Normal-Wishart prior , is conjugate.
Proof
Use in the likelihood, . The prior contributes . The two quadratics in add as in the scalar case:
where “=” means equality after taking the trace against (check by matching coefficients of , and the constant term). The exponent becomes and the powers of sum to for the Wishart plus for the normal in .
∎Read this as pseudo-observations. The prior corresponds to vectors with scatter (so a reasonable guide is with your best estimate of covariance) and observations of the mean at . The posterior adds both scatters and adds a term for disagreement between prior and data means, analogous to the term in .
The predictive distribution follows from the same scale-mixture trick, with a short proof.
Proof
First integrate : with and , so with . With , now mix over :
because the integral is the normalization constant of a Wishart with degrees. By the matrix determinant lemma, . Compare with the multivariate , : gives , and gives the stated scale matrix.
∎For , and the degrees of freedom are , as in the previous section.
Initially, with four points and a weak prior, , , , the 95 % region has 6.5 times the area of the Gaussian with estimated parameters, and it needs that area: of 3000 new points from the true distribution, covers 98 % and the Gaussian only 54 %. With 10 points (press “+5” and “+1”) the area ratio falls to 2.1 and coverage becomes 98 % and 83 %; with 30 it becomes 1.3, 96 % and 91 %. shrinks toward the Gaussian as degrees of freedom rise and estimated covariance stabilizes; the posterior mean of , still almost the prior with four points (), has learned the correlation by 30 points ( versus true ). These coverages are from one dataset: the 95 % guarantee averages over datasets, as measured by the cell below. The prior matters: with large and an incorrect scale the cloud concentrates in the wrong place and data takes time to shift it. This makes the usual prior-data tension visible.
Validate the update and predictive distribution by simulation and measure calibration of the predictive region. The noninformative-prior limit in Bishop’s convention is , and (proper for ): the predictive distribution is with degrees and scale , exactly Hotelling’s prediction region.
import numpy as np
from scipy import stats
def normal_wishart_update(m0, kappa0, nu0, W0, X):
X = np.atleast_2d(X); n = X.shape[0]
xbar = X.mean(axis=0); S = (X - xbar).T @ (X - xbar)
kn = kappa0 + n; mn = (kappa0 * m0 + n * xbar) / kn; nun = nu0 + n
dm = (xbar - m0)[:, None]
Wn_inv = np.linalg.inv(W0) + S + (kappa0 * n / kn) * (dm @ dm.T)
return mn, kn, nun, np.linalg.inv(Wn_inv)
def predictive_t_params(mn, kn, nun, Wn):
d = len(mn); df = nun - d + 1
return df, mn, (kn + 1) / (kn * df) * np.linalg.inv(Wn)
rng = np.random.default_rng(0)
d = 2
m0, kappa0, nu0, W0 = np.array([0.5, -0.5]), 2.0, 5, np.array([[0.4, 0.1], [0.1, 0.3]])
X = rng.normal(size=(6, d)) * [1.0, 0.7] + [1.0, 0.0]
# 1) secuencial = por lotes
post = (m0, kappa0, nu0, W0)
for x in X:
post = normal_wishart_update(*post, x[None, :])
batch = normal_wishart_update(m0, kappa0, nu0, W0, X)
print("secuencial frente a lotes (máxima diferencia):", max(np.abs(np.asarray(a) - np.asarray(b)).max() for a, b in zip(post, batch)))
# 2) predictiva: simulación directa de (Lambda, mu, x*) frente a la t
mn, kn, nun, Wn = batch
df, loc, shape = predictive_t_params(mn, kn, nun, Wn)
N = 40000
Lam = stats.wishart(df=nun, scale=Wn).rvs(size=N, random_state=1)
Sig = np.linalg.inv(Lam)
Lc = np.linalg.cholesky(Sig)
mu_s = mn + np.einsum('nij,nj->ni', Lc, rng.normal(size=(N, d))) / np.sqrt(kn)
xs = mu_s + np.einsum('nij,nj->ni', Lc, rng.normal(size=(N, d)))
print(f"grados de libertad de la t = {df}; media simulada {np.round(xs.mean(0), 3)} frente a {np.round(mn, 3)}")
print("covarianza simulada:", np.round(np.cov(xs.T), 3).tolist(), " de la t:", np.round(shape * df / (df - 2), 3).tolist())
r2 = df * (0.05 ** (-2 / df) - 1) # Pr(delta^2 > r) = (1 + r/df)^(-df/2) en d = 2
delta2 = np.einsum('ni,ij,nj->n', xs - loc, np.linalg.inv(shape), xs - loc)
print(f"fracción de x* en la región del 95 % de la t: {np.mean(delta2 <= r2):.3f}")
from scipy.special import gammaln
from scipy.linalg import solve_triangular
def mvt_logpdf_chol(x, loc, shape, df):
"""log t_df(x | loc, shape) desde cero, con Cholesky de la matriz de escala."""
L = np.linalg.cholesky(shape); dd = len(loc)
z = solve_triangular(L, (np.atleast_2d(x) - loc).T, lower=True)
return (gammaln((df + dd) / 2) - gammaln(df / 2) - 0.5 * dd * np.log(df * np.pi)
- np.log(np.diag(L)).sum() - 0.5 * (df + dd) * np.log1p((z ** 2).sum(0) / df))
print("log-densidad de la t: diferencia máxima con scipy.stats.multivariate_t en 1000 puntos =",
np.abs(mvt_logpdf_chol(xs[:1000], loc, shape, df) - stats.multivariate_t(loc, shape, df).logpdf(xs[:1000])).max())
# 3) calibración: n = 5 puntos de N(mu, Sigma), región del 95 % para un punto nuevo, 20000 repeticiones
Sigma = np.array([[1.0, 0.6], [0.6, 0.8]]); mu = np.array([0.3, -0.2])
Lt = np.linalg.cholesky(Sigma)
R = 20000
print(f"\n{'n':>4} {'cobertura t (kappa0=0, nu0=-1)':>32} {'cobertura gaussiana N(xbar, S/n)':>34}")
for n in (4, 5, 10, 40):
Xr = mu + rng.normal(size=(R, n, d)) @ Lt.T
xb = Xr.mean(1); Dm = Xr - xb[:, None, :]
S = np.einsum('rni,rnj->rij', Dm, Dm)
new = mu + rng.normal(size=(R, d)) @ Lt.T
e = new - xb
nu_t = n - d # = nu_n - d + 1 con nu_n = n - 1
delta2_t = np.einsum('ri,rij,rj->r', e, np.linalg.inv((n + 1) / (n * nu_t) * S), e)
delta2_g = np.einsum('ri,rij,rj->r', e, np.linalg.inv(S / n), e)
print(f"{n:4d} {np.mean(delta2_t <= nu_t * (0.05 ** (-2 / nu_t) - 1)):32.3f} {np.mean(delta2_g <= -2 * np.log(0.05)):34.3f}")Simulation of the complete generative model agrees with with 10 degrees (mean and covariance to the third digit, and 95.0 % of mass in the region), your log density agrees with SciPy to rounding, sequential and batch updates agree, and calibration matches the theory: the region covers 95 % for every up to Monte Carlo error, a few tenths of a percentage point, whereas the Gaussian with estimated parameters falls short: 55 % with , 65 % with , 82 % with and 92 % with . The Gaussian also uses maximum-likelihood estimator , biased downward, making the shortfall worse; even with it would ignore uncertainty about , which corrects. One last library reminder, because the source of error here is convention.
d, nu = 2, 7
W = np.array([[0.5, 0.1], [0.1, 0.3]])
Lam = stats.wishart(df=nu, scale=W).rvs(size=20000, random_state=0)
print("E[Λ] simulada:", np.round(Lam.mean(0), 3).tolist(), " ν W =", (nu * W).round(3).tolist())
print("E[Σ] = E[Λ^{-1}] simulada:", np.round(np.linalg.inv(Lam).mean(0), 3).tolist())
print("W^{-1}/(ν - d - 1) :", np.round(np.linalg.inv(W) / (nu - d - 1), 3).tolist())
print("invwishart(df, scale=W^{-1}).mean():", np.round(stats.invwishart(df=nu, scale=np.linalg.inv(W)).mean(), 3).tolist())
print("invwishart(df, scale=W).mean() (error típico):", np.round(stats.invwishart(df=nu, scale=W).mean(), 3).tolist())In scipy.stats.wishart(df, scale) the second argument is the scale matrix of precision and the mean is df * scale, as in Bishop; invwishart(df, scale) models covariance with scale and mean scale / (df - d - 1). Other books and libraries exchange for its inverse or precision for covariance. The reliable check is to inspect the mean.
Moment-matching projection
Conjugacy gives exact posteriors, but a model is rarely conjugate. A Gaussian prior multiplied by a likelihood such as that of a probit classifier, an observation with heavy-tailed noise or a sign constraint gives a tilted distribution
that is no longer Gaussian. The module’s lessons approximate such a distribution with a Gaussian in three different ways, which are worth distinguishing from the outset:
- Laplace (lesson 7) fits at the mode: the center of is the maximum of and its variance is the inverse curvature of there. It looks at at only one point.
- Variational inference (lesson 18) minimizes . It penalizes for putting mass where has none, so it tends to keep one mode.
- Moment matching, next, minimizes . It penalizes for failing to cover mass that has, so it covers all of it. ADF and EP use this choice.
To see the difference, look before defining. In the figure, a prior is multiplied by a non-Gaussian factor; both approximations use the same distribution and yield different Gaussians.
Now the definition and result, for any exponential family with , for which you already know from exponential families that and .
The guided exercise at the end gives the argument. The idea fits in one line: is a convex function of (because is convex), and its gradient, , vanishes exactly when moments match. The same identity says maximum likelihood is a special case with the empirical distribution, the likelihood equation of an exponential family seen in statistics and inference.
The Gaussian case. For , and the projection is the Gaussian with the mean and covariance of : , . Existence requires to have those moments: for a Cauchy, and for every Gaussian, so there is no best Gaussian approximation in this sense. The same happens for a discrete family with other statistics: the closest categorical distribution in reproduces the marginal probabilities, and so on.
How to calculate moments of . Without new integrals, the tilted moments follow by differentiating with respect to the prior parameters, because (here ). Differentiating twice under the integral,
(The first is immediate. For the second, , and subtract the square of the first derivative of .) It suffices to calculate .
Probit. With , is the probability that with independent and , namely with . With (the inverse Mills ratio, satisfying ),
Step. With this is the limit : the truncated Gaussian, with , and ,
Two consistency checks. With , and , the probit formulas become the step formulas. With the factor equals everywhere, and , and you recover the prior. There is no closed form for Student ; compute it by Gauss-Hermite quadrature or numerically, as the figure does.
Return to the figure and look for three things.
- With the step, Laplace misses what matters. If , the maximum of is at the boundary , where jumps from to a finite value (and if its right derivative does not even vanish): there is no neighborhood of the mode for a Taylor expansion and no Laplace approximation. If , the mode is the prior mode and Laplace returns the entire prior, still containing the mass removed by truncation: its is . The projection preserves mean and variance.
- With and a distant observation, is bimodal. With default settings (prior , observation , scale , ), has one mode at , between prior and observation, and another at , close to the observation, with nearly equal heights. Laplace keeps one, with variance corresponding to that peak’s curvature. Moment projection uses a broad Gaussian covering both: less visually pleasing, but minimizing the penalty for the part of left uncovered, as measured by .
- The minimum of is at the projection, not the mode. In manual fitting, move mean and scale: decreases only until reaching the moment-matched Gaussian (offset , factor ) and increases in either direction. has its minimum elsewhere, and with the step it is infinite for every Gaussian because always puts some mass in , where .
The elementary step of ADF and expectation propagation is exactly this: given a Gaussian approximation and non-Gaussian factor , replace with the moment projection of (for ADF, assumed-density filtering, in lesson 14) or with the cavity removed (for EP, lesson 20). The work is calculating and its first two derivatives, which you will write in the lab.
import numpy as np
from scipy import stats
from scipy.optimize import minimize, minimize_scalar
from numpy.polynomial.hermite_e import hermegauss
def probit_moments(mu0, v0, c, s):
"""Z, media y varianza de p ∝ N(x | mu0, v0) Phi((x - c)/s)."""
den = np.sqrt(s * s + v0); z = (mu0 - c) / den
Z = stats.norm.cdf(z); r = stats.norm.pdf(z) / Z
return Z, mu0 + v0 * r / den, v0 - v0 ** 2 / (s * s + v0) * r * (z + r)
def step_moments(mu0, v0, c):
"""Lo mismo para el factor 1[x > c] (gaussiana truncada)."""
sd = np.sqrt(v0); a = (c - mu0) / sd
Z = stats.norm.sf(a); lam = stats.norm.pdf(a) / Z
return Z, mu0 + sd * lam, v0 * (1 + a * lam - lam ** 2)
def gh_moments(f, mu0, v0, m):
"""Mismos momentos por cuadratura de Gauss-Hermite con m nodos."""
t, w = hermegauss(m); x = mu0 + np.sqrt(v0) * t; w = w / np.sqrt(2 * np.pi)
fx = f(x); Z = (w * fx).sum(); mean = (w * fx * x).sum() / Z
return Z, mean, (w * fx * x ** 2).sum() / Z - mean ** 2
mu0, v0, c, s = 0.0, 1.0, 1.0, 0.5
probit = lambda x: stats.norm.cdf((x - c) / s)
step = lambda x: (x > c).astype(float)
exact_p, exact_s = probit_moments(mu0, v0, c, s), step_moments(mu0, v0, c)
print("probit cerrada (Z, media, var):", np.round(exact_p, 5))
print("escalón cerrada (Z, media, var):", np.round(exact_s, 5))
rng = np.random.default_rng(0)
xs = rng.normal(mu0, np.sqrt(v0), size=400000) # Monte Carlo ponderado por el factor
for nombre, fun, ex in (("probit", probit, exact_p), ("escalón", step, exact_s)):
w = fun(xs); m = (w * xs).sum() / w.sum(); v = (w * xs ** 2).sum() / w.sum() - m ** 2
print(f"{nombre:8s} Monte Carlo: Z {w.mean():.4f} media {m:.4f} var {v:.4f}")
print("\nerror de la media con Gauss-Hermite según el número de nodos:")
print(f"{'nodos':>6} {'probit':>10} {'escalón':>10}")
for m in (5, 10, 20, 50, 200):
print(f"{m:6d} {abs(gh_moments(probit, mu0, v0, m)[1] - exact_p[1]):10.1e} {abs(gh_moments(step, mu0, v0, m)[1] - exact_s[1]):10.1e}")
# KL(p || q) en una rejilla: proyección de momentos frente a Laplace, y búsqueda numérica del mínimo
x = np.linspace(-10, 10, 40001); dx = x[1] - x[0]
logp_t = stats.norm.logpdf(x, mu0, np.sqrt(v0)) + stats.norm.logcdf((x - c) / s)
p = np.exp(logp_t - logp_t.max()); p /= p.sum() * dx
def kl_pq(m, v):
return float(np.sum(p * (np.log(p + 1e-300) - stats.norm.logpdf(x, m, np.sqrt(v)))) * dx)
g = lambda t: -(stats.norm.logpdf(t, mu0, np.sqrt(v0)) + stats.norm.logcdf((t - c) / s))
mode = minimize_scalar(g, bounds=(-5, 5), method="bounded", options={"xatol": 1e-10}).x
h = 1e-4; curv = (g(mode + h) - 2 * g(mode) + g(mode - h)) / h ** 2
print(f"\nprobit: KL(p||q) con momentos {kl_pq(exact_p[1], exact_p[2]):.5f}; con Laplace (modo {mode:.4f}, var {1 / curv:.4f}) {kl_pq(mode, 1 / curv):.5f}")
res = minimize(lambda th: kl_pq(th[0], np.exp(th[1])), [0.0, 0.0], method="Nelder-Mead", options={"xatol": 1e-8, "fatol": 1e-12})
print(f"mínimo numérico de KL(p||q): media {res.x[0]:.4f}, var {np.exp(res.x[1]):.4f} (momentos: {exact_p[1]:.4f}, {exact_p[2]:.4f})")
Zs = exact_s[0]
print(f"escalón con mu0 = 1 > c = 0: Laplace devuelve el prior, KL(p||q) = -log Z = {-np.log(step_moments(1.0, 1.0, 0.0)[0]):.4f}; "
f"momentos: media {step_moments(1.0, 1.0, 0.0)[1]:.4f}, var {step_moments(1.0, 1.0, 0.0)[2]:.4f}")Three observations follow. The closed forms agree with Monte Carlo within its error (, mean and variance to the third digit). Gauss-Hermite quadrature converges geometrically fast for the analytic probit factor (mean error with 5 nodes, with 50), and does not converge in practice for the discontinuous step: error stays between and even with 200 nodes, because the rule treats the jump as smooth. ADF and EP therefore use closed forms when available. Finally, numerical minimization of lands on the mean and variance of ( and ), as the theorem says, while Laplace, centered at mode with variance , pays three times the KL ( versus ).
Reuse map
| Tool from this lesson | Where it returns |
|---|---|
| Conditioning and marginalizing (Schur) | Kalman (lessons 12 and 13), Gaussian processes (16 and 20), Gibbs with Gaussian conditionals (22) |
| Information form | Gaussian Markov fields (3), Gaussian message passing (5), information filter |
| Linear Gaussian model | Bayesian regression (6), Kalman correction (12), Gaussian-process regression (16) |
| Cholesky, jitter | Everywhere: densities, sampling, Gaussian processes (16 and 20), square-root Kalman (12) |
| Normal-gamma and Normal-Wishart, predictive | Regression with unknown noise (6), conjugate Gibbs and CAVI (22 and 18), hierarchical models (24) |
| Moment matching | ADF in nonlinear filters (14), expectation propagation and Gaussian-process classification (20) |
In quantitative finance, fusion by precision reappears as Black-Litterman, combining a market prior with views, and the Normal-Wishart prior estimates asset covariances with shrinkage.
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. How do you write while separating what depends on ?
Step 1 of 3. Which integral do you set up?
mvn_logpdf_chol(x, mu, L) to return the log density of at x, where L is the lower-triangular Cholesky factor. x can be a vector (d,) (return a scalar) or matrix (m, d) (return an array (m,)). Do not use inverses, det, slogdet or general solve: solve the triangular system using scipy.linalg.solve_triangular and calculate the log determinant from the diagonal of L. Tests include dimension 200 (where does not fit in float64) and nearly singular covariances.import numpy as np
from scipy.linalg import solve_triangular
def mvn_logpdf_chol(x, mu, L):
"""Log-densidad de N(mu, L L^T) en x. L es triangular inferior con diagonal positiva."""
# tu código
return 0.0normal_wishart_update(m0, kappa0, nu0, W0, X) under Bishop's convention (, W0 is the precision scale matrix), returning tuple (mn, kn, nun, Wn) of posterior hyperparameters from data X of shape (n, d). Tests compare it with sequential updates, the Normal-gamma case and Monte Carlo posterior means (importance sampling).import numpy as np
def normal_wishart_update(m0, kappa0, nu0, W0, X):
"""Devuelve (mn, kn, nun, Wn). Wn es la matriz de escala (no su inversa)."""
X = np.atleast_2d(X)
# tu código
return m0, kappa0, nu0, W0probit_moments(mu0, v0, c, s) returning (Z, media, varianza) for with the lesson's closed-form formulas (without numerical quadrature). ADF and EP will use this function. It must accept mu0 and c over any reasonable range, including the tail where is very small (use scipy.special.log_ndtr or a stable Mills ratio for ).import numpy as np
from scipy import stats
def probit_moments(mu0, v0, c, s):
"""Devuelve (Z, media, varianza) de p ∝ N(x | mu0, v0) * Phi((x - c) / s)."""
# tu código
return 1.0, mu0, v0Summary
- Conditioning a Gaussian slices rather than projects: conditional mean is affine in the observation and conditional covariance (Schur) does not depend on it; conditioning never increases covariance.
- Information form: multiplying Gaussians adds precisions and information vectors; sensor fusion never worsens the result and averaging covariances is an error. The linear Gaussian model unifies Kalman, Bayesian regression and Gaussian processes.
- Cholesky instead of inverses: log density, sampling and log determinant follow from the factor. Problem conditioning limits single-system accuracy; Cholesky offers symmetry, positivity, diagnostics and cost advantages. Jitter changes the model.
- Normal-gamma and Normal-Wishart: update by adding sufficient statistics and scatters, with and ; the predictive distribution is with or degrees, a scale mixture whose heavy tails dissipate with data. Always check the Wishart convention using its mean.
- Moment-matching projection: in an exponential family, satisfies . For it is the Gaussian with the mean and covariance of ; moments of follow from and its derivatives. This is neither Laplace (the mode) nor variational inference (): it is the ADF and EP step.