Module contents
Lesson 1 of 27Review 90 min

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

Model, infer, decide

This module comes down to three verbs. Modeling means writing the joint distribution of what you observe, y\vb{y}, and what you cannot see but want to know, x\vb{x} or θ\theta: p(x,y)p(\vb{x}, \vb{y}). Inferring means conditioning: p(x∣y)=p(x,y)/p(y)p(\vb{x} \given \vb{y}) = p(\vb{x}, \vb{y})/p(\vb{y}). 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 tt predictive distribution.
  • Moment-matching projection. How to approximate a non-Gaussian distribution by a Gaussian and why the correct answer for KL⁡(p ∥ q)\KL(p \,\|\, q) 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 p(D∣θ)p(\Data \given \theta); a prior supplies π(θ)\pi(\theta); Bayes’ theorem gives the posterior π(θ∣D)=p(D∣θ) π(θ)/p(D)\pi(\theta \given \Data) = p(\Data \given \theta)\,\pi(\theta)/p(\Data), where p(D)=∫p(D∣θ)π(θ) ⁣dθp(\Data) = \int p(\Data \given \theta)\pi(\theta)\dd\theta is the evidence. To predict a new observation, rather than using an estimated parameter, average over all parameters considered plausible by the posterior,

p(x∗∣D)=∫p(x∗∣θ) π(θ∣D) ⁣dθ,p(x^* \given \Data) = \int p(x^* \given \theta)\,\pi(\theta \given \Data)\dd\theta,

which is the posterior predictive distribution. With the known-variance normal from the Bayesian inference lesson (prior N(10,4)\Normal(10, 4), noise σ2=9\sigma^2 = 9, nine observations with mean 1212), the posterior is N(11.6,0.8)\Normal(11.6, 0.8) and the predictive distribution is N(11.6, 0.8+9)=N(11.6,9.8)\Normal(11.6,\ 0.8 + 9) = \Normal(11.6, 9.8): predictive variance combines two sources, observation noise and remaining uncertainty about θ\theta. 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 ℓ(a,θ)\ell(a, \theta), the expected posterior loss of action aa is ρ(a∣D)=E[ℓ(a,θ)∣D]\rho(a \given \Data) = \E[\ell(a, \theta) \given \Data], and the Bayes action minimizes it (Bayes decision rule).

Proof

(1) ρ(a)=E[(a−θ)2]=Var⁡(θ)+(a−Eθ)2\rho(a) = \E[(a - \theta)^2] = \Var(\theta) + (a - \E\theta)^2, minimized at a=Eθa = \E\theta. (2) Differentiating under the expectation gives ρ′(a)=P(θ<a)−P(θ>a)\rho'(a) = \Pr(\theta < a) - \Pr(\theta > a), which changes sign at a median. (3) ρ(a)=1−π(a∣D)\rho(a) = 1 - \pi(a \given \Data), 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, x=(xa,xb)\vb{x} = (\vb{x}_a, \vb{x}_b), with mean (μa,μb)(\vb{\mu}_a, \vb{\mu}_b) and covariance Σ=[ΣaaΣabΣbaΣbb]\mat{\Sigma} = \begin{bmatrix} \mat{\Sigma}_{aa} & \mat{\Sigma}_{ab} \\ \mat{\Sigma}_{ba} & \mat{\Sigma}_{bb} \end{bmatrix}, with Σbb≻0\mat{\Sigma}_{bb} \succ 0.

Proof

Define the residual r=xa−μa−ΣabΣbb−1(xb−μb)\vb{r} = \vb{x}_a - \vb{\mu}_a - \mat{\Sigma}_{ab}\mat{\Sigma}_{bb}\inv(\vb{x}_b - \vb{\mu}_b). It is a linear function of x\vb{x}, so (r,xb)(\vb{r}, \vb{x}_b) is jointly Gaussian, and its cross-covariance is Σab−ΣabΣbb−1Σbb=0\mat{\Sigma}_{ab} - \mat{\Sigma}_{ab}\mat{\Sigma}_{bb}\inv\mat{\Sigma}_{bb} = \mat{0}. Jointly Gaussian and uncorrelated variables are independent, so conditioning on xb\vb{x}_b does not change the law of r\vb{r}: it remains N(0,Var⁡r)\Normal(\vb{0}, \Var\vb{r}) with Var⁡r=Σaa−ΣabΣbb−1Σba\Var\vb{r} = \mat{\Sigma}_{aa} - \mat{\Sigma}_{ab}\mat{\Sigma}_{bb}\inv\mat{\Sigma}_{ba} (expand Var⁡(xa−Gxb)\Var(\vb{x}_a - \mat{G}\vb{x}_b) using G=ΣabΣbb−1\mat{G} = \mat{\Sigma}_{ab}\mat{\Sigma}_{bb}\inv). Since xa=μa+G(xb−μb)+r\vb{x}_a = \vb{\mu}_a + \mat{G}(\vb{x}_b - \vb{\mu}_b) + \vb{r}, given xb\vb{x}_b the only random part is r\vb{r}, yielding the stated mean and covariance.

∎

The figure reveals a geometric interpretation of the proof. The conditional mean is the orthogonal projection of xa\vb{x}_a onto what you know (Gxb\mat{G}\vb{x}_b, the best linear predictor), and r\vb{r} is what remains unexplained. The conditional distribution is a renormalized slice of the joint density, rather than its projection onto an axis.

InteractiveSlice a 2D Gaussian
  • 1- and 2-standard-deviation ellipses of p(x)p(\vb{x})
  • normalized slice p(x1∣x2=a)p(x_1 \mid x_2 = a) and its mean
  • line μ1∣2(x2)\mu_{1\mid 2}(x_2) with band ±2Σ1∣2\pm 2\sqrt{\Sigma_{1\mid 2}}
Densities of x1x_1: marginal (projection) and conditional (slice)
1.00
Conditional mean μ1∣2\mu_{1\mid 2}1.14
Conditional variance Σ1∣2\Sigma_{1\mid 2}0.841
Marginal variance Σ11\Sigma_{11}1.647
Correlation ρ\rho0.70
Slope Σ12/Σ22\Sigma_{12}/\Sigma_{22}0.92
Standard deviation ratio Σ1∣2/Σ11\sqrt{\Sigma_{1\mid 2}/\Sigma_{11}}0.715
1−ρ2\sqrt{1-\rho^2}0.715
Move aa: the conditional mean follows the orange line, but the slice width stays constant. It changes only when the ellipse is deformed.
Drag the two blue points to deform the covariance ellipse (the larger rotates and stretches the principal axis, the smaller stretches the other) and move the line x2=ax_2 = a with the gray point or slider. Below are the marginal of x1x_1 (blue, the density projection) and the conditional (magenta, the normalized slice). Observe three things: how does the conditional mean move when aa changes, does the slice width change, and what determines that width?

The figure shows the theorem in two dimensions. With ρ=Σ12/Σ11Σ22\rho = \Sigma_{12}/\sqrt{\Sigma_{11}\Sigma_{22}},

