Module contents
Lesson 15 of 24Advanced 115 min

The multivariate Gaussian II: marginalization, conditioning and linear-Gaussian models

The two operations that make Gaussians tractable: marginalization by selecting a sub-block and conditioning via the Schur complement. Study information form, conditional independence in the precision matrix, the linear Gaussian model underlying Gaussian processes, Kalman filtering and diffusion, sensor fusion and Stein's lemma.

After this lesson you can

  • Derive the conditional mean and covariance of a partitioned Gaussian by completing the square and by projection in L².
  • Work in moment and information forms and choose the appropriate one for marginalization or conditioning.
  • Read conditional independences from zeros of the precision matrix.
  • Compute the marginal and posterior of a linear Gaussian model and recognize the Kalman gain.
  • Prove and apply Stein's lemma.

Before you start

Motivation: three algorithms, one formula

Three algorithms you will implement in this course seem unrelated:

  • Gaussian process regression. You know an unknown function’s values at a few points and want predictions with error bars elsewhere.
  • Kalman filter update. A vehicle believes it is at a position with some uncertainty; a noisy GPS measurement arrives and that belief must be revised.
  • Diffusion. Training a diffusion model requires the law of xt−1\vb{x}_{t-1} given clean data x0\vb{x}_0 and its noisy version xt\vb{x}_t, the target the network learns to imitate.

All three compute the same thing: the law of one part of a Gaussian vector conditioned on another. If (Xa,Xb)(\vb{X}_a, \vb{X}_b) is Gaussian, the answer is

Xa∣Xb=xb  ∼  N(μa+ΣabΣbb−1(xb−μb),    Σaa−ΣabΣbb−1Σba),\vb{X}_a \given \vb{X}_b = \vb{x}_b \;\sim\; \Normal\big(\vb{\mu}_a + \mat{\Sigma}_{ab}\mat{\Sigma}_{bb}\inv(\vb{x}_b - \vb{\mu}_b),\;\; \mat{\Sigma}_{aa} - \mat{\Sigma}_{ab}\mat{\Sigma}_{bb}\inv\mat{\Sigma}_{ba}\big),

and this lesson understands that line in every possible way. The previous lesson studied a whole Gaussian vector. Here we split it into blocks and perform probability’s two basic operations: marginalize (forget a part) and condition (fix a part at its observed value). Both have closed forms for Gaussians, making them a building block of Gaussian processes, Kalman filtering and diffusion. Along the way: the precision matrix, whose zeros encode an independence graph; the Gaussian linear model, containing those three algorithms as special cases; and Stein’s lemma, integration by parts connecting Gaussians and gradients.

Partitioning and marginalization

Fix notation for the lesson. Split X∼N(μ,Σ)\vb{X} \sim \Normal(\vb{\mu}, \mat{\Sigma}) in Rd\R^d into coordinate blocks Xa∈Rp\vb{X}_a \in \R^{p} and Xb∈Rq\vb{X}_b \in \R^{q} with p+q=dp + q = d, and write mean and covariance as block matrices:

X=[XaXb],μ=[μaμb],Σ=[ΣaaΣabΣbaΣbb],Σba=Σab⊤.\vb{X} = \begin{bmatrix} \vb{X}_a \\ \vb{X}_b \end{bmatrix}, \qquad \vb{\mu} = \begin{bmatrix} \vb{\mu}_a \\ \vb{\mu}_b \end{bmatrix}, \qquad \mat{\Sigma} = \begin{bmatrix} \mat{\Sigma}_{aa} & \mat{\Sigma}_{ab} \\ \mat{\Sigma}_{ba} & \mat{\Sigma}_{bb} \end{bmatrix}, \quad \mat{\Sigma}_{ba} = \mat{\Sigma}_{ab}\T.

Nothing requires aa to contain the first coordinates: any index subset works after permutation. For an arbitrary random vector, the law of Xa\vb{X}_a requires integrating joint density over xb\vb{x}_b. For a Gaussian no integration is needed.

Proof

Let Ea=[Ip    0]∈Rp×d\mat{E}_a = [\mat{I}_p \;\; \mat{0}] \in \R^{p \times d} select coordinates of aa, so Xa=EaX\vb{X}_a = \mat{E}_a\vb{X}. By closure under affine transformations, Xa∼N(Eaμ,EaΣEa⊤)=N(μa,Σaa)\vb{X}_a \sim \Normal(\mat{E}_a\vb{\mu}, \mat{E}_a\mat{\Sigma}\mat{E}_a\T) = \Normal(\vb{\mu}_a, \mat{\Sigma}_{aa}).

∎

Geometrically, marginalization is projection: the X\vb{X} cloud is flattened onto the coordinate subspace of aa, revealing its shadow. Beware the false converse: Gaussian marginals do not make the vector Gaussian (the counterexample in the projection definition). Everything below assumes the joint vector, not merely its parts, is Gaussian.

Conditioning: slicing instead of projecting

Conditioning is different. Rather than flattening the cloud, slice the joint density by affine subspace {xb fijo}\{\vb{x}_b \text{ fijo}\} and renormalize what remains to integrate to one: the conditional density p(xa∣xb)=p(xa,xb)/p(xb)p(\vb{x}_a \given \vb{x}_b) = p(\vb{x}_a, \vb{x}_b)/p(\vb{x}_b). Before formulas, compare the operations in two dimensions.

InteractiveProjecting versus slicing
Joint density: line x1=ax_1 = a slices, the left edge projects
E[X₂ | X₁]
Densities of X2X_2: marginal versus conditional
  • marginal p(x₂): project
  • unnormalized slice p(a, x₂)
  • conditional p(x₂ | a): slice and renormalize
The slice has area pX1(a)=0.144p_{X_1}(a) = 0.144; dividing by it gives the conditional. Its width σ21−ρ2=0.763\sigma_2\sqrt{1-\rho^2} = 0.763 does not depend on aa.
1.60
0.72
1.30
1.10
Σ=[1.691.031.031.21]\mat{\Sigma} = \begin{bmatrix} 1.69 & 1.03 \\ 1.03 & 1.21 \end{bmatrix}
E[X2∣X1=a]=βa\E[X_2 \given X_1 = a] = \beta a0.975
Var⁡(X2∣X1=a)=σ22(1−ρ2)\Var(X_2 \given X_1 = a) = \sigma_2^2(1 - \rho^2)0.583
Var⁡(X2)\Var(X_2), marginal1.210
Slope β=Σ21/Σ11\beta = \Sigma_{21}/\Sigma_{11}0.609
Slice area, pX1(a)p_{X_1}(a)0.1439
Centered Gaussian in R2\R^2 with Mahalanobis ellipses of radius 1, 2 and 3. At the left edge, gray marginal density of X2X_2: the shadow of the whole cloud. On orange line x1=ax_1 = a, blue conditional density of X2X_2 given X1=aX_1 = a, with its ±2\pm 2 standard-deviation interval. Below, light gray marginal of X1X_1; height at aa (orange point) is slice mass up to scale. Right panel overlays all three curves on the x2x_2 axis. Dashed blue is E[X2∣X1]\E[X_2 \given X_1]; hollow circles mark vertical tangency points of the radius-2 ellipse.

What you should have seen:

  • Conditional mean follows a line. Dragging aa slides the blue bell’s center along x2=βx1x_2 = \beta x_1 with β=Σ21/Σ11\beta = \Sigma_{21}/\Sigma_{11}, the regression line of X2X_2 on X1X_1. At initial values (σ1=1.3\sigma_1 = 1.3, σ2=1.1\sigma_2 = 1.1, ρ=0.72\rho = 0.72), β=0.609\beta = 0.609 and E[X2∣X1=1.6]=0.975\E[X_2 \given X_1 = 1.6] = 0.975.
  • Conditional width does not depend on aa. The blue bell shifts without changing shape: variance is σ22(1−ρ2)=0.583\sigma_2^2(1 - \rho^2) = 0.583 for all aa, versus marginal variance σ22=1.21\sigma_2^2 = 1.21. Conditioning always narrows (or leaves unchanged if ρ=0\rho = 0).
  • Renormalizing divides by slice mass. The dashed orange curve on the right is the raw slice p(a,x2)p(a, x_2); it has conditional shape but area pX1(a)p_{X_1}(a), marked by the lower orange point’s height (the “Slice area” reading). Division by that number is all Bayes’s formula does.
  • The regression line is not the principal axis. Enable “Inverse line and principal axis”: E[X2∣X1]\E[X_2 \given X_1] passes through vertical ellipse tangencies, E[X1∣X2]\E[X_1 \given X_2] through horizontal tangencies, and the major axis lies between them. Each regression line, read as a function of its predictor, is flatter than the axis: Galton’s regression to the mean.

The two-dimensional case sets the pattern: conditional mean is affine in the observation, conditional covariance constant. In arbitrary dimension the statement is the same, with matrices.

There are two proofs, both worthwhile. The first is geometric and avoids densities: it works even when Σaa\mat{\Sigma}_{aa} is singular.

Proof

Projection proof. Define residual R=(Xa−μa)−G(Xb−μb)\vb{R} = (\vb{X}_a - \vb{\mu}_a) - \mat{G}(\vb{X}_b - \vb{\mu}_b). The pair (R,Xb)(\vb{R}, \vb{X}_b) is an affine transformation of X\vb{X}, hence Gaussian. Its cross-covariance is

Cov⁡(R,Xb)=Σab−GΣbb=Σab−ΣabΣbb−1Σbb=0.\Cov(\vb{R}, \vb{X}_b) = \mat{\Sigma}_{ab} - \mat{G}\mat{\Sigma}_{bb} = \mat{\Sigma}_{ab} - \mat{\Sigma}_{ab}\mat{\Sigma}_{bb}\inv\mat{\Sigma}_{bb} = \mat{0}.

Within a Gaussian vector, uncorrelated implies independent: R⊥ ⁣ ⁣ ⁣⊥Xb\vb{R} \indep \vb{X}_b. Also E[R]=0\E[\vb{R}] = \vb{0} and

Cov⁡(R)=Σaa−GΣba−ΣabG⊤+GΣbbG⊤=Σaa−ΣabΣbb−1Σba,\Cov(\vb{R}) = \mat{\Sigma}_{aa} - \mat{G}\mat{\Sigma}_{ba} - \mat{\Sigma}_{ab}\mat{G}\T + \mat{G}\mat{\Sigma}_{bb}\mat{G}\T = \mat{\Sigma}_{aa} - \mat{\Sigma}_{ab}\mat{\Sigma}_{bb}\inv\mat{\Sigma}_{ba},

