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
- 04Multivariate Gaussian distributionAffine transformations of GaussiansGaussian sampling via CholeskyMahalanobis distanceConditional densityConditional expectationConditional expectation as L2 projectionLaw of total varianceConditional independenceUncorrelated jointly Gaussian variables are independent
- 02Block matricesSchur complementSherman-Morrison-Woodbury identity
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 given clean data and its noisy version , 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 is Gaussian, the answer is
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 in into coordinate blocks and with , and write mean and covariance as block matrices:
Nothing requires to contain the first coordinates: any index subset works after permutation. For an arbitrary random vector, the law of requires integrating joint density over . For a Gaussian no integration is needed.
Proof
Let select coordinates of , so . By closure under affine transformations, .
∎Geometrically, marginalization is projection: the cloud is flattened onto the coordinate subspace of , 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 and renormalize what remains to integrate to one: the conditional density . Before formulas, compare the operations in two dimensions.
What you should have seen:
- Conditional mean follows a line. Dragging slides the blue bell’s center along with , the regression line of on . At initial values (, , ), and .
- Conditional width does not depend on . The blue bell shifts without changing shape: variance is for all , versus marginal variance . Conditioning always narrows (or leaves unchanged if ).
- Renormalizing divides by slice mass. The dashed orange curve on the right is the raw slice ; it has conditional shape but area , 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”: passes through vertical ellipse tangencies, 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 is singular.
Proof
Projection proof. Define residual . The pair is an affine transformation of , hence Gaussian. Its cross-covariance is
Within a Gaussian vector, uncorrelated implies independent: . Also and
because the last three terms are , and . Thus , with independent of . For bounded measurable , the freezing lemma (if , then with , proved using Fubini) gives
which says exactly that is the conditional law of at .
∎The proof says more than the claim. Decomposition is the orthogonal projection in of onto functions of . For an arbitrary vector, would only be the best affine prediction; here residual is independent of , not just uncorrelated, so orthogonal to every function of , and best affine prediction is best prediction outright:
The law of total variance reads from the same decomposition. Total covariance divides into the part explained by and what remains:
Since the first term is positive semidefinite, : conditioning never increases uncertainty of any linear combination . In the scalar case with , all reduces to two formulas worth memorizing:
In standardized units, prediction is times observed deviation: a father one standard deviation taller than average has children averaging only 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 , and . Thus for , the density of up to a factor. Both integrate to one, so the factors match.
∎Now write the joint density with precision , partitioned like . As a function of with fixed, the exponent is
and the lemma gives . Block-inverse formulas say and : 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, .
If is singular (e.g. the same coordinate observed twice without noise), the theorem still holds with pseudoinverse in place of inverse for almost every under the law of . In practice a little observation noise is preferable.
Conditional covariance does not depend on the observation
Look again: contains no . 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 and candidate list, without a datum. Mutual information between blocks, , 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 , 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 or the natural pair in its exponent.
Proof
(1) In , terms containing are ; the rest is constant in . The exponent-reading lemma gives the result.
(2) By block inversion, , so marginal precision is that Schur complement, call it . For the vector use in blocks: , the information vector of .
∎The table summarizes duality. The more useful form depends on which operation you perform most:
| Moment form | Information form | |
|---|---|---|
| Marginalize | select sub-blocks | Schur complement of |
| Condition | Schur complement of | select sub-blocks (and correct ) |
| Combine independent sources | complicated | add and |
The precision diagonal also has its own meaning. Apply (1) with and the rest:
Each row of divided by its diagonal is a regression of one variable on all others, with coefficient . If that coefficient is zero, does not help predict once the rest are known. This sounds like conditional independence.
Precision zeros: a Gaussian graph
Proof
Take and the rest. By duality, the law of given is Gaussian with precision , independent of . Its covariance is the inverse, , whose off-diagonal entry vanishes if and only if . Since the conditional law is bivariate Gaussian, uncorrelatedness equals independence, simultaneously for every .
∎The correlation of that conditional law has a name: partial correlation . It is correlation between and after linearly removing all other variables’ effects, and vanishes exactly when the coefficient in the regression of on the rest vanishes (regression with controls).
The theorem turns into a graph: one node per variable and an edge between and when . The Gaussian is an undirected graphical model (Gaussian Markov random field), with missing edges representing conditional independence. Covariance tells a different story: means marginal independence. The matrices are inverses, and a sparse matrix rarely has a sparse inverse.
What you should have seen:
- Chain: tridiagonal precision, dense covariance. In Markov chain , has 10 of 15 possible zeros and none: and have marginal correlation and exactly partial correlation. Even endpoints and correlate (). Dependence propagates along graph paths although each variable talks only to neighbors.
- Conditioning removes only the node. Observe : its row and column disappear from and the rest stays intact. In , the Schur complement instead creates a zero block between and : observing a graph separator makes both halves marginally independent.
- Marginalizing connects neighbors. In the star, integrating center adds 10 fill-in edges: five leaves conditionally independent given center become connected. Integrating a chain endpoint (, 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 penalty by graphical lasso), Gaussian Markov random fields in spatial statistics (millions of variables but few 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 is Gaussian (independent Gaussians), and is its affine transform, so Gaussian. Moments: ; ; . This is (1). Point (2) marginalizes (select block); (3) applies the conditioning theorem with and , positive definite because : and .
For (4), complete the square in in , equal to plus a constant:
The exponent-reading lemma finishes. That (3) and (4) describe the same Gaussian, read in covariance, is the Woodbury identity: .
∎Names come from Kalman filtering. is innovation (observation surprise), its covariance, and the Kalman gain, translating surprise in observation space into correction in state space. If the sensor is very noisy (large ), and observation barely matters; if precise, approaches a projector and posterior hugs the observation in directions seen by .
The forms have different costs. Moment form solves a system (observation size), information form an 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: is a matrix accumulated one datum at a time. Marginal (2), evaluated at observed , is evidence , useful for hyperparameter choice as seen in the interpolation cell.
The model contains the motivation’s three algorithms and one more:
- Bayesian linear regression. are coefficients, the design matrix and . With and , posterior mean solves ridge regression with .
- Kalman. Predicted state is and measurement linear. Each filter step is an affine transformation (prediction) followed by this theorem (update).
- Gaussian process regression. is a vector of function values on a grid, prior ; selects observed coordinates and is measurement noise.
- Diffusion. In the DDPM noising process, is the prior and the observation (by the Markov property, this law is unchanged by also conditioning on ), with and . Information form gives precision , so
This is the formula in the DDPM paper. The identity is all the algebra needed.
Gaussian process regression deserves an interactive. A Gaussian vector of 50 coordinates, , with covariance , is a smooth random function on a grid. Observing some coordinates with noise gives a linear Gaussian model in which selects rows of the identity, and the posterior is Gaussian process regression.
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 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 is the reach of information. With , each observation informs only a tiny neighborhood and the band opens up between data points; with , three points determine nearly the entire function. Change and look at the evidence: values of that poorly explain the data have much lower .
- 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 , , and evaluate at . On the left, , and because the density depends on only through a quadratic form. On the right, the theorem with gives and, in information form, .
∎In words: precisions add and means are averaged with weights equal to their precisions. The constant measures the compatibility of the two sources: if their means are far apart in the metric of , the product is tiny, and a sensible filter suspects an outlier. In one dimension, a belief and a measurement with variance fuse into ; the mean falls four times closer to the measurement because it is four times as precise.
With several independent linear sensors , , the prior and likelihoods multiply: posterior precision is . 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 : .
What you should have seen:
- An sensor with a round prior only informs . In the initial scenario, goes from to while stays at : the ellipse flattens horizontally.
- With a correlated prior, the same sensor also informs . Switch to Correlated: now falls from to without anyone measuring it, because the prior says moves with . In precision, however, the sensor changes only one entry: is zero except at . Information enters in one direction; covariance distributes it.
- Two nearly parallel sensors leave an elongated ellipse. With and at , the posterior is very narrow in the direction both measure and barely improves in the perpendicular direction: triangulation is poor at small angles, and is ill-conditioned.
- Sequential and joint updates agree. The difference between them is on the order of , 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 satisfies , and that differential equation turns multiplication by 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 and , write
The integrand is absolutely integrable over the relevant region (its absolute integral is ), so Fubini’s theorem allows us to exchange the order: the first term is , and the second is likewise . Adding, . No assumption about the behavior of at infinity is needed: suffices.
Standard Gaussian in . For and coordinate , condition on the other coordinates (Fubini again) and apply the one-dimensional case to : , that is, .
General case. Write with and , whose gradient is . Then .
∎The lemma characterizes the normal distribution: if a variable with satisfies for every bounded function with bounded derivative, then . Take (its real and imaginary parts): the identity reads for the characteristic function, that is, with , whose unique solution is . 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:
- Gradients of Gaussian expectations. Differentiating under the integral, (the reparameterization estimator) and also (the score function estimator, since ). 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 (Price’s theorem), used in Gaussian variational inference.
- Estimating risk without knowing the truth (SURE). If and you estimate with , expanding the square and applying Stein to each cross term, , gives The right-hand side does not contain : 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, , it gives risk if : shrinking toward the origin improves on maximum likelihood for every .
- Tweedie’s formula. If with independent of (of arbitrary law), then . It follows from the same identity : differentiating under the expectation gives , and dividing by amounts to conditioning. Optimal denoising is equivalent to knowing the score : 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.
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 are nonnegative: conditioning cannot increase the variance of any linear combination (one eigenvalue is zero because has two coordinates and three, so the explained part has rank 2). Now an independent check: conditioning by rejection, keeping samples close to the observed value.
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.
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 and in the chain is to twelve decimal places, although the marginal correlation is . The collider shows the reverse, with and partial correlation . 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.
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 , the added information is exactly , and the filter reduces the root mean square error of the raw measurement (about 2 units) to a little over 1, with a 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 and a sensor of variance ; the exact posterior variance is .
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 returned by the engine also selects the kernel scale .
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 (almost tied with ), where the band contains the true signal on 95 % of the grid, as promised. With , 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.
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 , 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 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.
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 , the jitter size, which the two implementations place in slightly different locations. Internally, GaussianProcessRegressor does the same as our engine: a Cholesky factorization of and two substitutions.
Common mistakes
Exercises
Step 1 of 5. Why is it enough to study as a function of ?
Step 1 of 4. Write as a sum of terms. Which is the only one mixing and ?
Step 1 of 4. Which property of is key?
More than one answer may be correct.
More than one answer may be correct.
posterior_linear_gaussian(m, P, H, R, y, form) for the model , . With form='moment' use the Kalman gain and Joseph form; with form='info' use precision . 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,)
passSummary
- Marginalization. : 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 is independent of (projection in ), or complete the square. In the scalar case, .
- No dependence on the observed value. does not depend on : measurement locations can be designed without data, Kalman precomputes covariances, and the Gaussian is overconfident about outliers.
- Information form. , : conditioning selects and marginalization takes a Schur complement. .
- Graph. ; partial correlation . Conditioning removes nodes; marginalization connects neighbors (fill-in). Zeros of indicate marginal independences, a different matter.
- Linear Gaussian model. and with gain , or with precision (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. : characterizes the normal, equates reparameterization and score gradients in expectation, yields SURE (and James–Stein dominance), and leads to Tweedie’s formula.