μ1∣2(a)=μ1+Σ12Σ22(a−μ2),Σ1∣2=Σ11−Σ122Σ22=Σ11(1−ρ2).\mu_{1\mid 2}(a) = \mu_1 + \frac{\Sigma_{12}}{\Sigma_{22}}(a - \mu_2), \qquad \Sigma_{1\mid 2} = \Sigma_{11} - \frac{\Sigma_{12}^2}{\Sigma_{22}} = \Sigma_{11}(1 - \rho^2).
  1. The conditional mean is affine in aa. It follows the orange line, the regression of x1x_1 on x2x_2, with slope Σ12/Σ22\Sigma_{12}/\Sigma_{22}. With zero correlation the line is vertical: observing x2x_2 moves nothing.
  2. Conditional variance does not depend on aa. The orange band has constant width. In the proof, the residual r\vb{r} is independent of xb\vb{x}_b. This is a property of the Gaussian, not of conditioning generally. For the uniform distribution on a disk, the slice x2=ax_2 = a is a segment of length 21−a22\sqrt{1 - a^2}, and the variance of x1x_1 given x2=ax_2 = a equals (1−a2)/3(1 - a^2)/3, which does depend on aa (for a unit radius here).
  3. Width depends only on the shape of the ellipse. With a circular ellipse (ρ=0\rho = 0), the slice has the same variance as the marginal. The narrower the ellipse (the higher the correlation), the narrower the slice, with the ratio 1−ρ2\sqrt{1 - \rho^2} shown in the figure. In the limit of a degenerate ellipse, the observation almost completely fixes x1x_1.

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 Λ=Σ−1\mat{\Lambda} = \mat{\Sigma}\inv is the precision and η=Λμ\vb{\eta} = \mat{\Lambda}\vb{\mu} the information vector, then

N(x∣μ,Σ) ∝ exp⁡ ⁣(η⊤x−12x⊤Λx).\Normal(\vb{x} \given \vb{\mu}, \mat{\Sigma}) \ \propto\ \exp\!\Big(\vb{\eta}\T\vb{x} - \tfrac12 \vb{x}\T\mat{\Lambda}\vb{x}\Big).

This is the natural form of the exponential family (with sufficient statistic (x,xx⊤)(\vb{x}, \vb{x}\vb{x}\T)), 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 x\vb{x}; the sum is a quadratic with precision and linear terms added.

Sensor fusion. Two sensors measure the same position: zi∣x∼N(x,Ri)\vb{z}_i \given \vb{x} \sim \Normal(\vb{x}, \mat{R}_i). With a flat prior over x\vb{x}, the posterior is the product of the two likelihoods viewed as functions of x\vb{x} (N(zi∣x,Ri)\Normal(\vb{z}_i \given \vb{x}, \mat{R}_i) is symmetric in zi\vb{z}_i and x\vb{x}), so

Λ=RA−1+RB−1,μ=Λ−1(RA−1zA+RB−1zB).\mat{\Lambda} = \mat{R}_A\inv + \mat{R}_B\inv, \qquad \vb{\mu} = \mat{\Lambda}\inv\big(\mat{R}_A\inv\vb{z}_A + \mat{R}_B\inv\vb{z}_B\big).

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 1/σ21/\sigma^2.

InteractiveFuse two sensors
  • sensor A: RA\mat{R}_A
  • sensor B: RB\mat{R}_B
  • posterior: Λ=ΛA+ΛB\mat{\Lambda}=\mat{\Lambda}_A+\mat{\Lambda}_B
  • direction φ\varphi
0°
Posterior mean(0.50, 0.51)
Posterior standard deviations (axes)0.34 and 0.34
Sensor A standard deviations (axes)1.70 and 0.35
Sensor B standard deviations (axes)1.70 and 0.35
Precision of A in φ\varphi: u⊤ΛAu\vb{u}\T\mat{\Lambda}_A\vb{u}0.35
Precision of B in φ\varphi: u⊤ΛBu\vb{u}\T\mat{\Lambda}_B\vb{u}8.16
Posterior precision in φ\varphi8.51
In direction φ\varphi, 0.35 + 8.16 = 8.51: precisions add. Variances do not: in that direction, u⊤Σu=0.118\vb{u}\T\mat{\Sigma}\vb{u} = 0.118, compared with 2.890 (A) and 0.122 (B); never larger than the smaller of the two.
Sensor A (blue) is precise vertically and B (orange) horizontally. Drag their centers (large points) and axis points to rotate and stretch them. The magenta ellipse is the posterior. Move direction φ\varphi: posterior precision in that direction is always the sum of the two. Enable comparison with the average covariance to see why it is not a fusion.

Notice three things in the figure.

  1. The posterior inherits what each sensor does well. Initially, A fixes most of coordinate x2x_2 and B fixes x1x_1, and the posterior is a small, nearly circular ellipse, much smaller than either one. Neither sensor alone could locate the point; together they can.
  2. Precisions add, covariances do not. In any unit direction u\vb{u}, u⊤Λu=u⊤ΛAu+u⊤ΛBu\vb{u}\T\mat{\Lambda}\vb{u} = \vb{u}\T\mat{\Lambda}_A\vb{u} + \vb{u}\T\mat{\Lambda}_B\vb{u} (shown live in the panel). Averaging covariances, (RA+RB)/2(\mat{R}_A + \mat{R}_B)/2, is a common error: it gives an ellipse that improves on neither sensor because it ignores accumulating information.
  3. It never gets worse. If Λ⪰ΛA≻0\mat{\Lambda} \succeq \mat{\Lambda}_A \succ 0 then Λ−1⪯ΛA−1\mat{\Lambda}\inv \preceq \mat{\Lambda}_A\inv in the Loewner order. Proof: M=ΛA−1/2Λ ΛA−1/2⪰I\mat{M} = \mat{\Lambda}_A^{-1/2}\mat{\Lambda}\,\mat{\Lambda}_A^{-1/2} \succeq \mat{I} has all eigenvalues ≥1\ge 1, so M−1⪯I\mat{M}\inv \preceq \mat{I}, and reversing the change gives Λ−1⪯ΛA−1\mat{\Lambda}\inv \preceq \mat{\Lambda}_A\inv. More observations never increase Gaussian uncertainty in any direction.

Information form has another advantage used in lessons 3 and 4: zeros of Λ\mat{\Lambda} represent conditional independences, because the precision of the conditional of xa\vb{x}_a given the rest is the block Λaa\mat{\Lambda}_{aa}, and the conditional mean depends on xb\vb{x}_b only through nonzero blocks of Λab\mat{\Lambda}_{ab}. 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 x∼N(m,P)\vb{x} \sim \Normal(\vb{m}, \mat{P}) and, given x\vb{x}, the observation is an affine function with Gaussian noise, y∣x∼N(Hx+b,R)\vb{y} \given \vb{x} \sim \Normal(\mat{H}\vb{x} + \vb{b}, \mat{R}), you have the linear Gaussian model.

Proof

The joint distribution of (x,y)(\vb{x}, \vb{y}) is Gaussian (everything is affine in Gaussian noise), and y=Hx+b+ε\vb{y} = \mat{H}\vb{x} + \vb{b} + \vb{\varepsilon} gives mean Hm+b\mat{H}\vb{m} + \vb{b}, covariance S\mat{S} and cross-covariance Cov⁡(x,y)=PH⊤\Cov(\vb{x}, \vb{y}) = \mat{P}\mat{H}\T. Gain form follows from the conditioning theorem with Σab=PH⊤\mat{\Sigma}_{ab} = \mat{P}\mat{H}\T and Σbb=S\mat{\Sigma}_{bb} = \mat{S}. Information form comes from multiplying prior and likelihood: x\vb{x} appears in the exponent as −12(x−m)⊤P−1(x−m)−12(y−Hx−b)⊤R−1(y−Hx−b)-\tfrac12(\vb{x} - \vb{m})\T\mat{P}\inv(\vb{x} - \vb{m}) - \tfrac12(\vb{y} - \mat{H}\vb{x} - \vb{b})\T\mat{R}\inv(\vb{y} - \mat{H}\vb{x} - \vb{b}), a quadratic whose term quadratic in x\vb{x} is P−1+H⊤R−1H\mat{P}\inv + \mat{H}\T\mat{R}\inv\mat{H} and whose linear term is P−1m+H⊤R−1(y−b)\mat{P}\inv\vb{m} + \mat{H}\T\mat{R}\inv(\vb{y} - \vb{b}). The two forms coincide by the Woodbury identity.