because the last three terms are −ΣabΣbb−1Σba-\mat{\Sigma}_{ab}\mat{\Sigma}_{bb}\inv\mat{\Sigma}_{ba}, −ΣabΣbb−1Σba-\mat{\Sigma}_{ab}\mat{\Sigma}_{bb}\inv\mat{\Sigma}_{ba} and +ΣabΣbb−1Σba+\mat{\Sigma}_{ab}\mat{\Sigma}_{bb}\inv\mat{\Sigma}_{ba}. Thus Xa=μa+G(Xb−μb)+R\vb{X}_a = \vb{\mu}_a + \mat{G}(\vb{X}_b - \vb{\mu}_b) + \vb{R}, with R∼N(0,Σa∣b)\vb{R} \sim \Normal(\vb{0}, \mat{\Sigma}_{a \given b}) independent of Xb\vb{X}_b. For bounded measurable ff, the freezing lemma (if R⊥ ⁣ ⁣ ⁣⊥Xb\vb{R} \indep \vb{X}_b, then E[ϕ(Xb,R)∣Xb]=ψ(Xb)\E[\phi(\vb{X}_b, \vb{R}) \given \vb{X}_b] = \psi(\vb{X}_b) with ψ(x)=E[ϕ(x,R)]\psi(\vb{x}) = \E[\phi(\vb{x}, \vb{R})], proved using Fubini) gives

E[f(Xa)∣Xb]=ψ(Xb),ψ(xb)=E[f(μa+G(xb−μb)+R)]=∫f  ⁣dN(μa∣b,Σa∣b),\E[f(\vb{X}_a) \given \vb{X}_b] = \psi(\vb{X}_b), \qquad \psi(\vb{x}_b) = \E\big[f\big(\vb{\mu}_a + \mat{G}(\vb{x}_b - \vb{\mu}_b) + \vb{R}\big)\big] = \int f \,\dd\Normal(\vb{\mu}_{a \given b}, \mat{\Sigma}_{a \given b}),

which says exactly that N(μa∣b,Σa∣b)\Normal(\vb{\mu}_{a \given b}, \mat{\Sigma}_{a \given b}) is the conditional law of Xa\vb{X}_a at Xb=xb\vb{X}_b = \vb{x}_b.

∎

The proof says more than the claim. Decomposition Xa=μa+G(Xb−μb)⏟funcioˊn de Xb+R⏟⊥ ⁣ ⁣ ⁣⊥ Xb\vb{X}_a = \underbrace{\vb{\mu}_a + \mat{G}(\vb{X}_b - \vb{\mu}_b)}_{\text{función de } \vb{X}_b} + \underbrace{\vb{R}}_{\indep\, \vb{X}_b} is the orthogonal projection in L2L^2 of Xa\vb{X}_a onto functions of Xb\vb{X}_b. For an arbitrary vector, μa+G(Xb−μb)\vb{\mu}_a + \mat{G}(\vb{X}_b - \vb{\mu}_b) would only be the best affine prediction; here residual is independent of Xb\vb{X}_b, not just uncorrelated, so orthogonal to every function of Xb\vb{X}_b, and best affine prediction is best prediction outright:

E[Xa∣Xb]=μa+ΣabΣbb−1(Xb−μb).\E[\vb{X}_a \given \vb{X}_b] = \vb{\mu}_a + \mat{\Sigma}_{ab}\mat{\Sigma}_{bb}\inv(\vb{X}_b - \vb{\mu}_b).

The law of total variance reads from the same decomposition. Total covariance divides into the part explained by Xb\vb{X}_b and what remains:

Σaa=Cov⁡(E[Xa∣Xb])⏟GΣbbG⊤ = ΣabΣbb−1Σba+E[Cov⁡(Xa∣Xb)]⏟Σa∣b.\mat{\Sigma}_{aa} = \underbrace{\Cov\big(\E[\vb{X}_a \given \vb{X}_b]\big)}_{\mat{G}\mat{\Sigma}_{bb}\mat{G}\T \,=\, \mat{\Sigma}_{ab}\mat{\Sigma}_{bb}\inv\mat{\Sigma}_{ba}} + \underbrace{\E\big[\Cov(\vb{X}_a \given \vb{X}_b)\big]}_{\mat{\Sigma}_{a \given b}}.

Since the first term is positive semidefinite, Σa∣b⪯Σaa\mat{\Sigma}_{a \given b} \preceq \mat{\Sigma}_{aa}: conditioning never increases uncertainty of any linear combination c⊤Xa\vb{c}\T\vb{X}_a. In the scalar case with ρ=Corr⁡(X1,X2)\rho = \operatorname{Corr}(X_1, X_2), all reduces to two formulas worth memorizing:

E[X2∣X1=x]=μ2+ρ σ2σ1(x−μ1),Var⁡(X2∣X1=x)=σ22(1−ρ2).\E[X_2 \given X_1 = x] = \mu_2 + \rho\,\frac{\sigma_2}{\sigma_1}(x - \mu_1), \qquad \Var(X_2 \given X_1 = x) = \sigma_2^2(1 - \rho^2).

In standardized units, prediction is ρ\rho times observed deviation: a father one standard deviation taller than average has children averaging only ρ\rho deviations above. Galton called this regression to the mean, a geometric consequence of the ellipses just seen, not a biological force.

Second route: completing the square

The second proof is used for calculation and will be reused three times. It rests on an elementary fact: a density with concave quadratic log is Gaussian, and its parameters are read from coefficients.

Proof

With m=A−1b\vb{m} = \mat{A}\inv\vb{b}, −12(x−m)⊤A(x−m)=−12x⊤Ax+m⊤Ax−12m⊤Am-\tfrac{1}{2}(\vb{x} - \vb{m})\T\mat{A}(\vb{x} - \vb{m}) = -\tfrac{1}{2}\vb{x}\T\mat{A}\vb{x} + \vb{m}\T\mat{A}\vb{x} - \tfrac{1}{2}\vb{m}\T\mat{A}\vb{m} and m⊤Ax=b⊤x\vb{m}\T\mat{A}\vb{x} = \vb{b}\T\vb{x}. Thus p(x)=Cexp⁡(−12(x−m)⊤A(x−m))p(\vb{x}) = C\exp(-\tfrac{1}{2}(\vb{x} - \vb{m})\T\mat{A}(\vb{x} - \vb{m})) for C>0C > 0, the density of N(m,A−1)\Normal(\vb{m}, \mat{A}\inv) up to a factor. Both integrate to one, so the factors match.

∎

Now write the joint density with precision Λ=Σ−1\mat{\Lambda} = \mat{\Sigma}\inv, partitioned like Σ\mat{\Sigma}. As a function of xa\vb{x}_a with xb\vb{x}_b fixed, the exponent is

−12(x−μ)⊤Λ(x−μ)=−12xa⊤Λaaxa+xa⊤(Λaaμa−Λab(xb−μb))+cte,-\tfrac{1}{2}(\vb{x} - \vb{\mu})\T\mat{\Lambda}(\vb{x} - \vb{\mu}) = -\tfrac{1}{2}\vb{x}_a\T\mat{\Lambda}_{aa}\vb{x}_a + \vb{x}_a\T\big(\mat{\Lambda}_{aa}\vb{\mu}_a - \mat{\Lambda}_{ab}(\vb{x}_b - \vb{\mu}_b)\big) + \text{cte},

and the lemma gives Xa∣xb∼N(μa−Λaa−1Λab(xb−μb),  Λaa−1)\vb{X}_a \given \vb{x}_b \sim \Normal\big(\vb{\mu}_a - \mat{\Lambda}_{aa}\inv\mat{\Lambda}_{ab}(\vb{x}_b - \vb{\mu}_b),\; \mat{\Lambda}_{aa}\inv\big). Block-inverse formulas say Λaa=(Σaa−ΣabΣbb−1Σba)−1\mat{\Lambda}_{aa} = (\mat{\Sigma}_{aa} - \mat{\Sigma}_{ab}\mat{\Sigma}_{bb}\inv\mat{\Sigma}_{ba})\inv and −Λaa−1Λab=ΣabΣbb−1-\mat{\Lambda}_{aa}\inv\mat{\Lambda}_{ab} = \mat{\Sigma}_{ab}\mat{\Sigma}_{bb}\inv: same result. Exercise Completing the square works through the steps. Retain the seed of the next section: in precision, conditional covariance is a simple sub-block, Σa∣b=Λaa−1\mat{\Sigma}_{a \given b} = \mat{\Lambda}_{aa}\inv.

If Σbb\mat{\Sigma}_{bb} is singular (e.g. the same coordinate observed twice without noise), the theorem still holds with pseudoinverse Σbb+\mat{\Sigma}_{bb}\pinv in place of inverse for almost every xb\vb{x}_b under the law of Xb\vb{X}_b. In practice a little observation noise is preferable.

Conditional covariance does not depend on the observation

Look again: Σa∣b=Σaa−ΣabΣbb−1Σba\mat{\Sigma}_{a \given b} = \mat{\Sigma}_{aa} - \mat{\Sigma}_{ab}\mat{\Sigma}_{bb}\inv\mat{\Sigma}_{ba} contains no xb\vb{x}_b. How much a Gaussian observation teaches you depends only on what you observe, not its value. This special Gaussian property has practical consequences:

  • Experimental design without data. Calculate posterior uncertainty for each measurement plan before measuring. Where should three temperature sensors go in a warehouse to minimize maximum map variance? At which inputs should an expensive function be evaluated? Use Σ\mat{\Sigma} and candidate list, without a datum. Mutual information between blocks, I(Xa;Xb)=12log⁡(det⁡Σaa/det⁡Σa∣b)I(\vb{X}_a; \vb{X}_b) = \tfrac{1}{2}\log\big(\det\mat{\Sigma}_{aa}/\det\mat{\Sigma}_{a \given b}\big), also does not depend on data, so with known Gaussian parameters an optimal design can be fixed in advance and gains nothing from adaptation.
  • Precomputable Kalman filter. The sequence of covariances (and gains) depends only on model matrices; it can be computed without data and in a time-invariant model under usual detectability conditions converges to steady state. See state-space models.
  • Overconfidence. This property is also a weakness: if an absurd observation arrives six standard deviations from expectation, the Gaussian shifts its mean toward it and declares the same certainty as for a normal observation. A heavy-tailed model (Student tt, for example) would widen the posterior. With outliers, the Gaussian will not warn you.

The Gaussian-process interactive below demonstrates the first consequence: drag an observation vertically and the mean moves while the uncertainty band stays still.

Information form: precision and duality

The previous section’s final observation generalizes to a perfect symmetry. A Gaussian can be described by moments (μ,Σ)(\vb{\mu}, \mat{\Sigma}) or the natural pair in its exponent.

Proof