∎

Two consequences are reusable. First, P′\mat{P}' does not depend on y\vb{y}, only on P\mat{P}, H\mat{H} and R\mat{R}, 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, dim⁡y\dim\vb{y}; information form uses one sized by the unknown, dim⁡x\dim\vb{x}. 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 seex\vb{x}y\vb{y}H\mat{H}
Sensor fusion (above)positionthe two stacked measurementstwo I\mat{I} blocks
Bayesian linear regression (lesson 6)weights w\vb{w}targetsdesign matrix Φ\mat{\Phi}
Kalman filter correction step (lesson 12)state, using prediction as priormeasurementobservation matrix
Regression with Gaussian processes (lesson 16)function values at training and test pointsnoisy observed valuesa selection of coordinates

Stable computation: Cholesky instead of inverses

The formulas above write Σ−1\mat{\Sigma}\inv and det⁡Σ\det\mat{\Sigma} for clarity; serious code does not calculate them that way. With Cholesky factorization Σ=LL⊤\mat{\Sigma} = \mat{L}\mat{L}\T (L\mat{L} lower triangular with positive diagonal), everything reduces to triangular systems:

log⁡N(x∣μ,Σ)=−12(dlog⁡2π+2∑ilog⁡Lii+∥L−1(x−μ)∥22),x=μ+Lz,  z∼N(0,I).\log\Normal(\vb{x} \given \vb{\mu}, \mat{\Sigma}) = -\tfrac12\Big(d\log 2\pi + 2\sum_{i}\log L_{ii} + \norm{\mat{L}\inv(\vb{x} - \vb{\mu})}_2^2\Big), \qquad \vb{x} = \vb{\mu} + \mat{L}\vb{z},\ \ \vb{z} \sim \Normal(\vb{0}, \mat{I}).

The log determinant is 2∑ilog⁡Lii2\sum_i \log L_{ii} (because det⁡Σ=(∏iLii)2\det\mat{\Sigma} = (\prod_i L_{ii})^2), the quadratic form is the norm of the solution of Lu=x−μ\mat{L}\vb{u} = \vb{x} - \vb{\mu} by forward substitution, and sampling is a triangular multiplication. Factorize once in roughly n3/3n^3/3 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 log⁡p(y)\log p(\vb{y})).

[ ]Gaussian kit from scratchBrowser
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.

[ ]Cholesky versus the explicit inverseBrowser
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 f∼N(0,K)\vb{f} \sim \Normal(\vb{0}, \mat{K}) on its own values: conditional covariance K−KK−1K\mat{K} - \mat{K}\mat{K}\inv\mat{K} is exactly 0\mat{0}, so any nonzero value is rounding error. With the explicit inverse it becomes negative and grows with conditioning (−1.4⋅10−9-1.4 \cdot 10^{-9}, −2.5⋅10−7-2.5 \cdot 10^{-7} and −1.7⋅10−5-1.7 \cdot 10^{-5} for κ≈108\kappa \approx 10^{8}, 101010^{10} and 101210^{12}), whereas Cholesky stays at −10−15-10^{-15}, machine epsilon, regardless of κ\kappa. 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, A−1b\mat{A}\inv\vb{b} is as accurate as the solution from the best backward-stable methods. Both lose on the order of log⁡10κ\log_{10}\kappa digits, because that loss belongs to the problem (its condition number κ\kappa), not the method. What inversion does not provide is:

  • Symmetry and positivity. The computed K−1\mat{K}\inv 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. log⁡det⁡\log\det comes for free from the diagonal; log⁡(det⁡Σ)\log(\det\mat{\Sigma}) overflows at moderate dimensions, as output with d=200d = 200 shows.
  • Cost. Forming the inverse takes roughly 2n32n^3 operations versus n3/3n^3/3 for Cholesky, and the printed timing ratio confirms it is several times slower (the exact figure varies between runs).

Jitter, adding τI\tau\mat{I} to the diagonal, shifts every eigenvalue τ\tau upward, so κ(K+τI)≤(λmax⁡+τ)/τ\kappa(\mat{K} + \tau\mat{I}) \le (\lambda_{\max} + \tau)/\tau: that permits factorization. This changes the model (equivalent to observation noise of variance τ\tau) 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 w\vb{w} and noise precision λ=1/σ2\lambda = 1/\sigma^2, 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 y∈Rn\vb{y} \in \R^n with design matrix Φ∈Rn×p\mat{\Phi} \in \R^{n \times p} is N(y∣Φw,λ−1I)\Normal(\vb{y} \given \mat{\Phi}\vb{w}, \lambda\inv\mat{I}). As a function of λ\lambda it is λn/2e−λ(⋯ )\lambda^{n/2}e^{-\lambda(\cdots)} (a gamma kernel), and as a function of w\vb{w} for fixed λ\lambda it is Gaussian with precision λΦ⊤Φ\lambda\mat{\Phi}\T\mat{\Phi}. This suggests a prior in which precision of w\vb{w} scales with λ\lambda:

Interpret it as pseudo-observations: 2a02a_0 noise observations with mean variance σ02=b0/a0\sigma_0^2 = b_0/a_0, and confidence Λ0\mat{\Lambda}_0 in m0\vb{m}_0 measured in units of Φ⊤Φ\mat{\Phi}\T\mat{\Phi}.

Proof

Multiply likelihood and prior. The powers of λ\lambda are λn/2\lambda^{n/2} (data), λp/2\lambda^{p/2} (the prior on w\vb{w}) and λa0−1\lambda^{a_0 - 1} (that on λ\lambda). The exponent is −λ2[∥y−Φw∥2+(w−m0)⊤Λ0(w−m0)+2b0]-\tfrac\lambda2\big[\norm{\vb{y} - \mat{\Phi}\vb{w}}^2 + (\vb{w} - \vb{m}_0)\T\mat{\Lambda}_0(\vb{w} - \vb{m}_0) + 2b_0\big]. Expand and group by powers of w\vb{w}:

w⊤Λnw−2w⊤(Φ⊤y+Λ0m0)+y⊤y+m0⊤Λ0m0+2b0.\vb{w}\T\mat{\Lambda}_n\vb{w} - 2\vb{w}\T(\mat{\Phi}\T\vb{y} + \mat{\Lambda}_0\vb{m}_0) + \vb{y}\T\vb{y} + \vb{m}_0\T\mat{\Lambda}_0\vb{m}_0 + 2b_0.

Completing the square yields =(w−mn)⊤Λn(w−mn)+2bn= (\vb{w} - \vb{m}_n)\T\mat{\Lambda}_n(\vb{w} - \vb{m}_n) + 2b_n with mn,bn\vb{m}_n, b_n as stated. What remains is λa0+n/2−1 e−bnλ⋅λp/2e−λ2(w−mn)⊤Λn(w−mn)\lambda^{a_0 + n/2 - 1}\,e^{-b_n\lambda}\cdot\lambda^{p/2}e^{-\frac\lambda2(\vb{w} - \vb{m}_n)\T\mat{\Lambda}_n(\vb{w} - \vb{m}_n)}: a gamma (an,bn)(a_n, b_n) in λ\lambda times a Gaussian of precision λΛn\lambda\mat{\Lambda}_n in w\vb{w}.

∎

Look at bnb_n: term m0⊤Λ0m0−mn⊤Λnmn\vb{m}_0\T\mat{\Lambda}_0\vb{m}_0 - \vb{m}_n\T\mat{\Lambda}_n\vb{m}_n grows when the prior on w\vb{w} and the data disagree. Thus, the model learns that noise is larger when the prior does not fit the data; for a sample mean (p=1p = 1, Φ=1\mat{\Phi} = \vb{1}, Λ0=κ0\mat{\Lambda}_0 = \kappa_0) this is bn=b0+12S+κ0n2κn(yˉ−m0)2b_n = b_0 + \tfrac12 S + \tfrac{\kappa_0 n}{2\kappa_n}(\bar y - m_0)^2, with S=∑i(yi−yˉ)2S = \sum_i(y_i - \bar y)^2. Since Λn\mat{\Lambda}_n, Λnmn\mat{\Lambda}_n\vb{m}_n and ana_n 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 w\vb{w} and the predictive distribution are no longer Gaussian. This is a consequence of integrating uncertainty over λ\lambda.

Proof

With Δ2=(x−μ)⊤Λ(x−μ)\Delta^2 = (\vb{x} - \vb{\mu})\T\mat{\Lambda}(\vb{x} - \vb{\mu}), p(x)=∫N(x∣μ,(λΛ)−1) Gamma(λ∣a,b) ⁣dλ∝∫λd/2+a−1exp⁡ ⁣(−λ(b+12Δ2)) ⁣dλ∝(b+12Δ2)−(a+d/2)∝(1+Δ2/2b)−(2a+d)/2p(\vb{x}) = \int \Normal(\vb{x} \given \vb{\mu}, (\lambda\mat{\Lambda})\inv)\,\mathrm{Gamma}(\lambda \given a, b)\dd\lambda \propto \int \lambda^{d/2 + a - 1}\exp\!\big(-\lambda(b + \tfrac12\Delta^2)\big)\dd\lambda \propto (b + \tfrac12\Delta^2)^{-(a + d/2)} \propto (1 + \Delta^2/2b)^{-(2a + d)/2} by the gamma integral. Since δ2=(a/b)Δ2\delta^2 = (a/b)\Delta^2, Δ2/(2b)=δ2/(2a)\Delta^2/(2b) = \delta^2/(2a), the density of the tt with ν=2a\nu = 2a.

∎

The mixture explains the tails. A tt is a continuous mixture of Gaussians at different scales, and large-variance components dominate far from the center: density decays as ∣x∣−(ν+d)\abs{\vb{x}}^{-(\nu + d)} (a power) rather than e−x2/2e^{-x^2/2}. With ν=1\nu = 1 it is Cauchy, with no mean; with ν≤2\nu \le 2 there is no variance. When the gamma concentrates, meaning a→∞a \to \infty with b/ab/a fixed, the mixing distribution collapses to a point and tt approaches a Gaussian.

Apply this to regression. Integrating w\vb{w} and then λ\lambda (first y∗∣λ∼N(ϕ∗Tmn, λ−1(1+ϕ∗TΛn−1ϕ∗))y^* \given \lambda \sim \Normal(\vb{\phi}^{*\mathrm T}\vb{m}_n,\ \lambda\inv(1 + \vb{\phi}^{*\mathrm T}\mat{\Lambda}_n\inv\vb{\phi}^*)) and then the theorem), the predictive distribution at a point with features ϕ∗\vb{\phi}^* is

y∗∣y∼t2an ⁣(ϕ∗Tmn,  bnan(1+ϕ∗TΛn−1ϕ∗)),y^* \given \vb{y} \sim t_{2a_n}\!\Big(\vb{\phi}^{*\mathrm T}\vb{m}_n,\ \ \tfrac{b_n}{a_n}\big(1 + \vb{\phi}^{*\mathrm T}\mat{\Lambda}_n\inv\vb{\phi}^*\big)\Big),

and the weight marginal is w∣y∼t2an(mn,bnanΛn−1)\vb{w} \given \vb{y} \sim t_{2a_n}(\vb{m}_n, \tfrac{b_n}{a_n}\mat{\Lambda}_n\inv). The degrees of freedom are 2an=2a0+n2a_n = 2a_0 + n: 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 (tt with 4 degrees) rather than 1.96, as in elementary statistics. In the improper limit Λ0→0\mat{\Lambda}_0 \to \mat{0}, a0=−p/2a_0 = -p/2, b0=0b_0 = 0 (the joint prior density is proportional to λ−1\lambda\inv, flat in w\vb{w}), the posterior is proper if n>pn > p and has 2an=n−p2a_n = n - p degrees: it is the tt of the classical least-squares prediction interval. We verify this and measure coverage.

[ ]Normal-gamma: update, t predictive distribution and coverageBrowser
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 0.25820.2582 in both cases), and tt 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 n=3n = 3 (one degree of freedom, a Cauchy), 85 % with n=5n = 5, 91.5 % with n=10n = 10 and 94.1 % with n=40n = 40, while the tt 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 λ\lambda becomes a matrix Λ≻0\mat{\Lambda} \succ 0 and the Wishart takes the gamma’s role. We use Bishop’s convention (2006, §2.3.6), in which W\mat{W} is the scale matrix and the mean is νW\nu\mat{W}.

A x1,…,xn∼iidN(μ,Λ−1)\vb{x}_1, \dots, \vb{x}_n \iid \Normal(\vb{\mu}, \mat{\Lambda}\inv) model with unknown mean and precision has the following likelihood in terms of sufficient statistics nn, xˉ\bar{\vb{x}} and S=∑i(xi−xˉ)(xi−xˉ)⊤\mat{S} = \sum_i(\vb{x}_i - \bar{\vb{x}})(\vb{x}_i - \bar{\vb{x}})\T. The Normal-Wishart prior Λ∼W(W0,ν0)\mat{\Lambda} \sim \mathcal{W}(\mat{W}_0, \nu_0), μ∣Λ∼N(m0,(κ0Λ)−1)\vb{\mu} \given \mat{\Lambda} \sim \Normal(\vb{m}_0, (\kappa_0\mat{\Lambda})\inv) is conjugate.

Proof