(1) In log⁡p(xa,xb)=−12x⊤Λx+h⊤x+c\log p(\vb{x}_a, \vb{x}_b) = -\tfrac{1}{2}\vb{x}\T\mat{\Lambda}\vb{x} + \vb{h}\T\vb{x} + c, terms containing xa\vb{x}_a are −12xa⊤Λaaxa−xa⊤Λabxb+ha⊤xa-\tfrac{1}{2}\vb{x}_a\T\mat{\Lambda}_{aa}\vb{x}_a - \vb{x}_a\T\mat{\Lambda}_{ab}\vb{x}_b + \vb{h}_a\T\vb{x}_a; the rest is constant in xa\vb{x}_a. The exponent-reading lemma gives the result.

(2) By block inversion, Σaa=(Λ−1)aa=(Λaa−ΛabΛbb−1Λba)−1\mat{\Sigma}_{aa} = (\mat{\Lambda}\inv)_{aa} = (\mat{\Lambda}_{aa} - \mat{\Lambda}_{ab}\mat{\Lambda}_{bb}\inv\mat{\Lambda}_{ba})\inv, so marginal precision is that Schur complement, call it Λ~\tilde{\mat{\Lambda}}. For the vector use h=Λμ\vb{h} = \mat{\Lambda}\vb{\mu} in blocks: ha−ΛabΛbb−1hb=Λaaμa+Λabμb−ΛabΛbb−1(Λbaμa+Λbbμb)=Λ~μa\vb{h}_a - \mat{\Lambda}_{ab}\mat{\Lambda}_{bb}\inv\vb{h}_b = \mat{\Lambda}_{aa}\vb{\mu}_a + \mat{\Lambda}_{ab}\vb{\mu}_b - \mat{\Lambda}_{ab}\mat{\Lambda}_{bb}\inv(\mat{\Lambda}_{ba}\vb{\mu}_a + \mat{\Lambda}_{bb}\vb{\mu}_b) = \tilde{\mat{\Lambda}}\vb{\mu}_a, the information vector of N(μa,Σaa)\Normal(\vb{\mu}_a, \mat{\Sigma}_{aa}).

∎

The table summarizes duality. The more useful form depends on which operation you perform most:

Moment form (μ,Σ)(\vb{\mu}, \mat{\Sigma})Information form (h,Λ)(\vb{h}, \mat{\Lambda})
Marginalizeselect sub-blocksSchur complement of Λbb\mat{\Lambda}_{bb}
ConditionSchur complement of Σbb\mat{\Sigma}_{bb}select sub-blocks (and correct ha\vb{h}_a)
Combine independent sourcescomplicatedadd h\vb{h} and Λ\mat{\Lambda}

The precision diagonal also has its own meaning. Apply (1) with a={i}a = \{i\} and bb the rest:

Λii=1Var⁡(Xi∣X−i),E[Xi∣X−i]=μi−∑j≠iΛijΛii(Xj−μj).\Lambda_{ii} = \frac{1}{\Var(X_i \given \vb{X}_{-i})}, \qquad \E[X_i \given \vb{X}_{-i}] = \mu_i - \sum_{j \neq i}\frac{\Lambda_{ij}}{\Lambda_{ii}}(X_j - \mu_j).

Each row of Λ\mat{\Lambda} divided by its diagonal is a regression of one variable on all others, with XjX_j coefficient −Λij/Λii-\Lambda_{ij}/\Lambda_{ii}. If that coefficient is zero, XjX_j does not help predict XiX_i once the rest are known. This sounds like conditional independence.

Precision zeros: a Gaussian graph

Proof

Take a={i,j}a = \{i, j\} and bb the rest. By duality, the law of (Xi,Xj)(X_i, X_j) given Xb=xb\vb{X}_b = \vb{x}_b is Gaussian with precision Λaa=[ΛiiΛijΛijΛjj]\mat{\Lambda}_{aa} = \begin{bmatrix} \Lambda_{ii} & \Lambda_{ij} \\ \Lambda_{ij} & \Lambda_{jj} \end{bmatrix}, independent of xb\vb{x}_b. Its covariance is the inverse, 1ΛiiΛjj−Λij2[Λjj−Λij−ΛijΛii]\frac{1}{\Lambda_{ii}\Lambda_{jj} - \Lambda_{ij}^2}\begin{bmatrix} \Lambda_{jj} & -\Lambda_{ij} \\ -\Lambda_{ij} & \Lambda_{ii} \end{bmatrix}, whose off-diagonal entry vanishes if and only if Λij=0\Lambda_{ij} = 0. Since the conditional law is bivariate Gaussian, uncorrelatedness equals independence, simultaneously for every xb\vb{x}_b.

∎

The correlation of that conditional law has a name: partial correlation ρij⋅resto=−Λij/ΛiiΛjj\rho_{ij \cdot \text{resto}} = -\Lambda_{ij}/\sqrt{\Lambda_{ii}\Lambda_{jj}}. It is correlation between XiX_i and XjX_j after linearly removing all other variables’ effects, and vanishes exactly when the XjX_j coefficient in the regression of XiX_i on the rest vanishes (regression with controls).

The theorem turns Λ\mat{\Lambda} into a graph: one node per variable and an edge between ii and jj when Λij≠0\Lambda_{ij} \neq 0. The Gaussian is an undirected graphical model (Gaussian Markov random field), with missing edges representing conditional independence. Covariance tells a different story: Σij=0\Sigma_{ij} = 0 means marginal independence. The matrices are inverses, and a sparse matrix rarely has a sparse inverse.

InteractiveDense covariance, sparse precision
Graph: one edge per Λij≠0\Lambda_{ij} \neq 0
X₁X₂X₃X₄X₅X₆
Blue: graph edges. Dotted: the chosen pair if it is not an edge.
Σ\mat{\Sigma}: covariance
X₁X₁X₂X₂X₃X₃X₄X₄X₅X₅X₆X₆2.801.640.970.590.380.301.642.131.260.760.500.380.971.261.921.170.760.590.590.761.171.921.260.970.380.500.761.262.131.640.300.380.590.971.642.80
Λ=Σ−1\mat{\Lambda} = \mat{\Sigma}^{-1}: precision
X₁X₁X₂X₂X₃X₃X₄X₄X₅X₅X₆X₆0.65−0.500000−0.501.15−0.500000−0.501.15−0.500000−0.501.15−0.500000−0.501.15−0.500000−0.500.65
Operation
Variable kk
Off-diagonal zeros of Λ\mat{\Lambda}10 of 15
Off-diagonal zeros of Σ\mat{\Sigma}0 of 15
New edges (fill-in)0
Marginal correlation of X1,X3X_{1}, X_{3}0.417
Partial correlation given the rest0 (exact)
Six Gaussian variables. Graph edges fix zeros of Λ\mat{\Lambda} (diagonal 0.15+0.5⋅grado0.15 + 0.5\cdot\text{grado}, or 11 for an isolated node, and −0.5-0.5 per edge: diagonally dominant, hence positive definite). Click one node then another to add or remove an edge. Matrices show values; color is correlation (in Σ\mat{\Sigma}) or partial correlation (in Λ\mat{\Lambda}), and dotted cells are exact zeros. With 'Condition', variable XkX_k is observed (filled node); with 'Marginalize', it is integrated out (dashed node), and magenta edges are fill-in.

What you should have seen:

  • Chain: tridiagonal precision, dense covariance. In Markov chain X1−X2−⋯−X6X_1 - X_2 - \cdots - X_6, Λ\mat{\Lambda} has 10 of 15 possible zeros and Σ\mat{\Sigma} none: X1X_1 and X3X_3 have marginal correlation 0.4170.417 and exactly 00 partial correlation. Even endpoints X1X_1 and X6X_6 correlate (0.1050.105). Dependence propagates along graph paths although each variable talks only to neighbors.
  • Conditioning removes only the node. Observe X3X_3: its row and column disappear from Λ\mat{\Lambda} and the rest stays intact. In Σ\mat{\Sigma}, the Schur complement instead creates a zero block between {X1,X2}\{X_1, X_2\} and {X4,X5,X6}\{X_4, X_5, X_6\}: observing a graph separator makes both halves marginally independent.
  • Marginalizing connects neighbors. In the star, integrating center X1X_1 adds 10 fill-in edges: five leaves conditionally independent given center become connected. Integrating a chain endpoint (X1X_1, one neighbor) adds none. This is the fill-in that makes sparse-system variable elimination expensive, making elimination order important in sparse Cholesky factorization.

This reaches far. Sparse precision underlies Gaussian graphical models (estimated with ℓ1\ell_1 penalty by graphical lasso), Gaussian Markov random fields in spatial statistics (millions of variables but few Λ\mat{\Lambda} entries per row), and the Kalman smoother, a block-tridiagonal linear system.

The linear-Gaussian model

Now the central result. Most previous uses share a structure: a hidden quantity with Gaussian prior belief and a noisy Gaussian linear observation.

Proof

Pair (x,v)(\vb{x}, \vb{v}) is Gaussian (independent Gaussians), and (x,y)(\vb{x}, \vb{y}) is its affine transform, so Gaussian. Moments: E[y]=Hm+b\E[\vb{y}] = \mat{H}\vb{m} + \vb{b}; Cov⁡(x,y)=Cov⁡(x,Hx+v)=PH⊤\Cov(\vb{x}, \vb{y}) = \Cov(\vb{x}, \mat{H}\vb{x} + \vb{v}) = \mat{P}\mat{H}\T; Cov⁡(y)=HPH⊤+R=S\Cov(\vb{y}) = \mat{H}\mat{P}\mat{H}\T + \mat{R} = \mat{S}. This is (1). Point (2) marginalizes (select y\vb{y} block); (3) applies the conditioning theorem with Σab=PH⊤\mat{\Sigma}_{ab} = \mat{P}\mat{H}\T and Σbb=S\mat{\Sigma}_{bb} = \mat{S}, positive definite because R≻0\mat{R} \succ 0: G=K\mat{G} = \mat{K} and Σa∣b=P−KHP\mat{\Sigma}_{a \given b} = \mat{P} - \mat{K}\mat{H}\mat{P}.

For (4), complete the square in x\vb{x} in log⁡p(x)+log⁡p(y∣x)\log p(\vb{x}) + \log p(\vb{y} \given \vb{x}), equal to log⁡p(x∣y)\log p(\vb{x} \given \vb{y}) plus a constant:

−12(x−m)⊤P−1(x−m)−12(y−b−Hx)⊤R−1(y−b−Hx)=−12x⊤(P−1+H⊤R−1H)x+x⊤(P−1m+H⊤R−1(y−b))+cte.-\tfrac{1}{2}(\vb{x} - \vb{m})\T\mat{P}\inv(\vb{x} - \vb{m}) - \tfrac{1}{2}(\vb{y} - \vb{b} - \mat{H}\vb{x})\T\mat{R}\inv(\vb{y} - \vb{b} - \mat{H}\vb{x}) = -\tfrac{1}{2}\vb{x}\T\big(\mat{P}\inv + \mat{H}\T\mat{R}\inv\mat{H}\big)\vb{x} + \vb{x}\T\big(\mat{P}\inv\vb{m} + \mat{H}\T\mat{R}\inv(\vb{y} - \vb{b})\big) + \text{cte}.

The exponent-reading lemma finishes. That (3) and (4) describe the same Gaussian, read in covariance, is the Woodbury identity: (P−1+H⊤R−1H)−1=P−PH⊤(R+HPH⊤)−1HP(\mat{P}\inv + \mat{H}\T\mat{R}\inv\mat{H})\inv = \mat{P} - \mat{P}\mat{H}\T(\mat{R} + \mat{H}\mat{P}\mat{H}\T)\inv\mat{H}\mat{P}.

∎

Names come from Kalman filtering. y−Hm−b\vb{y} - \mat{H}\vb{m} - \vb{b} is innovation (observation surprise), S\mat{S} its covariance, and K\mat{K} the Kalman gain, translating surprise in observation space into correction in state space. If the sensor is very noisy (large R\mat{R}), K≈0\mat{K} \approx \mat{0} and observation barely matters; if precise, KH\mat{K}\mat{H} approaches a projector and posterior hugs the observation in directions seen by H\mat{H}.

The forms have different costs. Moment form solves a k×kk \times k system (observation size), information form an n×nn \times n one (state size). A Gaussian process with 50 observations and a million prediction points uses the former. Bayesian linear regression with 20 coefficients and a million observations uses the latter: H⊤R−1H\mat{H}\T\mat{R}\inv\mat{H} is a 20×2020 \times 20 matrix accumulated one datum at a time. Marginal (2), evaluated at observed y\vb{y}, is evidence log⁡p(y)\log p(\vb{y}), useful for hyperparameter choice as seen in the interpolation cell.

The model contains the motivation’s three algorithms and one more:

  • Bayesian linear regression. x=w\vb{x} = \vb{w} are coefficients, H\mat{H} the design matrix and R=σ2I\mat{R} = \sigma^2\mat{I}. With m=0\vb{m} = \vb{0} and P=τ2I\mat{P} = \tau^2\mat{I}, posterior mean solves ridge regression with λ=σ2/τ2\lambda = \sigma^2/\tau^2.
  • Kalman. Predicted state is N(m,P)\Normal(\vb{m}, \mat{P}) and measurement linear. Each filter step is an affine transformation (prediction) followed by this theorem (update).
  • Gaussian process regression. x\vb{x} is a vector of function values on a grid, prior N(0,K)\Normal(\vb{0}, \mat{K}); H\mat{H} selects observed coordinates and R=σ2I\mat{R} = \sigma^2\mat{I} is measurement noise.
  • Diffusion. In the DDPM noising process, xt−1∣x0∼N(αˉt−1 x0,(1−αˉt−1)I)\vb{x}_{t-1} \given \vb{x}_0 \sim \Normal(\sqrt{\bar\alpha_{t-1}}\,\vb{x}_0, (1 - \bar\alpha_{t-1})\mat{I}) is the prior and xt∣xt−1∼N(αt xt−1,βtI)\vb{x}_t \given \vb{x}_{t-1} \sim \Normal(\sqrt{\alpha_t}\,\vb{x}_{t-1}, \beta_t\mat{I}) the observation (by the Markov property, this law is unchanged by also conditioning on x0\vb{x}_0), with βt=1−αt\beta_t = 1 - \alpha_t and αˉt=∏s≤tαs\bar\alpha_t = \prod_{s \le t}\alpha_s. Information form gives precision 11−αˉt−1+αtβt=1−αˉtβt(1−αˉt−1)\frac{1}{1 - \bar\alpha_{t-1}} + \frac{\alpha_t}{\beta_t} = \frac{1 - \bar\alpha_t}{\beta_t(1 - \bar\alpha_{t-1})}, so
q(xt−1∣xt,x0)=N(αˉt−1 βt1−αˉtx0+αt (1−αˉt−1)1−αˉtxt,    1−αˉt−11−αˉtβt I),q(\vb{x}_{t-1} \given \vb{x}_t, \vb{x}_0) = \Normal\Big(\tfrac{\sqrt{\bar\alpha_{t-1}}\,\beta_t}{1 - \bar\alpha_t}\vb{x}_0 + \tfrac{\sqrt{\alpha_t}\,(1 - \bar\alpha_{t-1})}{1 - \bar\alpha_t}\vb{x}_t,\;\; \tfrac{1 - \bar\alpha_{t-1}}{1 - \bar\alpha_t}\beta_t\,\mat{I}\Big),

This is the formula in the DDPM paper. The identity βt+αt(1−αˉt−1)=1−αˉt\beta_t + \alpha_t(1 - \bar\alpha_{t-1}) = 1 - \bar\alpha_t is all the algebra needed.

Gaussian process regression deserves an interactive. A Gaussian vector of 50 coordinates, f=(f(x1),…,f(x50))\vb{f} = (f(x_1), \dots, f(x_{50})), with covariance Kij=exp⁡ ⁣(−(xi−xj)2/(2ℓ2))K_{ij} = \exp\!\big(-(x_i - x_j)^2/(2\ell^2)\big), is a smooth random function on a grid. Observing some coordinates with noise gives a linear Gaussian model in which H\mat{H} selects rows of the identity, and the posterior is Gaussian process regression.

InteractiveConditioning a Gaussian over functions
Conditional mean, ±2σ\pm 2\sigma band and samples of f∣\vb{f} \given data
  • conditional mean
  • ±2σ band
  • posterior samples
  • prior ±2 band
1.20
0.05
Gaussian dimension50
Observed coordinates3
Mean posterior standard deviation0.561
Maximum posterior standard deviation0.992
Evidence log⁡p(y)\log p(\vb{y})−4.33
A Gaussian in R50\R^{50} drawn as a function: each coordinate is the value at a grid point in [0,10][0, 10]. Click the chart to observe the nearest coordinate and drag the points vertically. The blue curve is the conditional mean and the band, ±2\pm 2 conditional standard deviations; the thin curves are posterior samples which, with Animate, trace great circles μ+L(εacos⁡φ+εbsin⁡φ)\vb{\mu} + \mat{L}(\vb{\eps}_a\cos\varphi + \vb{\eps}_b\sin\varphi) without changing distribution. Covariance matrix shows the entire Σa∣b\mat{\Sigma}_{a \given b}. The evidence is log⁡p(y)\log p(\vb{y}) from the model's marginal.

What you should have seen:

  • Interpolation with uncertainty. With little noise, the mean passes close to the points and the band narrows around them; far from the data, it returns to the prior’s ±2\pm 2 band. Delete all observations: what remains is the prior, with samples that are arbitrary smooth functions.
  • The band depends only on where you measure. Drag a point up and down: the mean follows it, but the band and covariance matrix stay fixed. This illustrates the section “Conditional covariance does not depend on the data.”
  • The scale ℓ\ell is the reach of information. With ℓ=0.3\ell = 0.3, each observation informs only a tiny neighborhood and the band opens up between data points; with ℓ=3\ell = 3, three points determine nearly the entire function. Change ℓ\ell and look at the evidence: values of ℓ\ell that poorly explain the data have much lower log⁡p(y)\log p(\vb{y}).
  • Conditioning empties rows of the covariance matrix. The row and column of each observed point almost vanish (entirely with zero noise), and covariance between points on opposite sides of an observation decreases: the data “disconnect” them.

Product of Gaussian densities and sensor fusion

Information form yields an identity that appears everywhere, from sensor fusion to message passing in graphical models.

Proof

Consider the linear Gaussian model x∼N(a,A)\vb{x} \sim \Normal(\vb{a}, \mat{A}), y∣x∼N(x,B)\vb{y} \given \vb{x} \sim \Normal(\vb{x}, \mat{B}), and evaluate p(x) p(y∣x)=p(y) p(x∣y)p(\vb{x})\,p(\vb{y} \given \vb{x}) = p(\vb{y})\,p(\vb{x} \given \vb{y}) at y=b\vb{y} = \vb{b}. On the left, N(x;a,A) N(b;x,B)\Normal(\vb{x}; \vb{a}, \mat{A})\,\Normal(\vb{b}; \vb{x}, \mat{B}), and N(b;x,B)=N(x;b,B)\Normal(\vb{b}; \vb{x}, \mat{B}) = \Normal(\vb{x}; \vb{b}, \mat{B}) because the density depends on b−x\vb{b} - \vb{x} only through a quadratic form. On the right, the theorem with H=I\mat{H} = \mat{I} gives p(b)=N(b;a,A+B)p(\vb{b}) = \Normal(\vb{b}; \vb{a}, \mat{A} + \mat{B}) and, in information form, x∣b∼N(c,C)\vb{x} \given \vb{b} \sim \Normal(\vb{c}, \mat{C}).

∎

In words: precisions add and means are averaged with weights equal to their precisions. The constant N(a;b,A+B)\Normal(\vb{a}; \vb{b}, \mat{A} + \mat{B}) measures the compatibility of the two sources: if their means are far apart in the metric of A+B\mat{A} + \mat{B}, the product is tiny, and a sensible filter suspects an outlier. In one dimension, a belief N(10,4)\Normal(10, 4) and a measurement 1313 with variance 11 fuse into N(12.4,0.8)\Normal(12.4, 0.8); the mean falls four times closer to the measurement because it is four times as precise.

With several independent linear sensors yk=hk⊤x+vky_k = \vb{h}_k\T\vb{x} + v_k, vk∼N(0,σk2)v_k \sim \Normal(0, \sigma_k^2), the prior and likelihoods multiply: posterior precision is P−1+∑khkhk⊤/σk2\mat{P}\inv + \sum_k \vb{h}_k\vb{h}_k\T/\sigma_k^2. Since addition is commutative and associative, processing the sensors one at a time, using each posterior as the next prior, gives the same result as processing them all together. This follows from conditional independence of the measurements given x\vb{x}: p(x∣y1,y2)∝p(x∣y1) p(y2∣x)p(\vb{x} \given y_1, y_2) \propto p(\vb{x} \given y_1)\,p(y_2 \given \vb{x}).

InteractiveSensor fusion
S1S2S3
  • prior (radii 1 and 2)
  • ±2σ band of each measurement
  • posterior