Use ∑i(xi−μ)(xi−μ)⊤=S+n(xˉ−μ)(xˉ−μ)⊤\sum_i(\vb{x}_i - \vb{\mu})(\vb{x}_i - \vb{\mu})\T = \mat{S} + n(\bar{\vb{x}} - \vb{\mu})(\bar{\vb{x}} - \vb{\mu})\T in the likelihood, ∏iN(xi∣μ,Λ−1)∝∣Λ∣n/2exp⁡ ⁣(−12tr⁡[Λ(S+n(xˉ−μ)(xˉ−μ)⊤)])\prod_i\Normal(\vb{x}_i \given \vb{\mu}, \mat{\Lambda}\inv) \propto \abs{\mat{\Lambda}}^{n/2}\exp\!\big(-\tfrac12\tr[\mat{\Lambda}(\mat{S} + n(\bar{\vb{x}} - \vb{\mu})(\bar{\vb{x}} - \vb{\mu})\T)]\big). The prior contributes ∣Λ∣(ν0−d−1)/2e−12tr⁡(W0−1Λ)⋅∣Λ∣1/2e−κ02(μ−m0)⊤Λ(μ−m0)\abs{\mat{\Lambda}}^{(\nu_0 - d - 1)/2}e^{-\frac12\tr(\mat{W}_0\inv\mat{\Lambda})}\cdot\abs{\mat{\Lambda}}^{1/2}e^{-\frac{\kappa_0}2(\vb{\mu} - \vb{m}_0)\T\mat{\Lambda}(\vb{\mu} - \vb{m}_0)}. The two quadratics in μ\vb{\mu} add as in the scalar case:

κ0(μ−m0)(μ−m0)⊤+n(μ−xˉ)(μ−xˉ)⊤  «=»  κn(μ−mn)(μ−mn)⊤+κ0nκn(xˉ−m0)(xˉ−m0)⊤,\kappa_0(\vb{\mu} - \vb{m}_0)(\vb{\mu} - \vb{m}_0)\T + n(\vb{\mu} - \bar{\vb{x}})(\vb{\mu} - \bar{\vb{x}})\T \ \ \text{«=»}\ \ \kappa_n(\vb{\mu} - \vb{m}_n)(\vb{\mu} - \vb{m}_n)\T + \tfrac{\kappa_0 n}{\kappa_n}(\bar{\vb{x}} - \vb{m}_0)(\bar{\vb{x}} - \vb{m}_0)\T,

where “=” means equality after taking the trace against Λ\mat{\Lambda} (check by matching coefficients of μμ⊤\vb{\mu}\vb{\mu}\T, μ\vb{\mu} and the constant term). The exponent becomes −12tr⁡[ΛWn−1]−κn2(μ−mn)⊤Λ(μ−mn)-\tfrac12\tr[\mat{\Lambda}\mat{W}_n\inv] - \tfrac{\kappa_n}{2}(\vb{\mu} - \vb{m}_n)\T\mat{\Lambda}(\vb{\mu} - \vb{m}_n) and the powers of ∣Λ∣\abs{\mat{\Lambda}} sum to (ν0+n−d−1)/2(\nu_0 + n - d - 1)/2 for the Wishart plus 1/21/2 for the normal in μ\vb{\mu}.

∎

Read this as pseudo-observations. The prior corresponds to ν0\nu_0 vectors with scatter W0−1\mat{W}_0\inv (so a reasonable guide is W0−1=ν0Σ0\mat{W}_0\inv = \nu_0\mat{\Sigma}_0 with Σ0\mat{\Sigma}_0 your best estimate of covariance) and κ0\kappa_0 observations of the mean at m0\vb{m}_0. The posterior adds both scatters and adds a term for disagreement between prior and data means, analogous to the term in bnb_n.

The predictive distribution follows from the same scale-mixture trick, with a short proof.

Proof

First integrate μ\vb{\mu}: x∗=μ+ε\vb{x}^* = \vb{\mu} + \vb{\varepsilon} with μ∣Λ∼N(mn,(κnΛ)−1)\vb{\mu} \given \mat{\Lambda} \sim \Normal(\vb{m}_n, (\kappa_n\mat{\Lambda})\inv) and ε∼N(0,Λ−1)\vb{\varepsilon} \sim \Normal(\vb{0}, \mat{\Lambda}\inv), so x∗∣Λ∼N(mn,(cΛ)−1)\vb{x}^* \given \mat{\Lambda} \sim \Normal(\vb{m}_n, (c\mat{\Lambda})\inv) with c=κn/(κn+1)c = \kappa_n/(\kappa_n + 1). With δ=x∗−mn\vb{\delta} = \vb{x}^* - \vb{m}_n, now mix over Λ∼W(Wn,νn)\mat{\Lambda} \sim \mathcal{W}(\mat{W}_n, \nu_n):

p(x∗)∝∫∣Λ∣νn+1−d−12exp⁡ ⁣(−12tr⁡[(Wn−1+c δδ⊤)Λ]) ⁣dΛ∝∣Wn−1+c δδ⊤∣−(νn+1)/2,p(\vb{x}^*) \propto \int \abs{\mat{\Lambda}}^{\frac{\nu_n + 1 - d - 1}{2}}\exp\!\Big(-\tfrac12\tr\big[(\mat{W}_n\inv + c\,\vb{\delta}\vb{\delta}\T)\mat{\Lambda}\big]\Big)\dd\mat{\Lambda} \propto \big|\mat{W}_n\inv + c\,\vb{\delta}\vb{\delta}\T\big|^{-(\nu_n + 1)/2},

because the integral is the normalization constant of a Wishart with νn+1\nu_n + 1 degrees. By the matrix determinant lemma, ∣Wn−1+c δδ⊤∣=∣Wn−1∣ (1+c δ⊤Wnδ)|\mat{W}_n\inv + c\,\vb{\delta}\vb{\delta}\T| = |\mat{W}_n\inv|\,(1 + c\,\vb{\delta}\T\mat{W}_n\vb{\delta}). Compare with the multivariate tt, (1+δ⊤Σt−1δ/ν′)−(ν′+d)/2(1 + \vb{\delta}\T\mat{\Sigma}_t\inv\vb{\delta}/\nu')^{-(\nu' + d)/2}: ν′+d=νn+1\nu' + d = \nu_n + 1 gives ν′=νn−d+1\nu' = \nu_n - d + 1, and Σt−1/ν′=c Wn\mat{\Sigma}_t\inv/\nu' = c\,\mat{W}_n gives the stated scale matrix.

∎

For d=1d = 1, νn=2an\nu_n = 2a_n and the degrees of freedom are 2an2a_n, as in the previous section.

InteractiveEllipses learned from data
  • data
  • 1σ ellipses of posterior-sampled covariances
  • 95 % t predictive region (thick line)
  • 95 % Gaussian region with xˉ\bar{\vb{x}} and S/n\mat{S}/n
  • true covariance Σ∗\mat{\Sigma}^* (1σ)
3
1.0
1.00
0.00
Data nn4
νn=ν0+n\nu_n = \nu_0 + n7
t degrees of freedom: νn−d+1\nu_n - d + 16
Actual 95 % coverage (t)98.2 %
Actual 95 % coverage (estimated Gaussian)54.2 %
Region area: t / Gaussian6.50
Σ∗\mat{\Sigma}^* true1 · 0.6 · 0.8
E[Σ]\E[\mat{\Sigma}] posterior0.98 · 0.08 · 0.98
Matrices are read as Σ11⋅Σ12⋅Σ22\Sigma_{11} \cdot \Sigma_{12} \cdot \Sigma_{22}. Coverage uses 3000 new points from the true distribution and this one dataset, so it varies across datasets. The calibration cell calculates the average over many datasets.
Each magenta ellipse is a covariance drawn from the Normal-Wishart posterior, centered at a sampled mean. With few observations the cloud is dispersed and its center depends on the prior; increase ν0\nu_0 for a stronger prior and add points using the buttons or by clicking the plane to see the cloud concentrate around the empirical covariance. The thick magenta ellipse is the 95 % region of the predictive tt; the dashed red ellipse is the Gaussian region with xˉ\bar{\vb{x}} and S/n\mat{S}/n. Compare their size and coverage with little data.

Initially, with four points and a weak prior, ν0=3\nu_0 = 3, κ0=1\kappa_0 = 1, Σ0=I\mat{\Sigma}_0 = \mat{I}, the 95 % tt 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, tt 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 %. tt shrinks toward the Gaussian as degrees of freedom rise and estimated covariance stabilizes; the posterior mean of Σ\mat{\Sigma}, still almost the prior with four points ([0.98 0.08; 0.08 0.98][0.98\ 0.08;\ 0.08\ 0.98]), has learned the correlation by 30 points ([1.08 0.62; 0.62 0.83][1.08\ 0.62;\ 0.62\ 0.83] versus true [1 0.6; 0.6 0.8][1\ 0.6;\ 0.6\ 0.8]). These coverages are from one dataset: the 95 % guarantee averages over datasets, as measured by the cell below. The prior matters: with large ν0\nu_0 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 κ0=0\kappa_0 = 0, ν0=−1\nu_0 = -1 and W0−1=0\mat{W}_0\inv = \mat{0} (proper for n>dn > d): the predictive distribution is tt with n−dn - d degrees and scale n+1n(n−d)S\frac{n + 1}{n(n - d)}\mat{S}, exactly Hotelling’s prediction region.

[ ]Normal-Wishart: update, t predictive distribution and calibrationBrowser
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 tt 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 tt region covers 95 % for every nn up to Monte Carlo error, a few tenths of a percentage point, whereas the Gaussian with estimated parameters falls short: 55 % with n=4n = 4, 65 % with n=5n = 5, 82 % with n=10n = 10 and 92 % with n=40n = 40. The Gaussian also uses maximum-likelihood estimator S/n\mat{S}/n, biased downward, making the shortfall worse; even with S/(n−1)\mat{S}/(n - 1) it would ignore uncertainty about Σ\mat{\Sigma}, which tt corrects. One last library reminder, because the source of error here is convention.

[ ]Wishart conventions in SciPyBrowser
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 W−1\mat{W}\inv and mean scale / (df - d - 1). Other books and libraries exchange W\mat{W} 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

p(x)=1Z N(x∣μ0,σ02) f(x),Z=∫N(x∣μ0,σ02) f(x) ⁣dx,p(x) = \frac{1}{Z}\,\Normal(x \given \mu_0, \sigma_0^2)\,f(x), \qquad Z = \int\Normal(x \given \mu_0, \sigma_0^2)\,f(x)\dd x,

that is no longer Gaussian. The module’s lessons approximate such a distribution with a Gaussian qq in three different ways, which are worth distinguishing from the outset:

  • Laplace (lesson 7) fits at the mode: the center of qq is the maximum of pp and its variance is the inverse curvature of −log⁡p-\log p there. It looks at pp at only one point.
  • Variational inference (lesson 18) minimizes KL⁡(q ∥ p)\KL(q \,\|\, p). It penalizes qq for putting mass where pp has none, so it tends to keep one mode.
  • Moment matching, next, minimizes KL⁡(p ∥ q)\KL(p \,\|\, q). It penalizes qq for failing to cover mass that pp 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 N(0,1)\Normal(0, 1) is multiplied by a non-Gaussian factor; both approximations use the same distribution pp and yield different Gaussians.

InteractiveProject a tilted distribution
  • prior N(μ0,σ02)\Normal(\mu_0, \sigma_0^2)
  • factor f(x)f(x) (rescaled)
  • exact tilted distribution pp
  • moment-matched Gaussian
  • Laplace
Likelihood factor
0.00
1.00
1.00
0.50
Constant Z=∫N(x∣μ0,σ02) f(x)  ⁣dxZ = \int \Normal(x\mid\mu_0,\sigma_0^2)\, f(x)\,\dd x0.1855
Mean and variance of pp (closed form)1.289 and 0.370
Moment-matched Gaussian: KL(p ∥ q)\mathrm{KL}(p\,\|\,q)0.0127
Laplace: mode and variance1.176 and 0.311
Laplace: KL(p ∥ q)\mathrm{KL}(p\,\|\,q)0.0409
Choose the factor (probit, step or Student t) and move it with the orange point or sliders. The blue Gaussian matches the mean and variance of pp (gray); red is the Laplace approximation at the mode. With the step, Laplace either ignores the truncation or does not exist. With t and an observation far from the prior, pp has two modes: Laplace chooses one, while the projection covers both. Enable 'fit a Gaussian qq by hand' and find the minimum of KL(p ∥ q)\mathrm{KL}(p\,\|\,q): where is it, and where is the minimum of KL(q ∥ p)\mathrm{KL}(q\,\|\,p)?

Now the definition and result, for any exponential family Q={qη}\mathcal{Q} = \{q_{\vb{\eta}}\} with qη(x)=h(x)exp⁡ ⁣(η⊤T(x)−A(η))q_{\vb{\eta}}(\vb{x}) = h(\vb{x})\exp\!\big(\vb{\eta}\T\vb{T}(\vb{x}) - A(\vb{\eta})\big), for which you already know from exponential families that ∇A(η)=Eqη[T]\nabla A(\vb{\eta}) = \E_{q_{\vb{\eta}}}[\vb{T}] and ∇2A(η)=Cov⁡qη(T)\nabla^2 A(\vb{\eta}) = \Cov_{q_{\vb{\eta}}}(\vb{T}).

The guided exercise at the end gives the argument. The idea fits in one line: KL⁡(p ∥ qη)=cte−η⊤Ep[T]+A(η)\KL(p \,\|\, q_{\vb{\eta}}) = \text{cte} - \vb{\eta}\T\E_p[\vb{T}] + A(\vb{\eta}) is a convex function of η\vb{\eta} (because AA is convex), and its gradient, ∇A(η)−Ep[T]\nabla A(\vb{\eta}) - \E_p[\vb{T}], vanishes exactly when moments match. The same identity says maximum likelihood is a special case with pp the empirical distribution, the likelihood equation of an exponential family seen in statistics and inference.

The Gaussian case. For q=N(μ,Σ)q = \Normal(\vb{\mu}, \mat{\Sigma}), T(x)=(x,xx⊤)\vb{T}(\vb{x}) = (\vb{x}, \vb{x}\vb{x}\T) and the projection is the Gaussian with the mean and covariance of pp: μ∗=Ep[x]\vb{\mu}^* = \E_p[\vb{x}], Σ∗=Cov⁡p(x)\mat{\Sigma}^* = \Cov_p(\vb{x}). Existence requires pp to have those moments: for a Cauchy, Ep[x2]=∞\E_p[x^2] = \infty and KL⁡(p ∥ q)=∞\KL(p \,\|\, q) = \infty 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 KL⁡(p ∥ q)\KL(p \,\|\, q) reproduces the marginal probabilities, and so on.

How to calculate moments of p∝Nfp \propto \Normal f. Without new integrals, the tilted moments follow by differentiating log⁡Z\log Z with respect to the prior parameters, because ∂μ0N(x∣μ0,v0)=N⋅(x−μ0)/v0\partial_{\mu_0}\Normal(x \given \mu_0, v_0) = \Normal\cdot(x - \mu_0)/v_0 (here v0=σ02v_0 = \sigma_0^2). Differentiating twice under the integral,