Measurements: y1=1.27y_1 = 1.27.
Prior
Ppost=[0.080.000.001.20]\mat{P}_{\text{post}} = \begin{bmatrix} 0.08 & 0.00 \\ 0.00 & 1.20 \end{bmatrix}
Var⁡(x1)\Var(x_1)1.20 → 0.084
Var⁡(x2)\Var(x_2)1.20 → 1.200
Posterior / prior area0.264
∑khkhkT/σk2=[11.110.000.000.00]\textstyle\sum_k \vb{h}_k\vb{h}_k^{\mathsf{T}}/\sigma_k^2 = \begin{bmatrix} 11.11 & 0.00 \\ 0.00 & 0.00 \end{bmatrix}
Sequential − joint, max ∣Δ∣|\Delta|00
The dashed gray ellipse is the prior N(m,P)\Normal(\vb{m}, \mat{P}) (Mahalanobis radii 1 and 2), and the point from which the arrows start is the true position. Each sensor measures projection hk⊤x\vb{h}_k\T\vb{x} with noise; its likelihood is the colored strip (centered on the measurement, width ±2σk\pm 2\sigma_k). Drag each arrow tip to change direction hk\vb{h}_k and noise (2σk2\sigma_k is its length). The magenta ellipse is the posterior. Sequential steps draws intermediate posteriors, and the final reading compares sequential (moment form) and joint (information form) updates.

What you should have seen:

  • An x1x_1 sensor with a round prior only informs x1x_1. In the initial scenario, Var⁡(x1)\Var(x_1) goes from 1.21.2 to 0.0840.084 while Var⁡(x2)\Var(x_2) stays at 1.21.2: the ellipse flattens horizontally.
  • With a correlated prior, the same sensor also informs x2x_2. Switch to Correlated: Var⁡(x2)\Var(x_2) now falls from 11 to 0.4910.491 without anyone measuring it, because the prior says x2x_2 moves with x1x_1. In precision, however, the sensor changes only one entry: ∑khkhk⊤/σk2\sum_k \vb{h}_k\vb{h}_k\T/\sigma_k^2 is zero except at (1,1)(1, 1). Information enters in one direction; covariance distributes it.
  • Two nearly parallel sensors leave an elongated ellipse. With h1\vb{h}_1 and h2\vb{h}_2 at 17°17°, the posterior is very narrow in the direction both measure and barely improves in the perpendicular direction: triangulation is poor at small angles, and ∑khkhk⊤/σk2\sum_k\vb{h}_k\vb{h}_k\T/\sigma_k^2 is ill-conditioned.
  • Sequential and joint updates agree. The difference between them is on the order of 10−1610^{-16}, the rounding error of float64, for any order and any number of sensors.

Stein’s lemma: integration by parts against a Gaussian

The final tool remains. The standard normal density φ(z)=(2π)−1/2e−z2/2\varphi(z) = (2\pi)^{-1/2}e^{-z^2/2} satisfies φ′(z)=−z φ(z)\varphi'(z) = -z\,\varphi(z), and that differential equation turns multiplication by zz into differentiation. It underlies Stein’s method, Gaussian expectation gradient estimators, and the formula connecting denoising to the score in diffusion.

Proof

One dimension. Since ∫z∞tφ(t) ⁣dt=φ(z)\int_z^\infty t\varphi(t)\dd t = \varphi(z) and ∫−∞z−tφ(t) ⁣dt=φ(z)\int_{-\infty}^z -t\varphi(t)\dd t = \varphi(z), write