Ep[x]=μ0+v0 ∂log⁡Z∂μ0,Var⁡p(x)=v0+v02 ∂2log⁡Z∂μ02.\E_p[x] = \mu_0 + v_0\,\pd{\log Z}{\mu_0}, \qquad \Var_p(x) = v_0 + v_0^2\,\frac{\partial^2\log Z}{\partial\mu_0^2}.

(The first is immediate. For the second, ∂μ02Z/Z=Ep[(x−μ0)2]/v02−1/v0\partial^2_{\mu_0}Z/Z = \E_p[(x - \mu_0)^2]/v_0^2 - 1/v_0, and subtract the square of the first derivative of log⁡Z\log Z.) It suffices to calculate ZZ.

Probit. With f(x)=Φ((x−c)/s)f(x) = \Phi\big((x - c)/s\big), ZZ is the probability that c+s ε<xc + s\,\varepsilon < x with independent x∼N(μ0,v0)x \sim \Normal(\mu_0, v_0) and ε∼N(0,1)\varepsilon \sim \Normal(0, 1), namely Z=Φ(z)Z = \Phi(z) with z=(μ0−c)/s2+v0z = (\mu_0 - c)/\sqrt{s^2 + v_0}. With r(z)=φ(z)/Φ(z)r(z) = \varphi(z)/\Phi(z) (the inverse Mills ratio, satisfying r′(z)=−r(z) (z+r(z))r'(z) = -r(z)\,(z + r(z))),

Ep[x]=μ0+v0s2+v0 r(z),Var⁡p(x)=v0−v02s2+v0 r(z)(z+r(z)).\E_p[x] = \mu_0 + \frac{v_0}{\sqrt{s^2 + v_0}}\,r(z), \qquad \Var_p(x) = v_0 - \frac{v_0^2}{s^2 + v_0}\,r(z)\big(z + r(z)\big).

Step. With f(x)=1[x>c]f(x) = \ind[x > c] this is the limit s→0s \to 0: the truncated Gaussian, with α=(c−μ0)/σ0\alpha = (c - \mu_0)/\sigma_0, Z=Φ(−α)Z = \Phi(-\alpha) and λ=φ(α)/Φ(−α)\lambda = \varphi(\alpha)/\Phi(-\alpha),

Ep[x]=μ0+σ0λ,Var⁡p(x)=σ02(1+αλ−λ2).\E_p[x] = \mu_0 + \sigma_0\lambda, \qquad \Var_p(x) = \sigma_0^2\big(1 + \alpha\lambda - \lambda^2\big).

Two consistency checks. With s→0s \to 0, z→(μ0−c)/σ0=−αz \to (\mu_0 - c)/\sigma_0 = -\alpha and r(z)→φ(α)/Φ(−α)=λr(z) \to \varphi(\alpha)/\Phi(-\alpha) = \lambda, the probit formulas become the step formulas. With c→−∞c \to -\infty the factor equals 11 everywhere, λ→0\lambda \to 0 and αλ→0\alpha\lambda \to 0, and you recover the prior. There is no closed form for Student tt; compute it by Gauss-Hermite quadrature or numerically, as the figure does.

Return to the figure and look for three things.

  1. With the step, Laplace misses what matters. If μ0≤c\mu_0 \le c, the maximum of pp is at the boundary x=cx = c, where log⁡p\log p jumps from −∞-\infty to a finite value (and if μ0<c\mu_0 < c its right derivative does not even vanish): there is no neighborhood of the mode for a Taylor expansion and no Laplace approximation. If μ0>c\mu_0 > c, the mode is the prior mode and Laplace returns the entire prior, still containing the mass removed by truncation: its KL⁡(p ∥ q)\KL(p \,\|\, q) is −log⁡Z-\log Z. The projection preserves mean and variance.
  2. With tt and a distant observation, pp is bimodal. With default settings (prior N(0,1)\Normal(0, 1), observation c=3.5c = 3.5, scale 0.30.3, ν=2\nu = 2), pp has one mode at x≈1.33x \approx 1.33, between prior and observation, and another at x≈3.23x \approx 3.23, 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 pp left uncovered, as measured by KL⁡(p ∥ q)\KL(p \,\|\, q).
  3. The minimum of KL⁡(p ∥ q)\KL(p \,\|\, q) is at the projection, not the mode. In manual fitting, move mean and scale: KL⁡(p ∥ q)\KL(p \,\|\, q) decreases only until reaching the moment-matched Gaussian (offset 00, factor ×1.00\times 1.00) and increases in either direction. KL⁡(q ∥ p)\KL(q \,\|\, p) has its minimum elsewhere, and with the step it is infinite for every Gaussian qq because qq always puts some mass in x<cx < c, where p=0p = 0.

The elementary step of ADF and expectation propagation is exactly this: given a Gaussian approximation qq and non-Gaussian factor fif_i, replace qq with the moment projection of q fiq\,f_i (for ADF, assumed-density filtering, in lesson 14) or q∖i fiq_{\setminus i}\,f_i with the cavity removed (for EP, lesson 20). The work is calculating ZZ and its first two derivatives, which you will write in the lab.

[ ]Moments of tilted distributions: closed form, quadrature and Monte CarloBrowser
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 (ZZ, mean and variance to the third digit). Gauss-Hermite quadrature converges geometrically fast for the analytic probit factor (mean error 7⋅10−27 \cdot 10^{-2} with 5 nodes, 6⋅10−106 \cdot 10^{-10} with 50), and does not converge in practice for the discontinuous step: error stays between 0.070.07 and 0.20.2 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 KL⁡(p ∥ q)\KL(p \,\|\, q) lands on the mean and variance of pp (1.28911.2891 and 0.36950.3695), as the theorem says, while Laplace, centered at mode 1.1761.176 with variance 0.3110.311, pays three times the KL (0.0410.041 versus 0.0130.013).

Reuse map

Tool from this lessonWhere it returns
Conditioning and marginalizing (Schur)Kalman (lessons 12 and 13), Gaussian processes (16 and 20), Gibbs with Gaussian conditionals (22)
Information formGaussian Markov fields (3), Gaussian message passing (5), information filter
Linear Gaussian modelBayesian regression (6), Kalman correction (12), Gaussian-process regression (16)
Cholesky, jitterEverywhere: densities, sampling, Gaussian processes (16 and 20), square-root Kalman (12)
Normal-gamma and Normal-Wishart, tt predictiveRegression with unknown noise (6), conjugate Gibbs and CAVI (22 and 18), hierarchical models (24)
Moment matchingADF 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

NumericTwo thermometers
Two thermometers measure the same temperature. The first reads 20.020.0 with variance 11 and the second 21.021.0 with variance 0.250.25. With a flat prior, what is the mean of the fused posterior?
log⁡[N(x∣z1,r1) N(x∣z2,r2)]=−12((x−z1)2r1+(x−z2)2r2)+cte\begin{aligned}\log\big[\Normal(x \given z_1, r_1)\,\Normal(x \given z_2, r_2)\big] \\ = -\tfrac12\Big(\tfrac{(x - z_1)^2}{r_1} + \tfrac{(x - z_2)^2}{r_2}\Big) + \text{cte}\end{aligned}
Posterior with a flat prior: product of the two likelihoods viewed as functions of xx. Predict the next step by grouping powers of xx.
1/5
QuizWhat is true about conditioning
Let (xa,xb)(\vb{x}_a, \vb{x}_b) be Gaussian with Σbb≻0\mat{\Sigma}_{bb} \succ 0. Which statements are true?

More than one answer may be correct.

ProofThe minimum of KL(p‖q) matches moments
Prove: Let qη(x)=h(x)exp⁡(η⊤T(x)−A(η))q_{\vb{\eta}}(\vb{x}) = h(\vb{x})\exp\big(\vb{\eta}\T\vb{T}(\vb{x}) - A(\vb{\eta})\big) be a regular exponential family and pp a density with Ep∣T∣<∞\E_p\abs{\vb{T}} < \infty and KL⁡(p ∥ qη)<∞\KL(p \,\|\, q_{\vb{\eta}}) < \infty for some η\vb{\eta}. Then η∗\vb{\eta}^* minimizes KL⁡(p ∥ qη)\KL(p \,\|\, q_{\vb{\eta}}) if and only if Eqη∗[T]=Ep[T]\E_{q_{\vb{\eta}^*}}[\vb{T}] = \E_p[\vb{T}].
0
Start from the definition KL⁡(p ∥ q)=Ep[log⁡p−log⁡q]\KL(p \,\|\, q) = \E_p[\log p - \log q] and the fact that, in a regular exponential family, AA is differentiable and ∇A(η)=Eqη[T]\nabla A(\vb{\eta}) = \E_{q_{\vb{\eta}}}[\vb{T}], ∇2A(η)=Cov⁡qη(T)\nabla^2 A(\vb{\eta}) = \Cov_{q_{\vb{\eta}}}(\vb{T}).

Step 1 of 4. How do you write KL⁡(p ∥ qη)\KL(p \,\|\, q_{\vb{\eta}}) while separating what depends on η\vb{\eta}?

NumericMoment-matched Gaussian: the mean
Project distribution p∝N(x∣0,1) 1[x>0]p \propto \Normal(x \given 0, 1)\,\ind[x > 0] onto Gaussians by moment matching. What is the mean of the resulting Gaussian?
NumericMoment-matched Gaussian: the variance
For the same p∝N(x∣0,1) 1[x>0]p \propto \Normal(x \given 0, 1)\,\ind[x > 0], what is the variance of the Gaussian matching its moments?
QuizLaplace versus moments with a step
The prior is N(0,4)\Normal(0, 4) and the factor is the step 1[x>−1]\ind[x > -1], so p∝N(x∣0,4) 1[x>−1]p \propto \Normal(x \given 0, 4)\,\ind[x > -1]. What do the Laplace approximation and moment-matched Gaussian return?
ProofThe t distribution comes from integrating variance
Prove: If λ∼Gamma(a,b)\lambda \sim \mathrm{Gamma}(a, b) and x∣λ∼N(μ,1/(λτ))x \given \lambda \sim \Normal(\mu, 1/(\lambda\tau)), the marginal of xx is a tt with 2a2a degrees of freedom, location μ\mu and scale b/(aτ)b/(a\tau) (scale variance, that is σt2=b/(aτ)\sigma_t^2 = b/(a\tau)).
0
Write Δ2=τ(x−μ)2\Delta^2 = \tau(x - \mu)^2 and recall ∫0∞λα−1e−βλ ⁣dλ=Γ(α)β−α\int_0^\infty\lambda^{\alpha - 1}e^{-\beta\lambda}\dd\lambda = \Gamma(\alpha)\beta^{-\alpha}.

Step 1 of 3. Which integral do you set up?

QuizFive observations and heavy tails
You have 55 observations from a Gaussian with unknown variance and use a Normal-gamma prior. Why does the predictive distribution have heavier tails than a Gaussian with estimated variance, and what happens as nn grows?
QuizChoose the prior scale
You work in dimension d=3d = 3 under Bishop's convention (E[Λ]=νW\E[\mat{\Lambda}] = \nu\mat{W}) and want a Normal-Wishart prior with ν0=10\nu_0 = 10 pseudo-observations whose expected covariance equals your prior estimate: E[Σ]=Σ0\E[\mat{\Sigma}] = \mat{\Sigma}_0, with Σ=Λ−1\mat{\Sigma} = \mat{\Lambda}\inv. Which scale matrix W0\mat{W}_0 do you choose?
NumericVariance of a t predictive distribution
An unknown mean and variance have Normal-gamma prior m0=0m_0 = 0, κ0=1\kappa_0 = 1, a0=2a_0 = 2, b0=2b_0 = 2 (precision λ∼Gamma(a0,b0)\lambda \sim \mathrm{Gamma}(a_0, b_0), μ∣λ∼N(m0,1/(κ0λ))\mu \given \lambda \sim \Normal(m_0, 1/(\kappa_0\lambda))). You observe n=4n = 4 points with mean yˉ=3\bar y = 3 and S=∑(yi−yˉ)2=6S = \sum(y_i - \bar y)^2 = 6. What is the predictive variance for a new observation?
NumericVariance of projection with a probit factor
Project p∝N(x∣0,1) Φ(x)p \propto \Normal(x \given 0, 1)\,\Phi(x) (probit with c=0c = 0 and s=1s = 1) onto Gaussians by moment matching. What is the resulting variance?
CodeGaussian log density with Cholesky
Implement mvn_logpdf_chol(x, mu, L) to return the log density of N(μ,LL⊤)\Normal(\vb{\mu}, \mat{L}\mat{L}\T) 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 det⁡Σ\det\mat{\Sigma} 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.0
Shift+Enter to run
CodeNormal-Wishart update
Implement normal_wishart_update(m0, kappa0, nu0, W0, X) under Bishop's convention (E[Λ]=νW\E[\mat{\Lambda}] = \nu\mat{W}, 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 d=1d = 1 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, W0
Shift+Enter to run
CodeMoments of a probit-tilted distribution
Implement probit_moments(mu0, v0, c, s) returning (Z, media, varianza) for p∝N(x∣μ0,v0) Φ((x−c)/s)p \propto \Normal(x \given \mu_0, v_0)\,\Phi((x - c)/s) 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 Φ(z)\Phi(z) is very small (use scipy.special.log_ndtr or a stable Mills ratio for r(z)=φ(z)/Φ(z)r(z) = \varphi(z)/\Phi(z)).
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, v0
Shift+Enter to run

Summary

Key idea
Modeling writes the joint distribution, inference conditions, and deciding minimizes expected posterior loss. In the Gaussian world conditioning is closed-form algebra (Schur or adding precisions) computed with Cholesky; with unknown variance conjugacy stays closed-form but the predictive distribution is Student t; and when a posterior is non-Gaussian, the Gaussian minimizing KL(p ‖ q) matches its moments.
  • 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 νn=ν0+n\nu_n = \nu_0 + n and κn=κ0+n\kappa_n = \kappa_0 + n; the predictive distribution is tt with 2an2a_n or νn−d+1\nu_n - d + 1 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, arg min⁡qKL⁡(p ∥ q)\argmin_q\KL(p \,\|\, q) satisfies Eq[T]=Ep[T]\E_q[\vb{T}] = \E_p[\vb{T}]. For T=(x,xx⊤)\vb{T} = (\vb{x}, \vb{x}\vb{x}\T) it is the Gaussian with the mean and covariance of pp; moments of N⋅f\Normal\cdot f follow from log⁡Z\log Z and its derivatives. This is neither Laplace (the mode) nor variational inference (KL⁡(q ∥ p)\KL(q \,\|\, p)): it is the ADF and EP step.