E[f′(Z)]=∫0∞f′(z)∫z∞tφ(t) ⁣dt ⁣dz−∫−∞0f′(z)∫−∞ztφ(t) ⁣dt ⁣dz.\E[f'(Z)] = \int_0^\infty f'(z)\int_z^\infty t\varphi(t)\dd t\dd z - \int_{-\infty}^0 f'(z)\int_{-\infty}^z t\varphi(t)\dd t\dd z.

The integrand is absolutely integrable over the relevant region (its absolute integral is E∣f′(Z)∣<∞\E\abs{f'(Z)} < \infty), so Fubini’s theorem allows us to exchange the order: the first term is ∫0∞tφ(t)∫0tf′(z) ⁣dz ⁣dt=∫0∞tφ(t)(f(t)−f(0)) ⁣dt\int_0^\infty t\varphi(t)\int_0^t f'(z)\dd z\dd t = \int_0^\infty t\varphi(t)(f(t) - f(0))\dd t, and the second is likewise −∫−∞0tφ(t)(f(0)−f(t)) ⁣dt-\int_{-\infty}^0 t\varphi(t)(f(0) - f(t))\dd t. Adding, E[f′(Z)]=E[Zf(Z)]−f(0)E[Z]=E[Zf(Z)]\E[f'(Z)] = \E[Zf(Z)] - f(0)\E[Z] = \E[Zf(Z)]. No assumption about the behavior of ff at infinity is needed: E∣f′(Z)∣<∞\E\abs{f'(Z)} < \infty suffices.

Standard Gaussian in Rd\R^d. For Z∼N(0,I)\vb{Z} \sim \Normal(\vb{0}, \mat{I}) and coordinate ii, condition on the other coordinates (Fubini again) and apply the one-dimensional case to zi↦f(z)z_i \mapsto f(\vb{z}): E[Zif(Z)]=E[∂if(Z)]\E[Z_i f(\vb{Z})] = \E[\partial_i f(\vb{Z})], that is, E[Zf(Z)]=E[∇f(Z)]\E[\vb{Z} f(\vb{Z})] = \E[\grad f(\vb{Z})].

General case. Write X=μ+LZ\vb{X} = \vb{\mu} + \mat{L}\vb{Z} with LL⊤=Σ\mat{L}\mat{L}\T = \mat{\Sigma} and g(z)=f(μ+Lz)g(\vb{z}) = f(\vb{\mu} + \mat{L}\vb{z}), whose gradient is ∇g(z)=L⊤∇f(μ+Lz)\grad g(\vb{z}) = \mat{L}\T\grad f(\vb{\mu} + \mat{L}\vb{z}). Then E[(X−μ)f(X)]=L E[Zg(Z)]=L E[∇g(Z)]=LL⊤E[∇f(X)]=Σ E[∇f(X)]\E[(\vb{X} - \vb{\mu})f(\vb{X})] = \mat{L}\,\E[\vb{Z}g(\vb{Z})] = \mat{L}\,\E[\grad g(\vb{Z})] = \mat{L}\mat{L}\T\E[\grad f(\vb{X})] = \mat{\Sigma}\,\E[\grad f(\vb{X})].

∎

The lemma characterizes the normal distribution: if a variable ZZ with E∣Z∣<∞\E\abs{Z} < \infty satisfies E[Zf(Z)]=E[f′(Z)]\E[Zf(Z)] = \E[f'(Z)] for every bounded C1C^1 function ff with bounded derivative, then Z∼N(0,1)Z \sim \Normal(0, 1). Take f(z)=eitzf(z) = e^{itz} (its real and imaginary parts): the identity reads −i φZ′(t)=it φZ(t)-i\,\varphi_Z'(t) = it\,\varphi_Z(t) for the characteristic function, that is, φZ′=−tφZ\varphi_Z' = -t\varphi_Z with φZ(0)=1\varphi_Z(0) = 1, whose unique solution is e−t2/2e^{-t^2/2}. Measuring the failure of Stein’s identity measures how far a law is from normal; this is the origin of Stein’s method for quantitative limit theorems and Stein discrepancies used to evaluate samplers.

Three consequences you will use:

  1. Gradients of Gaussian expectations. Differentiating under the integral, ∇μE[f(X)]=E[∇f(X)]\grad_{\vb{\mu}}\E[f(\vb{X})] = \E[\grad f(\vb{X})] (the reparameterization estimator) and also ∇μE[f(X)]=E[f(X) Σ−1(X−μ)]\grad_{\vb{\mu}}\E[f(\vb{X})] = \E[f(\vb{X})\,\mat{\Sigma}\inv(\vb{X} - \vb{\mu})] (the score function estimator, since ∇μlog⁡p=Σ−1(x−μ)\grad_{\vb{\mu}}\log p = \mat{\Sigma}\inv(\vb{x} - \vb{\mu})). Stein’s lemma says they are equal in expectation; their variance distinguishes them, as you saw in the PyTorch cell of the previous lesson. Applying the lemma twice also gives ∇ΣE[f(X)]=12E[∇2f(X)]\grad_{\mat{\Sigma}}\E[f(\vb{X})] = \tfrac{1}{2}\E[\hess f(\vb{X})] (Price’s theorem), used in Gaussian variational inference.
  2. Estimating risk without knowing the truth (SURE). If Y∼N(θ,σ2Ip)\vb{Y} \sim \Normal(\vb{\theta}, \sigma^2\mat{I}_p) and you estimate θ\vb{\theta} with θ^=Y+g(Y)\hat{\vb{\theta}} = \vb{Y} + \vb{g}(\vb{Y}), expanding the square and applying Stein to each cross term, E[(Yi−θi)gi(Y)]=σ2E[∂igi(Y)]\E[(Y_i - \theta_i)g_i(\vb{Y})] = \sigma^2\E[\partial_i g_i(\vb{Y})], gives E∥θ^−θ∥2=pσ2+E[∥g(Y)∥2+2σ2 ∇⋅g(Y)].\E\norm{\hat{\vb{\theta}} - \vb{\theta}}^2 = p\sigma^2 + \E\big[\norm{\vb{g}(\vb{Y})}^2 + 2\sigma^2\,\grad\cdot\vb{g}(\vb{Y})\big]. The right-hand side does not contain θ\vb{\theta}: the expression inside the expectation is an unbiased risk estimator computable from the data. This is the result from Stein’s 1981 paper. For the James–Stein estimator, g(y)=−(p−2)σ2y/∥y∥2\vb{g}(\vb{y}) = -(p - 2)\sigma^2\vb{y}/\norm{\vb{y}}^2, it gives risk pσ2−(p−2)2σ4 E[1/∥Y∥2]<pσ2p\sigma^2 - (p - 2)^2\sigma^4\,\E[1/\norm{\vb{Y}}^2] < p\sigma^2 if p≥3p \ge 3: shrinking toward the origin improves on maximum likelihood for every θ\vb{\theta}.
  3. Tweedie’s formula. If Y=X+σZ\vb{Y} = \vb{X} + \sigma\vb{Z} with Z∼N(0,I)\vb{Z} \sim \Normal(\vb{0}, \mat{I}) independent of X\vb{X} (of arbitrary law), then E[X∣Y=y]=y+σ2∇log⁡pY(y)\E[\vb{X} \given \vb{Y} = \vb{y}] = \vb{y} + \sigma^2\grad\log p_{\vb{Y}}(\vb{y}). It follows from the same identity ∇φσ(u)=−u φσ(u)/σ2\grad\varphi_\sigma(\vb{u}) = -\vb{u}\,\varphi_\sigma(\vb{u})/\sigma^2: differentiating pY(y)=E[φσ(y−X)]p_{\vb{Y}}(\vb{y}) = \E[\varphi_\sigma(\vb{y} - \vb{X})] under the expectation gives σ2∇pY(y)=E[(X−y)φσ(y−X)]\sigma^2\grad p_{\vb{Y}}(\vb{y}) = \E[(\vb{X} - \vb{y})\varphi_\sigma(\vb{y} - \vb{X})], and dividing by pY(y)p_{\vb{Y}}(\vb{y}) amounts to conditioning. Optimal denoising is equivalent to knowing the score ∇log⁡pY\grad\log p_{\vb{Y}}: this idea makes score-based diffusion models work.

Implementation from scratch

We build a linear Gaussian engine with five functions: marginalization and conditioning in moment form, the same operations in information form, and the linear Gaussian model update with its evidence. Neither form explicitly constructs an unnecessary inverse: everything uses Cholesky factorizations and triangular solves, as in the previous lesson.

[ ]Linear Gaussian engine: moments, information and linear modelBrowser
import numpy as np
from scipy.linalg import cho_factor, cho_solve

def _sym(A):
    return (A + A.T) / 2

def marginalize(mu, S, a):
    """Ley de X_a en forma de momentos: seleccionar sub-bloques."""
    a = np.asarray(a)
    return mu[a], S[np.ix_(a, a)]

def condition(mu, S, a, b, xb):
    """Ley de X_a | X_b = xb en forma de momentos: complemento de Schur, sin invertir S_bb."""
    a, b = np.asarray(a), np.asarray(b)
    c = cho_factor(S[np.ix_(b, b)], lower=True)
    G = cho_solve(c, S[np.ix_(b, a)]).T                  # G = S_ab S_bb⁻¹
    return mu[a] + G @ (xb - mu[b]), _sym(S[np.ix_(a, a)] - G @ S[np.ix_(b, a)])

def to_info(mu, S):
    c = cho_factor(S, lower=True)
    return cho_solve(c, mu), cho_solve(c, np.eye(len(mu)))   # h = Λμ, Λ = Σ⁻¹

def from_info(h, Lam):
    c = cho_factor(Lam, lower=True)
    return cho_solve(c, h), cho_solve(c, np.eye(len(h)))

def condition_info(h, Lam, a, b, xb):
    """En forma de información, condicionar es seleccionar: (h_a − Λ_ab x_b, Λ_aa)."""
    a, b = np.asarray(a), np.asarray(b)
    return h[a] - Lam[np.ix_(a, b)] @ xb, Lam[np.ix_(a, a)]

def marginalize_info(h, Lam, a, b):
    """En forma de información, marginalizar exige el complemento de Schur de Λ_bb."""
    a, b = np.asarray(a), np.asarray(b)
    c = cho_factor(Lam[np.ix_(b, b)], lower=True)
    G = cho_solve(c, Lam[np.ix_(b, a)]).T                # Λ_ab Λ_bb⁻¹
    return h[a] - G @ h[b], _sym(Lam[np.ix_(a, a)] - G @ Lam[np.ix_(b, a)])

def linear_gaussian_update(m, P, H, R, y, b=None):
    """x ~ N(m, P), y | x ~ N(Hx + b, R). Devuelve media y covarianza posteriores y log p(y)."""
    b = np.zeros(len(y)) if b is None else b
    r = y - H @ m - b                                    # innovación
    S = H @ P @ H.T + R                                  # covarianza de la marginal de y
    c = cho_factor(S, lower=True)
    K = cho_solve(c, H @ P).T                            # ganancia K = P Hᵀ S⁻¹
    A = np.eye(len(m)) - K @ H
    P_post = _sym(A @ P @ A.T + K @ R @ K.T)             # forma de Joseph (ver más abajo)
    logev = -0.5 * (r @ cho_solve(c, r) + 2 * np.log(np.diag(c[0])).sum() + len(y) * np.log(2 * np.pi))
    return m + K @ r, P_post, logev

rng = np.random.default_rng(0)
d = 5
A = rng.standard_normal((d, d))
S = A @ A.T + 0.5 * np.eye(d)
mu = rng.standard_normal(d)
a, b, xb = [0, 1, 2], [3, 4], np.array([1.0, -0.5])

m1, C1 = condition(mu, S, a, b, xb)
h, Lam = to_info(mu, S)
m2, C2 = from_info(*condition_info(h, Lam, a, b, xb))
print("condicionar, momentos frente a información: máx |Δμ| =", np.abs(m1 - m2).max(), " máx |ΔΣ| =", np.abs(C1 - C2).max())
m3, C3 = from_info(*marginalize_info(h, Lam, a, b))
print("marginalizar, sub-bloque frente a Schur de Λ: máx |Δμ| =", np.abs(m3 - mu[a]).max(), " máx |ΔΣ| =", np.abs(C3 - S[np.ix_(a, a)]).max())
print("autovalores de Σ_aa − Σ_{a|b} (≥ 0):", np.linalg.eigvalsh(S[np.ix_(a, a)] - C1).round(4) + 0.0)

The two forms agree up to rounding, and the eigenvalues of Σaa−Σa∣b\mat{\Sigma}_{aa} - \mat{\Sigma}_{a \given b} are nonnegative: conditioning cannot increase the variance of any linear combination (one eigenvalue is zero because Xb\vb{X}_b has two coordinates and Xa\vb{X}_a three, so the explained part has rank 2). Now an independent check: conditioning by rejection, keeping samples close to the observed value.

[ ]Monte Carlo verification: conditioning by rejectionBrowser
rng = np.random.default_rng(12)
n = 400_000
X = mu + rng.standard_normal((n, d)) @ np.linalg.cholesky(S).T
x5, delta = 0.7, 0.03
sel = np.abs(X[:, 4] - x5) < delta                       # entorno pequeño de {X_5 = 0.7}
mc, Cc = condition(mu, S, [0, 1, 2, 3], [4], np.array([x5]))
print(f"se aceptan {sel.sum()} de {n} muestras")
print("media condicional exacta    :", mc.round(3))
print("media de las aceptadas      :", X[sel, :4].mean(0).round(3))
print("desv. condicionales exactas :", np.sqrt(np.diag(Cc)).round(3))
print("desv. de las aceptadas      :", X[sel, :4].std(0).round(3))
print("desv. marginales            :", np.sqrt(np.diag(S)[:4]).round(3))

G = S[0, 4] / S[4, 4]                                    # ley de la varianza total para X_1 dado X_5
print(f"Σ_11 = {S[0, 0]:.4f} = E[Var(X_1 | X_5)] + Var(E[X_1 | X_5]) = {Cc[0, 0]:.4f} + {G**2 * S[4, 4]:.4f}")

With around five thousand accepted samples, means and standard deviations agree with the formulas within Monte Carlo error (about 1 or 2 % of the standard deviation; other seeds yield fluctuations of that size), and every conditional standard deviation is smaller than its marginal counterpart. Next is the precision structure: the chain, the collider from the warning and fill-in on marginalization.

[ ]Precision zeros: chain, collider and fill-inBrowser
np.set_printoptions(precision=2, suppress=True, linewidth=110)

def clean(M):
    M = M.copy(); M[np.abs(M) < 1e-12] = 0.0
    return M + 0.0                                       # evita imprimir −0.

def partial_corr(Lam):
    dd = np.sqrt(np.diag(Lam))
    P = -Lam / np.outer(dd, dd); np.fill_diagonal(P, 1.0)
    return P

phi, idx = 0.8, np.arange(6)
S_ar = phi ** np.abs(idx[:, None] - idx[None, :]) / (1 - phi**2)     # AR(1) estacionario: una cadena
print("Σ de la cadena (densa):\n", S_ar)
print("Λ = Σ⁻¹ (tridiagonal):\n", clean(np.linalg.inv(S_ar)))
print("corr(X_1, X_3): marginal", round(S_ar[0, 2] / S_ar[0, 0], 3), " parcial", round(partial_corr(np.linalg.inv(S_ar))[0, 2], 12))

S_col = np.array([[1.0, 0.0, 1.0], [0.0, 1.0, 1.0], [1.0, 1.0, 3.0]])  # X_3 = X_1 + X_2 + ruido
print("\ncolisionador: Σ_12 =", S_col[0, 1], "  Λ =", clean(np.linalg.inv(S_col)).tolist(),
      "  corr. parcial (1, 2 | 3) =", round(partial_corr(np.linalg.inv(S_col))[0, 1], 6))

Lam_star = np.eye(6); Lam_star[0, 1:] = Lam_star[1:, 0] = -0.35     # estrella con centro X_1
_, Lc = condition_info(np.zeros(6), Lam_star, range(1, 6), [0], np.array([0.0]))
_, Lm = marginalize_info(np.zeros(6), Lam_star, range(1, 6), [0])
iu = np.triu_indices(5, 1)
print("\nestrella: ceros entre las hojas tras condicionar en el centro:", int((np.abs(Lc[iu]) < 1e-12).sum()), "de 10;",
      "tras marginalizarlo:", int((np.abs(Lm[iu]) < 1e-12).sum()), "de 10")

The partial correlation of X1X_1 and X3X_3 in the chain is 00 to twelve decimal places, although the marginal correlation is 0.640.64. The collider shows the reverse, Σ12=0\Sigma_{12} = 0 with Λ12=1\Lambda_{12} = 1 and partial correlation −0.5-0.5. And the star goes from 10 zeros between leaves to none when the center is integrated out.

Tracking an object

Now for the application. First, three scalar sensors on a fixed position in the plane, processed one by one and all at once. Then an object moving in one dimension at almost constant velocity: prediction is an affine transformation and updating is linear_gaussian_update. Repeating this gives the Kalman filter.

[ ]Sensor fusion and tracking with prediction and updateBrowser
rng = np.random.default_rng(1)
x_true = np.array([2.0, 1.0])
m0, P0 = np.zeros(2), np.array([[4.0, 1.5], [1.5, 2.0]])
Hs = np.array([[1.0, 0.0], [0.6, 0.8], [-0.8, 0.6]])         # tres sensores escalares
rs = np.array([0.5, 0.3, 1.0]) ** 2
ys = Hs @ x_true + np.sqrt(rs) * rng.standard_normal(3)

m_seq, P_seq = m0, P0
for h, r, y in zip(Hs, rs, ys):                                # uno a uno
    m_seq, P_seq, _ = linear_gaussian_update(m_seq, P_seq, h[None, :], np.array([[r]]), np.array([y]))
m_all, P_all, _ = linear_gaussian_update(m0, P0, Hs, np.diag(rs), ys)   # todos a la vez
print("secuencial frente a conjunta: máx |Δm| =", np.abs(m_seq - m_all).max(), " máx |ΔP| =", np.abs(P_seq - P_all).max())
print("Λ_post − Λ_0 =", (np.linalg.inv(P_all) - np.linalg.inv(P0)).round(4).tolist())
print("Σ h hᵀ / r   =", (Hs.T @ np.diag(1 / rs) @ Hs).round(4).tolist())

# objeto en 1D con estado (posición, velocidad)
dt, q, r_pos, T = 1.0, 0.05, 4.0, 60
F = np.array([[1.0, dt], [0.0, 1.0]])
Q = q * np.array([[dt**3 / 3, dt**2 / 2], [dt**2 / 2, dt]])
Hp, Lq = np.array([[1.0, 0.0]]), np.linalg.cholesky(Q)
s, m, P = np.array([0.0, 1.0]), np.zeros(2), np.diag([10.0, 4.0])
err_f, err_z, dentro = [], [], 0
for t in range(T):
    s = F @ s + Lq @ rng.standard_normal(2)                    # el objeto se mueve
    z = Hp @ s + np.sqrt(r_pos) * rng.standard_normal(1)       # medición ruidosa de la posición
    m, P = F @ m, F @ P @ F.T + Q                              # predecir: transformación afín
    m, P, _ = linear_gaussian_update(m, P, Hp, np.array([[r_pos]]), z)   # actualizar: modelo lineal gaussiano
    if t >= 10:                                                # descartamos el arranque
        err_f.append(m[0] - s[0]); err_z.append(z[0] - s[0])
        dentro += abs(m[0] - s[0]) <= 2 * np.sqrt(P[0, 0])
print(f"\nRMSE de la medición cruda: {np.sqrt(np.mean(np.square(err_z))):.2f};  del filtro: {np.sqrt(np.mean(np.square(err_f))):.2f}")
print(f"posición real dentro de ±2σ del filtro: {dentro} de {T - 10} pasos")

The difference between sequential and joint processing is 10−1610^{-16}, the added information is exactly ∑khkhk⊤/rk\sum_k \vb{h}_k\vb{h}_k\T/r_k, and the filter reduces the root mean square error of the raw measurement (about 2 units) to a little over 1, with a ±2σ\pm 2\sigma band containing the true position in 48 of 50 steps. Its reported uncertainty is honest.

The next cell illustrates this with a prior of variance 10810^8 and a sensor of variance 10−810^{-8}; the exact posterior variance is σ2r/(σ2+r)≈10−8\sigma^2 r/(\sigma^2 + r) \approx 10^{-8}.

[ ]Joseph form versus P − KHP in floating pointBrowser
def posterior_var(dtype, sig2=1e8, r=1e-8):
    P = np.array([[sig2, 0.9 * sig2], [0.9 * sig2, sig2]], dtype=dtype)
    H, R = np.array([[1.0, 0.0]], dtype=dtype), np.array([[r]], dtype=dtype)
    K = P @ H.T / (H @ P @ H.T + R)[0, 0]
    A = np.eye(2, dtype=dtype) - K @ H
    return (A @ P)[0, 0], (A @ P @ A.T + K @ R @ K.T)[0, 0]

print("varianza posterior exacta de x_1:", 1e8 * 1e-8 / (1e8 + 1e-8))
for dt_ in (np.float64, np.float32):
    std, jos = posterior_var(dt_)
    print(f"{dt_.__name__}:  P − KHP da {float(std):.3e}   Joseph da {float(jos):.3e}")

In float64, the naive formula is wrong by 11 %; in float32 (the usual precision on GPUs and embedded systems) it returns exactly zero variance, after which the filter believes it knows everything and ignores subsequent measurements. Joseph gets both cases right.

Interpolating a signal: conditioning 60 coordinates

Gaussian process regression applies the engine to a grid. A signal is sampled with noise at 8 of 60 points, and we condition the 60-dimensional Gaussian on them. The evidence log⁡p(y)\log p(\vb{y}) returned by the engine also selects the kernel scale ℓ\ell.

[ ]Interpolating a sampled signal and choosing ℓ by evidenceBrowser
def k_se(x1, x2, ell, amp=1.0):
    return amp * np.exp(-0.5 * ((x1[:, None] - x2[None, :]) / ell) ** 2)

grid = np.linspace(0, 1, 60)
f_true = np.sin(2 * np.pi * 1.3 * grid) + 0.4 * np.cos(2 * np.pi * 3.1 * grid)
obs = np.array([3, 10, 17, 25, 33, 41, 48, 56])
noise = 0.1
y_obs = f_true[obs] + noise * np.random.default_rng(2).standard_normal(len(obs))
H = np.eye(len(grid))[obs]                                     # observar = seleccionar coordenadas
R = noise**2 * np.eye(len(obs))

print("   ℓ     log p(y)   RMSE    cobertura de ±2σ")
for ell in (0.05, 0.08, 0.12, 0.2, 0.3):
    K = k_se(grid, grid, ell) + 1e-8 * np.eye(len(grid))
    mean, cov, logev = linear_gaussian_update(np.zeros(len(grid)), K, H, R, y_obs)
    sd = np.sqrt(np.clip(np.diag(cov), 0, None))
    print(f"  {ell:4.2f}  {logev:8.2f}   {np.sqrt(np.mean((mean - f_true) ** 2)):.3f}   {np.mean(np.abs(mean - f_true) <= 2 * sd):.2f}")

K = k_se(grid, grid, 0.12) + 1e-8 * np.eye(len(grid))
_, cov1, _ = linear_gaussian_update(np.zeros(len(grid)), K, H, R, y_obs)
_, cov2, _ = linear_gaussian_update(np.zeros(len(grid)), K, H, R, y_obs + 5.0)
print("\n¿cambia la covarianza posterior si se suman 5 unidades a todos los datos?", not np.allclose(cov1, cov2))

Evidence is highest at ℓ=0.12\ell = 0.12 (almost tied with 0.080.08), where the ±2σ\pm 2\sigma band contains the true signal on 95 % of the grid, as promised. With ℓ=0.3\ell = 0.3, the model is too rigid: evidence drops by about 30 log units, error doubles and the overconfident band covers only 38 % of the signal. Posterior covariance does not change when the data move.

The diffusion posterior and Stein’s lemma

Two final checks: the DDPM formula is the linear Gaussian model update, and Stein’s lemma and SURE hold by Monte Carlo.

[ ]Diffusion, Stein's lemma and James–Stein risk by SUREBrowser
rng = np.random.default_rng(3)
betas = np.linspace(1e-4, 0.02, 1000); alphas = 1 - betas; abar = np.cumprod(alphas)
t, I3 = 300, np.eye(3)
x0 = rng.standard_normal(3)
xt = np.sqrt(abar[t]) * x0 + np.sqrt(1 - abar[t]) * rng.standard_normal(3)
m_post, P_post, _ = linear_gaussian_update(np.sqrt(abar[t - 1]) * x0, (1 - abar[t - 1]) * I3, np.sqrt(alphas[t]) * I3, betas[t] * I3, xt)
mu_ddpm = (np.sqrt(abar[t - 1]) * betas[t] * x0 + np.sqrt(alphas[t]) * (1 - abar[t - 1]) * xt) / (1 - abar[t])
print("difusión: máx |media − DDPM| =", np.abs(m_post - mu_ddpm).max(), "  varianza:", P_post[0, 0], "frente a", (1 - abar[t - 1]) / (1 - abar[t]) * betas[t])

n = 400_000
S2, mu2 = np.array([[2.0, 0.8], [0.8, 1.0]]), np.array([0.5, -1.0])
X = mu2 + rng.standard_normal((n, 2)) @ np.linalg.cholesky(S2).T
f = lambda x: np.sin(x[:, 0]) * x[:, 1] ** 2
grad_f = lambda x: np.stack([np.cos(x[:, 0]) * x[:, 1] ** 2, 2 * np.sin(x[:, 0]) * x[:, 1]], axis=1)
print("\nStein:  E[(X − μ) f(X)] =", ((X - mu2) * f(X)[:, None]).mean(0).round(3), "   Σ E[∇f(X)] =", (S2 @ grad_f(X).mean(0)).round(3))

p, reps = 50, 4000
theta = np.concatenate([np.full(10, 2.0), np.zeros(40)])
Y = theta + rng.standard_normal((reps, p))                    # σ = 1
nrm2 = (Y ** 2).sum(1)
js = (1 - (p - 2) / nrm2)[:, None] * Y                        # James-Stein
sure = p - (p - 2) ** 2 / nrm2                                # SURE, sin usar θ
print(f"James-Stein: riesgo real {((js - theta) ** 2).sum(1).mean():.2f},  media de SURE {sure.mean():.2f};",
      f" máxima verosimilitud: {((Y - theta) ** 2).sum(1).mean():.2f} (teoría {p})")

The DDPM mean and variance agree with the generic update up to rounding. Both sides of Stein’s lemma agree within Monte Carlo error. And SURE, which does not know θ\vb{\theta}, estimates the risk of the James–Stein estimator (about 24 units, less than half the maximum-likelihood estimator’s 50) with an error of a few tenths.

With libraries

SciPy evaluates densities, so it lets us verify log⁡p(xa,xb)=log⁡p(xb)+log⁡p(xa∣xb)\log p(\vb{x}_a, \vb{x}_b) = \log p(\vb{x}_b) + \log p(\vb{x}_a \given \vb{x}_b) point by point with our marginal and conditional formulas. Scikit-learn provides Gaussian process regression; with fixed hyperparameters (optimizer=None), it should give exactly our mean and standard deviation.

[ ]SciPy and scikit-learn versus our engineBrowser
from scipy import stats
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF

pts = np.random.default_rng(4).standard_normal((6, 5))
lj = stats.multivariate_normal(mu, S).logpdf(pts)
lm = stats.multivariate_normal(*marginalize(mu, S, [3, 4])).logpdf(pts[:, [3, 4]])
lc = np.array([stats.multivariate_normal(*condition(mu, S, [0, 1, 2], [3, 4], q[[3, 4]])).logpdf(q[:3]) for q in pts])
print("máx |log p(x_a, x_b) − log p(x_b) − log p(x_a | x_b)| =", np.abs(lj - lm - lc).max())

ell = 0.12
K = k_se(grid, grid, ell) + 1e-8 * np.eye(len(grid))
mean, cov, _ = linear_gaussian_update(np.zeros(len(grid)), K, H, R, y_obs)
gpr = GaussianProcessRegressor(kernel=RBF(length_scale=ell), alpha=noise**2 + 1e-8, optimizer=None)
gpr.fit(grid[obs, None], y_obs)
mu_sk, sd_sk = gpr.predict(grid[:, None], return_std=True)
print("scikit-learn frente al motor: máx |Δmedia| =", np.abs(mu_sk - mean).max(),
      "  máx |Δσ| =", np.abs(sd_sk - np.sqrt(np.clip(np.diag(cov), 0, None))).max())

The differences are on the order of 10−810^{-8}, the jitter size, which the two implementations place in slightly different locations. Internally, GaussianProcessRegressor does the same as our engine: a Cholesky factorization of KOO+σ2I\mat{K}_{OO} + \sigma^2\mat{I} and two substitutions.

Common mistakes

Exercises

ProofCompleting the square
Prove: Let X=(Xa,Xb)∼N(μ,Σ)\vb{X} = (\vb{X}_a, \vb{X}_b) \sim \Normal(\vb{\mu}, \mat{\Sigma}) with Σ≻0\mat{\Sigma} \succ 0 and Λ=Σ−1\mat{\Lambda} = \mat{\Sigma}\inv partitioned into blocks. Then Xa∣Xb=xb∼N(μa+ΣabΣbb−1(xb−μb),  Σaa−ΣabΣbb−1Σba)\vb{X}_a \given \vb{X}_b = \vb{x}_b \sim \Normal\big(\vb{\mu}_a + \mat{\Sigma}_{ab}\mat{\Sigma}_{bb}\inv(\vb{x}_b - \vb{\mu}_b),\; \mat{\Sigma}_{aa} - \mat{\Sigma}_{ab}\mat{\Sigma}_{bb}\inv\mat{\Sigma}_{ba}\big).
0
Work with the joint density as a function of xa\vb{x}_a, with xb\vb{x}_b fixed. You may use the exponent-reading lemma and block inverse formulas.

Step 1 of 5. Why is it enough to study p(xa,xb)p(\vb{x}_a, \vb{x}_b) as a function of xa\vb{x}_a?

ProofPrecision zeros by factorization
Prove: Let X∼N(μ,Σ)\vb{X} \sim \Normal(\vb{\mu}, \mat{\Sigma}) with Σ≻0\mat{\Sigma} \succ 0 and Λ=Σ−1\mat{\Lambda} = \mat{\Sigma}\inv. For i≠ji \neq j, Λij=0\Lambda_{ij} = 0 if and only if Xi⊥ ⁣ ⁣ ⁣⊥Xj∣X−{i,j}X_i \indep X_j \given \vb{X}_{-\{i,j\}}.
0
Use the factorization criterion: for positive densities, Xi⊥ ⁣ ⁣ ⁣⊥Xj∣XcX_i \indep X_j \given \vb{X}_c (where cc is the rest) if and only if p(xi,xj,xc)=g(xi,xc) k(xj,xc)p(x_i, x_j, \vb{x}_c) = g(x_i, \vb{x}_c)\,k(x_j, \vb{x}_c) for some functions gg and kk.

Step 1 of 4. Write log⁡p(x)\log p(\vb{x}) as a sum of terms. Which is the only one mixing xix_i and xjx_j?

ProofStein's lemma by integration by parts
Prove: Let Z∼N(0,1)Z \sim \Normal(0, 1) and f∈C1(R)f \in C^1(\R) with ∣f(z)∣+∣f′(z)∣≤Cec∣z∣\abs{f(z)} + \abs{f'(z)} \le C e^{c\abs{z}} for some constants C,cC, c. Then E[Zf(Z)]=E[f′(Z)]\E[Zf(Z)] = \E[f'(Z)], and for X∼N(μ,Σ)\vb{X} \sim \Normal(\vb{\mu}, \mat{\Sigma}) we have E[(X−μ)f(X)]=Σ E[∇f(X)]\E[(\vb{X} - \vb{\mu})f(\vb{X})] = \mat{\Sigma}\,\E[\grad f(\vb{X})] (under the analogous assumption in Rd\R^d).
0
Use integration by parts with density φ(z)=(2π)−1/2e−z2/2\varphi(z) = (2\pi)^{-1/2}e^{-z^2/2}.

Step 1 of 4. Which property of φ\varphi is key?

NumericConditional variance
(X,Y)(X, Y) is centered Gaussian with Var⁡(X)=4\Var(X) = 4, Var⁡(Y)=9\Var(Y) = 9 and Corr⁡(X,Y)=0.5\operatorname{Corr}(X, Y) = 0.5. Compute Var⁡(Y∣X)\Var(Y \given X).
NumericConditional prediction
With the same vector as in the previous exercise (Var⁡(X)=4\Var(X) = 4, Var⁡(Y)=9\Var(Y) = 9, Corr⁡(X,Y)=0.5\operatorname{Corr}(X, Y) = 0.5, zero means), compute E[Y∣X=2]\E[Y \given X = 2].
NumericMeasuring x informs y
Position x=(x1,x2)\vb{x} = (x_1, x_2) has prior N(0,[4223])\Normal\left(\vb{0}, \begin{bmatrix} 4 & 2 \\ 2 & 3 \end{bmatrix}\right). A sensor measures only the first coordinate, y=x1+vy = x_1 + v with independent v∼N(0,1)v \sim \Normal(0, 1). What is the posterior variance of x2x_2?
NumericFrom precision to marginal correlation
A Gaussian vector (X1,X2,X3)(X_1, X_2, X_3) has precision Λ=[2−10−12−10−12]\mat{\Lambda} = \begin{bmatrix} 2 & -1 & 0 \\ -1 & 2 & -1 \\ 0 & -1 & 2 \end{bmatrix}. Compute the marginal correlation Corr⁡(X1,X3)\operatorname{Corr}(X_1, X_3).
QuizConditional covariance and experimental design
In a Gaussian model (Xa,Xb)(\vb{X}_a, \vb{X}_b) with known parameters, the covariance of Xa\vb{X}_a given Xb=xb\vb{X}_b = \vb{x}_b does not depend on xb\vb{x}_b. Which statements are correct?

More than one answer may be correct.

QuizOperations in precision and covariance
Let X\vb{X} be Gaussian in R6\R^6 with sparse precision Λ\mat{\Lambda} whose graph is a cycle X1−X2−⋯−X6−X1X_1 - X_2 - \cdots - X_6 - X_1. Which statements are true?

More than one answer may be correct.

CodeLinear Gaussian posterior in two forms
Implement posterior_linear_gaussian(m, P, H, R, y, form) for the model x∼N(m,P)\vb{x} \sim \Normal(\vb{m}, \mat{P}), y∣x∼N(Hx,R)\vb{y} \given \vb{x} \sim \Normal(\mat{H}\vb{x}, \mat{R}). With form='moment' use the Kalman gain and Joseph form; with form='info' use precision P−1+H⊤R−1H\mat{P}\inv + \mat{H}\T\mat{R}\inv\mat{H}. Return the tuple (media, covarianza). Do not use np.linalg.inv: solve systems (for instance with cho_factor and cho_solve). The tests compare the two forms with each other and a case with known solution, and check the covariance is symmetric and positive definite.
import numpy as np
from scipy.linalg import cho_factor, cho_solve

def posterior_linear_gaussian(m, P, H, R, y, form="moment"):
  # m: (n,), P: (n, n), H: (k, n), R: (k, k), y: (k,)
  pass
Shift+Enter to run

Summary

Key idea
Within a Gaussian vector, marginalization selects blocks of (μ,Σ)(\vb{\mu}, \mat{\Sigma}) and conditioning takes a Schur complement: Xa∣xb∼N(μa+ΣabΣbb−1(xb−μb),Σaa−ΣabΣbb−1Σba)\vb{X}_a \given \vb{x}_b \sim \Normal(\vb{\mu}_a + \mat{\Sigma}_{ab}\mat{\Sigma}_{bb}\inv(\vb{x}_b - \vb{\mu}_b), \mat{\Sigma}_{aa} - \mat{\Sigma}_{ab}\mat{\Sigma}_{bb}\inv\mat{\Sigma}_{ba}). In precision the roles reverse, its zeros indicate conditional independences, and the linear Gaussian model, with precisions adding, contains Gaussian processes, Kalman filtering and the diffusion posterior.
  • Marginalization. Xa∼N(μa,Σaa)\vb{X}_a \sim \Normal(\vb{\mu}_a, \mat{\Sigma}_{aa}): project the cloud; no integrals.
  • Conditioning. Slice and renormalize. The mean is affine in the data (the regression line, flatter than the ellipse axis) and covariance is the Schur complement. Two proofs: residual Xa−GXb\vb{X}_a - \mat{G}\vb{X}_b is independent of Xb\vb{X}_b (projection in L2L^2), or complete the square. In the scalar case, σ22(1−ρ2)\sigma_2^2(1 - \rho^2).
  • No dependence on the observed value. Σa∣b\mat{\Sigma}_{a \given b} does not depend on xb\vb{x}_b: measurement locations can be designed without data, Kalman precomputes covariances, and the Gaussian is overconfident about outliers.
  • Information form. Λ=Σ−1\mat{\Lambda} = \mat{\Sigma}\inv, h=Λμ\vb{h} = \mat{\Lambda}\vb{\mu}: conditioning selects and marginalization takes a Schur complement. Λii=1/Var⁡(Xi∣resto)\Lambda_{ii} = 1/\Var(X_i \given \text{resto}).
  • Graph. Λij=0  ⟺  Xi⊥ ⁣ ⁣ ⁣⊥Xj∣resto\Lambda_{ij} = 0 \iff X_i \indep X_j \given \text{resto}; partial correlation −Λij/ΛiiΛjj-\Lambda_{ij}/\sqrt{\Lambda_{ii}\Lambda_{jj}}. Conditioning removes nodes; marginalization connects neighbors (fill-in). Zeros of Σ\mat{\Sigma} indicate marginal independences, a different matter.
  • Linear Gaussian model. y∼N(Hm+b,S)\vb{y} \sim \Normal(\mat{H}\vb{m} + \vb{b}, \mat{S}) and x∣y\vb{x} \given \vb{y} with gain K=PH⊤S−1\mat{K} = \mat{P}\mat{H}\T\mat{S}\inv, or with precision P−1+H⊤R−1H\mat{P}\inv + \mat{H}\T\mat{R}\inv\mat{H} (Woodbury connects them). Update covariance with Joseph form.
  • Product of Gaussians. Precisions add and means are precision-weighted; sequential fusion agrees with joint fusion.
  • Stein. E[(X−μ)f(X)]=ΣE[∇f(X)]\E[(\vb{X} - \vb{\mu})f(\vb{X})] = \mat{\Sigma}\E[\grad f(\vb{X})]: characterizes the normal, equates reparameterization and score gradients in expectation, yields SURE (and James–Stein dominance), and leads to Tweedie’s formula.