Multivariate Distributions

A robot's position and speed move together: if it went further than planned, it was probably faster. With a correlation of 0.9, learning the position cuts the spread of the speed from 0.50 to 0.22 m/s. Nothing measured the speed.

Drag the correlation, then drag the pink line to read a position. Watch the teal slice of samples and the speed curve on the right. Then we build, piece by piece, ten distributions over vectors, matrices, functions and directions.

You need what a probability is, the bell curve and what a matrix is. We build the rest from zero.

Read one number, learn the other

0.90
3.0 m

Illustrative toy: 1,500 seeded draws from a Gaussian with position spread 2 m and speed spread 0.5 m/s. The warm curve is the exact conditional; the blue bars are the speeds of the teal samples within 0.3 m of the line.

Chapter 0

Two Numbers That Move Together

Keep the pair together, because the two side views throw the link away

A robot drives down a corridor. Its estimate holds two numbers: the position error x and the speed error y. They are not separate. If the robot went further than planned, it probably went faster. One distribution must describe the pair.

That distribution is the joint distribution p(x, y): how likely each pair of values is. Look at one number alone, and you get its marginal distribution p(x): add up the joint over every y. Fix one number and ask about the other, and you get the conditional distribution p(y | x), said "p of y given x".

Shuffle the pairs

Blue dots are 1,000 pairs; the side histograms are the two marginals, with the warm bell curve. Shuffle the pairs: every side view stays the same, but the corner empties. Drag the corner's edge a.

1.0

Illustrative: seeded draws in standard units. The exact shares come from the bivariate Gaussian, integrated numerically.

Two numbers with the same marginals can have different joints. So the joint carries more than its two side views. How do we use it? Divide. Call the joint chance of a pair p(x, y) and the marginal chance of x p(x). Then:

Say it aloud

p of y given x equals p of x and y, over p of x.

p(y | x)
p of y given x the conditional: how likely each y is once you know x.
p(x, y)
p of x and y the joint: how likely this pair is.
p(x)
p of x the marginal of x: the joint added up over every y.
In plain words

Keep only the pairs whose first number is x. Rescale them by p(x) so they add up to 1 again. What is left is p(y | x). The same rule works for events.

With numbers

Standard units, correlation 0.8. Both errors above 1 has chance p(x, y) = 0.0976. The position error above 1 has p(x) = 0.1587. So the speed error is above 1 with chance 0.0976 / 0.1587 = 0.615 once you know the position is. Without that knowledge it is 0.159.

Failure: multiply the marginals.

Symptom: a safety check says both errors exceed one standard deviation in 2.5% of runs. The logs show 9.8%.

Measure: 0.1587 × 0.1587 = 0.0252 assumes the errors are independent. At correlation 0.8 the true corner chance is 0.0976, 3.9 times more.

Fix: model the pair with its joint. Multiply marginals only when you know the numbers are independent.

Each chapter below puts a distribution on one kind of linked object.

  1. Covariance: one number for how two numbers move together.
  2. Gaussian: the bell in many dimensions, its ellipses and the Mahalanobis distance.
  3. Conditioning: read one number, update the rest (the hero's pink line, and the Kalman update).
  4. Sampling and t: make correlated noise with a Cholesky factor, then fatten its tails.
  5. Dirichlet: a distribution over probability vectors, and its unlimited version.
  6. Wishart: a distribution over covariance matrices that learns from data.
  7. LKJ: a prior on correlations alone.
  8. Showcase: a Gaussian over whole functions.
  9. vMF: a bell on the sphere, for directions and embeddings.
  10. The field guide: every formula, link and convention in one place.
Two sensors each fail on 10% of days. Their failures are correlated. What can you say about the chance that both fail on one day?

Chapter 1

Measure How Two Numbers Move Together

Average the products of the deviations, then scale the result to get a correlation

We want one number for "x and y move together". Take each pair and measure how far each value sits from its own mean. If both sit on the same side, their product is positive. If they sit on opposite sides, it is negative. Average the products.

Call the means μX and μY, said "mu-X" and "mu-Y". The average of the products is the covariance:

Say it aloud

Cov of X and Y equals the expected value of X minus mu-X, times Y minus mu-Y.

Cov(X, Y)
cov of X and Y the covariance: positive if they rise together, negative if one rises as the other falls. Its unit is X's unit times Y's unit.
E[ ]
the expected value of the average over many draws. On a sample of n pairs, add the products and divide by n − 1.
μX
mu-X the mean of X.
μY
mu-Y the mean of Y.
In plain words

Subtract mu-X from each X and mu-Y from each Y. Multiply the two deviations of each pair. Average the products. That average is Cov(X, Y).

With numbers

Five pairs: (1, 2), (2, 1), (3, 4), (4, 3), (5, 5). Both means are 3. The products of deviations are 2, 2, 0, 0 and 4. Their sum is 8, and 8 / (5 − 1) = 2.0.

Colour the products

The yellow cross marks the two means. Teal points have a positive product (both above or both below). Grey rings have a negative product. Pick a data set.

Illustrative: seeded data sets of 300 points; the five pairs are the worked example. Sample formulas, dividing by n − 1.

Covariance has awkward units: metres times metres per second. Divide by the two standard deviations σX and σY ("sigma"), the square roots of the variances, and the units cancel. The result is the correlation ρ ("rho"), always between −1 and 1:

ρ = Cov(X, Y) / (σX σY) = 2.0 / (√2.5 × √2.5) = 0.80

With D numbers, put every variance and covariance in one table: the covariance matrix Σ ("capital sigma"). Entry i, j is Cov(Xi, Xj), so the diagonal holds the variances. For the five pairs, Σ = [[2.5, 2.0], [2.0, 2.5]]. It is symmetric. No direction can have negative variance, so Σ is positive semi-definite.

Failure: zero correlation read as "no link".

Symptom: the Bowl data has correlation 0.00, so a filter drops y as unrelated to x. But x sets y.

Measure: correlate y with x2 instead: about 1. Correlation sees straight lines only; up on one side and up on the other cancel.

Fix: plot the scatter. Zero correlation means independence only for a jointly Gaussian pair.

X and Y have covariance 6, σX = 3 and σY = 4. What is their correlation?

Chapter 2

The Bell in Many Dimensions

Measure distance in units of the cloud, and the contours become tilted ellipses

Take two points, both 1.41 from the centre of a cloud with correlation 0.8. One sits along the cloud; one sits across it. The first is ordinary. The second is strange. Straight-line distance cannot tell them apart. We need a distance that knows the shape of the cloud.

Call the point x, the centre μ and the covariance matrix Σ. The Mahalanobis distance Δ ("delta") measures how far x is from μ in units of the cloud's own spread: Δ2 = (x − μ)T Σ−1 (x − μ). The multivariate Gaussian in D dimensions turns that distance into a density:

Say it aloud

p of x equals e to the minus one half delta squared, over two pi to the D over two, times the square root of the determinant of Sigma. Delta squared is x minus mu, transposed, times Sigma inverse, times x minus mu.

p(x)
p of x the density at the point x, a vector of D numbers.
exp(−½ Δ2)
e to the minus one half delta squared the bell: 1 at the centre, falling as the Mahalanobis distance grows.
(2π)D/2
two pi to the D over two part of the constant that makes the total volume 1. D is the number of dimensions.
|Σ|1/2
root of the determinant of Sigma the cloud's volume: a wider cloud spreads the same mass thinner.
Δ2
delta squared the squared Mahalanobis distance. Sigma inverse shrinks steps along the long axis and stretches steps across it.
In plain words

Measure the step from mu to x. Rescale it with Sigma inverse to get delta. Put delta into the bell. Divide by the constant so the whole volume is 1. Points with the same delta have the same density, so the contours are ellipses.

With numbers

Unit variances, correlation 0.8: Sigma inverse is [[2.78, −2.22], [−2.22, 2.78]] and |Σ| = 0.36. The point (1, 1) has Δ = 1.05 and density 0.152. The point (1, −1) has Δ = 3.16 and density 0.0018. Same straight-line distance, 85 times less likely.

Measure in units of the cloud

Warm ellipses are Δ = 1, 2 and 3, with the share of draws inside each. Yellow axes are the eigenvectors, scaled by √λ. Drag the pink point, or pick one below; the grey circle has the same straight-line distance.

1.0
1.0
0.80

Exact formulas. The shares inside each ellipse use the chi-squared law with 2 degrees of freedom: 1 − e−Δ²/2.

Why are the contours tilted? Split Σ into its eigenvectors q (directions that Σ only stretches) and eigenvalues λ ("lambda", how much it stretches each one): Σ = QΛQT. The ellipse's axes point along the eigenvectors, with half-lengths √λ. For correlation 0.8 the eigenvalues are 1.8 and 0.2, so the axes are 1.34 and 0.45 long, at 45°. Principal component analysis reads these axes off data (PCA; Eigenvalues).

Failure: a "2-sigma" gate in two dimensions.

Symptom: a tracker accepts a measurement only if Δ < 2, to keep 95%. It throws away 13.5% of good measurements in 2-D and 26% in 3-D.

Measure: Δ2 of a Gaussian draw is chi-squared with D degrees of freedom. The share inside Δ = 2 is 95.4% in 1-D, 86.5% in 2-D, 73.9% in 3-D.

Fix: gate at the chi-squared quantile: Δ < 2.45 for 95% in 2-D, 2.80 in 3-D. Robots gate data association this way (Uncertainty and Robust Costs).

Two points have the same straight-line distance from the mean of a correlated Gaussian. One lies along the long axis. Which has the larger Mahalanobis distance?

Chapter 3

Read One Number, Update the Other

Slice a Gaussian at a measurement and get a narrower Gaussian: the Kalman update

The robot believes its position is 0 m with spread 2 m, and its speed is 0 m/s with spread 0.5 m/s, correlation 0.9. A sensor reads the position as 3 m, with noise of spread 1 m. What should the robot now believe about both?

The Gaussian has three closed doors. A marginal of a Gaussian is Gaussian: delete the rows and columns you do not want. A linear map Ax + b of a Gaussian is Gaussian, with covariance AΣAT. And a conditional is Gaussian. Split the vector into the part you want, a, and the part you read, b. Split μ and Σ the same way:

Say it aloud

Mu a-given-b equals mu-a, plus Sigma-a-b times Sigma-b-b inverse times x-b minus mu-b. Sigma a-given-b equals Sigma-a-a minus Sigma-a-b, Sigma-b-b inverse, Sigma-b-a.

μa|b
mu a-given-b the new mean of the part a after reading b.
μa, μb
mu-a, mu-b the old means of the two parts.
Σab
Sigma-a-b the covariance between the two parts: the link that carries news from b to a. Σba is its transpose.
Σbb−1
Sigma-b-b inverse one over the spread of what you read: a noisy reading counts less.
xb
x-b the value you read. xb − μb is the surprise.
Σa|b
Sigma a-given-b the new covariance of a. It does not depend on the value read.
Σaa
Sigma-a-a the old covariance of a. The update subtracts from it, so it can only shrink.
In plain words

Take the surprise x-b minus mu-b. Scale it by the link Sigma-a-b over the spread Sigma-b-b, and add it to the old mean mu-a. Then subtract from Sigma-a-a the part of a's spread that b explains.

With numbers

Part a is (position, speed); part b is the reading z, position plus noise. Var(z) = 4 + 1 = 5. Cov with position is 4, with speed 0.9 × 2 × 0.5 = 0.9. The scale is (4/5, 0.9/5) = (0.8, 0.18). Surprise 3: the new means are 2.4 m and 0.54 m/s. New variances 4 − 0.8 × 4 = 0.8 and 0.25 − 0.18 × 0.9 = 0.088, so the spreads drop to 0.89 m and 0.30 m/s.

Read a noisy position

Warm: the belief before the reading. Pink: the reading and its noise band. Purple: the belief after. Drag the reading, its noise and the prior correlation.

3.0 m
1.0 m
0.90

Exact conditioning; the ellipses are Δ = 2. Illustrative robot numbers. The hero is the same update with zero reading noise.

This is the Kalman filter's update step, line for line. The scale is the Kalman gain, and the subtraction shrinks the covariance (The Kalman Filter; Linear Dynamical Systems). The predict step is the linear map: after one second, position gains speed, and the covariance becomes AΣAT = [[6.05, 1.15], [1.15, 0.25]]. Least-squares estimators report the inverse of Σ, the information matrix (Estimation and Least Squares; on rotations, Optimization on Manifolds).

Failure: a filter that understates the reading noise.

Symptom: the filter claims a position spread of 0.31 m, but its errors have spread 0.98 m.

Measure: with true noise 1 m and assumed noise 0.1 m, the 95% posterior ellipse holds the truth in 51.5% of 200,000 seeded runs. With the right noise it holds 95.1%.

Fix: estimate the noise from data, and check coverage before you trust the ellipse.

Two numbers are jointly Gaussian with correlation 0. You read one of them exactly. What happens to the other's distribution?

Chapter 4

Build the Cloud, Then Fatten Its Tails

Turn independent noise into correlated noise with a Cholesky factor, then divide by a random scale

A simulator needs fake sensor errors with the robot's covariance. A random number generator gives independent standard Gaussians z, each with mean 0 and spread 1. How do we bend them into the right cloud?

Find a lower-triangular matrix L with L LT = Σ. This Cholesky factor is a square root of Σ. By the linear-map rule, Lz has covariance L I LT = Σ. Now divide by the square root of a random positive number w. Each draw gets its own spread, so some draws land far out. If w is a chi-squared variable with ν ("nu") degrees of freedom divided by ν, the result is the multivariate Student-t:

Say it aloud

x equals mu plus L times z, over the square root of w.

x
x one draw: a vector of D numbers.
μ
mu the centre of the cloud.
L
L the Cholesky factor: lower triangular, with L LT = Σ.
z
z D independent standard Gaussians.
√w
root w a random scale for this draw. w = 1 gives the Gaussian. w = V/ν, with V chi-squared with ν degrees of freedom, gives the t.
In plain words

Draw D independent numbers z. Multiply by L to give them the links of Sigma. Draw one w and divide by its root, which blows up the draw when w is small. Add mu.

With numbers

Σ = [[4, 0.9], [0.9, 0.25]] gives L = [[2, 0], [0.45, 0.218]]. Take z = (1, −0.5). With w = 1, x = (2.00, 0.45 − 0.11) = (2.00, 0.34). A t draw with w = 0.25 doubles it to (4.00, 0.68).

Divide by a random scale

Every option uses the same 1,000 z draws and the same L. The warm ellipse holds 99.9% of Gaussian draws. Teal points land outside it. Pick ν.

Illustrative seeded draws with the robot's Σ. Points beyond the frame sit on its edge. Exact share outside: (1 + 13.8/ν)−ν/2 in 2-D.

The tails decay as a power of Δ, not as e−Δ²/2. At ν = 3, 7.5% of draws land outside the Gaussian's 99.9% ellipse. As ν grows, w settles at 1 and the t becomes the Gaussian. A t likelihood weighs each point by (ν + D)/(ν + Δ2). At ν = 3, a glitch with Δ = 5 counts 0.18 of a typical point (Robust Estimation; the 1-D t is in Continuous Distributions).

Failure: a covariance built one pair at a time.

Symptom: three correlations from three separate studies: 0.9, 0.9 and 0. np.linalg.cholesky stops with "Matrix is not positive definite".

Measure: its eigenvalues are 2.27, 1 and −0.27. A negative eigenvalue means a direction with negative variance, which no data can have.

Fix: estimate the correlations together, or clip the eigenvalues to a small positive number and rescale. Here that gives 0.73, 0.73 and 0.06.

z has 3 independent standard Gaussian entries. What is the covariance of Lz?

Chapter 5

Split One Unit of Probability

Put a distribution on probability vectors, then let the number of pieces grow without limit

A three-sided die has unknown chances (π1, π2, π3), each at least 0, adding to 1. We need a distribution whose every draw is such a vector: a point in the triangle called the simplex.

The Dirichlet distribution does this. It has one positive number per category, αi ("alpha-i"). Think of αi as a count of pretend rolls that came up i. Call the normalising constant B(α):

Say it aloud

p of pi equals one over B of alpha, times the product over i of pi-i to the alpha-i minus one.

p(π)
p of pi the density at one probability vector π.
1/B(α)
one over B of alpha the constant that makes the total 1, built from Gamma functions.
∏i
the product over i multiply one factor for each of the K categories.
πi
pi-i the chance of category i in this vector.
αi
alpha-i the pretend count for category i. Above 1 pulls draws to the middle; below 1 pushes them to the corners.
In plain words

Raise each chance pi-i to alpha-i minus one, multiply, and divide by B of alpha. Vectors that agree with the pretend counts score high.

With numbers

α = (1, 1, 1): every factor has power 0, so the density is 1/B = Γ(3) = 2 everywhere on the triangle. Now roll 10 times and see counts (4, 3, 3). Add them: the posterior is Dirichlet(5, 4, 4), with mean (5/13, 4/13, 4/13) = (0.385, 0.308, 0.308).

That step is conjugacy: prior and posterior are both Dirichlet, and the update adds counts. The Dirichlet is to a K-sided die what the Beta is to a coin (Continuous; the die's counts are multinomial in Discrete).

Break the stick

K = 3: each blue dot is one draw on the triangle. More categories: each row is one draw, pieces sorted from largest. The knob is the total α, shared evenly by the K categories.

3.0

Illustrative seeded draws. K = 3 uses Dirichlet(α/3, α/3, α/3); "No limit" is stick-breaking with Beta(1, α). Shares come from 2,000 draws.

How many topics does a corpus have? Let K grow without limit. Break a stick of length 1. Snap off a share β1 drawn from Beta(1, α), then the same kind of share of what is left, and so on. This is the Dirichlet process, a distribution over distributions with unlimited categories:

πk = βk × (1 − β1) … (1 − βk−1), βk ~ Beta(1, α) α = 1: the pieces average 0.5, 0.25, 0.125, …; the 2.9 largest cover 90% on average

Its counting view is the Chinese restaurant process. Customer n + 1 joins a table of nk people with chance nk/(n + α), or opens a new one with chance α/(n + α). With tables of 3 and 2 and α = 1, the sixth customer picks them with chances 3/6 and 2/6, or a new one with 1/6. After 100 customers, α = 1 gives 5.2 tables on average.

Failure: small α used as a "weak" prior.

Symptom: a "no opinion" topic prior of Dirichlet(0.1, 0.1, 0.1) makes almost every document one topic.

Measure: 66% of its draws put more than 0.9 on one category. Dirichlet(1, 1, 1) does that 3% of the time.

Fix: αi = 1 is flat. Below 1 is a strong belief in sparse vectors; choose it only on purpose.

Prior Dirichlet(2, 2, 2). You see counts (8, 0, 2). What is the posterior?

Chapter 6

A Distribution Over Covariance Matrices

Add up outer products of draws to get a Wishart, then invert it to get a prior that learns from data

A covariance estimated from 5 points is noisy; from 500 it is close. To say how much you trust one, you need a distribution over covariance matrices.

Draw ν Gaussian vectors zi with covariance V. Add up their D × D outer products ziziT. The sum has the Wishart distribution W(ν, V), with mean νV: the law of a Gaussian scatter matrix. Its inverse has the inverse Wishart IW(ν, Ψ), the standard prior on a Gaussian's covariance. Its mean is Ψ/(ν − D − 1).

Take the mean as known, here 0. Call the prior's settings ν0 and Ψ0 ("psi-zero"), the number of points n, and their scatter matrix S = ∑ xixiT. The update adds data to pretend data, as the Dirichlet did:

Say it aloud

The expected Sigma given the data equals Psi-zero plus S, over nu-zero plus n minus D minus one.

E[Σ | data]
the expected Sigma given the data the posterior mean of the covariance.
Ψ0
psi-zero the prior scale matrix: a pretend scatter matrix.
S
S the data's scatter: the sum of x-i times x-i transpose.
ν0
nu-zero the prior degrees of freedom: roughly its count of pretend points.
n
n the number of data points.
D
D the number of dimensions, here 2.
In plain words

Add the data's scatter S to the pretend scatter Psi-zero, and the n real points to the nu-zero pretend ones. Divide the first sum by the second, less D plus one. With much data this tends to S over n.

With numbers

With made-up numbers: ν0 = 4, Ψ0 = I, and 20 points with S = [[10, 4], [4, 16]]. Then Ψ0 + S = [[11, 4], [4, 17]] and 4 + 20 − 3 = 21, so the mean is [[0.52, 0.19], [0.19, 0.81]]. The raw estimate S/n is [[0.50, 0.20], [0.20, 0.80]].

Learn a covariance

Warm: prior draws. Yellow dashed: the truth. Add points (blue), and the purple posterior draws close in. ν0 sets how firmly the prior holds; its mean stays the identity.

4

Illustrative: seeded data from a true covariance [[1, 0.6], [0.6, 0.8]] with known mean 0. Prior Ψ0 = (ν0 − 3) I. Ellipses show Δ = 1.5; Bartlett draws.

For an unknown mean, the normal-inverse-Wishart prior adds a pretend count κ0 ("kappa-zero"). The mean becomes a weighted average: μn = (κ0μ0 + n x̄)/(κ0 + n). With κ0 = 1, μ0 = 0 and 20 points averaging x̄ = (1.2, 0.8), μn = (1.14, 0.76). A new point then follows a multivariate t with νn − D + 1 degrees of freedom (Murphy 2012, section 4.6). For the precision Σ−1, the conjugate prior is the Wishart itself (Bayesian Estimation).

Failure: a prior whose mean does not exist.

Symptom: you set ν0 = 3 for a 2 × 2 prior and average its draws to check it. The average of Σ11 keeps climbing.

Measure: IW(3, I) after 103, 104, 105 and 106 draws: 2.67, 4.56, 6.45, 8.21. The mean needs ν > D + 1 = 3.

Fix: use ν0 ≥ D + 2. IW(5, I) settles at 0.50.

Prior IW(ν0 = 6, Ψ0) on a 2 × 2 covariance. You add 10 points. What is the posterior's ν?

Chapter 7

Separate the Scale From the Links

Put the prior on the correlation matrix alone, and give each spread its own prior

You model five sensors. You know roughly how noisy each one is. You think their correlations are probably small. The inverse Wishart cannot say both: one ν sets the spreads and the links together.

So split the covariance. Write Σ = diag(σ) R diag(σ): the spreads σ on the outside, a correlation matrix R in the middle. R is symmetric and positive definite with ones on its diagonal. Give each σ its own prior. Give R the LKJ distribution, named after Lewandowski, Kurowicka and Joe (2009), with one knob η ("eta"):

Say it aloud

p of R is proportional to the determinant of R, to the eta minus one.

p(R)
p of R the density at one correlation matrix R.
∝
is proportional to equal up to a constant that makes the total 1.
det(R)
the determinant of R 1 for the identity (no links), near 0 when some correlations are near ±1.
η
eta the shrinkage knob. η = 1 is flat over all correlation matrices; above 1 pulls toward the identity; below 1 favours strong links.
In plain words

Score each correlation matrix by its determinant, raised to eta minus one. Strong links shrink the determinant, so with eta above 1 they score low.

With numbers

Two variables: det(R) = 1 − ρ2. With η = 2 the density is proportional to 1 − ρ2. At ρ = 0.9 that is 0.19; at ρ = 0 it is 1. So ρ = 0.9 is 5.3 times less likely.

Sample correlation matrices

The device samples 3,000 matrices and plots one of their correlations. Blue bars are the samples; teal bars mark |ρ| above 0.5; the warm curve is the exact marginal. Change the size D and η.

1.0

Seeded draws by the vine method of Lewandowski, Kurowicka and Joe. The exact marginal of each correlation is a Beta(η − 1 + D/2, η − 1 + D/2), stretched to −1 to 1.

Stan offers lkj_corr and PyMC offers LKJCorr and LKJCholeskyCov, usually with a half-Cauchy or exponential prior on each σ. Sampling works on the Cholesky factor of R, which is why the libraries offer that form.

Failure: "η = 1 is uninformative" in ten dimensions.

Symptom: with D = 10 and η = 1, a model never finds strong links, though the prior was meant to be flat.

Measure: flat over matrices is not flat over each entry. Each correlation is Beta(5, 5) on −1 to 1: |ρ| > 0.5 has chance 9.8%. With D = 2 it is 50%.

Fix: look at the implied marginal Beta(η − 1 + D/2) before you call a prior weak.

You want the spreads and the correlations to have separate priors. Which choice fits?

Chapter 8

A Gaussian Over Whole Functions

Condition infinitely many linked numbers on a few points and watch the band pinch

You have measured a function at five places. You want its value everywhere else, with an honest spread that grows far from the data. Treat the function's value at every input as one huge Gaussian vector. Values at nearby inputs move together; far ones barely. Then use Chapter 3: condition on what you measured.

That is a Gaussian process. Its kernel k(x, x') gives the covariance between the values at x and x'. The common choice is the squared exponential, k(x, x') = σf2 exp(−(x − x')2/(2ℓ2)). Its lengthscale ℓ ("ell") says how far a correlation reaches. Call the covariance matrix of the n data inputs K, and the values seen y. Call the covariances between a new input x* and the data k*, and the measurement noise σn:

Say it aloud

Mu of x-star equals k-star transpose, times K plus sigma-n squared I, inverse, times y. Sigma squared of x-star equals k of x-star and x-star, minus k-star transpose, times that same inverse, times k-star.

μ(x*)
mu of x-star the posterior mean of the function at the new input x*.
k*
k-star the n covariances between x* and the data inputs: Σab from Chapter 3.
(K + σn2I)−1
K plus sigma-n squared I, inverse one over the spread of the readings: Σbb−1, with noise added to the diagonal.
y
y the n values you measured (prior mean 0).
σ2(x*)
sigma squared of x-star the posterior variance of the function at x*.
k(x*, x*)
k of x-star and x-star the prior variance at x*, σf2.
In plain words

Weigh each measured y by how strongly x-star links to it, after undoing the links among the data. That is the mean. Start from the prior variance and subtract what the data explains. That is the band.

With numbers

One point: y = 1 at x = 1, with ℓ = 1, σf = 1, σn = 0.1. At x* = 2, k* = e−0.5 = 0.607 and K + σn2 = 1.01. So μ = 0.607/1.01 = 0.60 and σ2 = 1 − 0.6072/1.01 = 0.64: a spread of 0.80.

Pin a function down

Tap the plot to add a point. The purple line is the posterior mean and the band is two spreads each side. Toggle draws from the prior (warm) or the posterior (purple). The pink line is the probe.

1.0
0.100
2.0

Exact GP algebra in your browser, σf = 1, prior mean 0. The noisy sine is 15 seeded points of sin(x) plus noise of spread 0.3. The error compares the mean with sin(x) on 301 grid points.

A short ℓ lets the mean fall back to 0 between points, and the band balloons. A long ℓ draws a stiff curve through everything. Far from all data, the band returns to the prior: ±2. Bayesian optimisation picks its next trial where the mean is high or the band is wide (Gaussian Processes).

Failure: zero noise on noisy data.

Symptom: with σn = 0.001, the mean threads every noisy point of the sine and swings out to 13.

Measure: its error against the true sine is 2.74 (root mean square). With σn = 0.3 it is 0.16.

Fix: fit ℓ and σn by maximising the marginal likelihood. On these points that gives ℓ = 1.47 and σn = 0.29, error 0.16.

Far from every data point, what does a GP with prior mean 0 predict?

Chapter 9

A Bell on the Sphere

Score a unit vector by its cosine to a mean direction, and watch high dimensions dilute it

A sentence embedding, normalised to length 1, is a point on a sphere. Similarity is the cosine of the angle between two of them, which for unit vectors is their dot product. A Gaussian puts mass off the sphere, so we need a bell that lives on it.

The von Mises-Fisher (vMF) distribution has a mean direction μ, a unit vector, and a concentration κ ("kappa"). Call the dimension D and the normalising constant CD(κ):

Say it aloud

p of x equals C-D of kappa, times e to the kappa, mu transpose x.

p(x)
p of x the density at the unit vector x on the sphere.
CD(κ)
C-D of kappa the constant that makes the total 1. It uses a Bessel function; you rarely need its value.
κ
kappa the concentration. κ = 0 is uniform on the sphere; large κ is a tight cap around μ.
μTx
mu transpose x the cosine between x and the mean direction, from −1 to 1.
In plain words

Take the cosine between x and mu. Multiply by kappa and exponentiate. Points close to mu score high; points opposite score low. In 2-D this is the von Mises distribution on a circle.

With numbers

In 2-D with κ = 5: at 30° from μ the cosine is 0.866, so the density is e5 × (0.866 − 1) = 0.51 of the peak. 74% of draws fall within 30°, and the average cosine to μ is 0.89.

Concentrate on a direction

Right: the cosine of each draw to μ (blue) against the exact density (warm). The yellow outline is random directions, κ = 0; the dashed line is the mean cosine. In 2-D the circle shows the draws. Raise D, then raise κ.

5.0

1,500 seeded draws of the cosine by Wood's (1994) method; the exact density is proportional to eκt(1 − t2)(D−3)/2.

Why does D matter? A random direction in 384 dimensions has a cosine to μ of 0 ± 0.051. Most of the sphere's area sits near the equator, so κ has to fight it. The mean cosine is a ratio of Bessel functions, ID/2(κ)/ID/2−1(κ). A vMF mixture clusters normalised embeddings by exactly this score (Similarity Metrics; Vector Embeddings; 1-D angles in Continuous).

Failure: a 3-D intuition for κ in 384 dimensions.

Symptom: a cluster fitted with κ = 10 looks tight on paper, but its draws look random.

Measure: at κ = 10 the mean cosine to μ is 0.90 in 3-D and 0.026 in 384-D. A mean cosine of 0.5 needs κ = 256 in 384-D.

Fix: read κ against D. From a mean cosine r, the estimate κ ≈ r(D − r2)/(1 − r2) of Banerjee and others (2005) gives 256 for r = 0.5.

Your data are unit-length embeddings compared by cosine. Which distribution fits them?

Chapter 10

The Field Guide

Match the object to its distribution, and keep the formulas and conventions in one place

Each distribution here puts uncertainty on one kind of object: a vector, a probability vector, a matrix, a function or a direction. Name the object first. Its shape picks the distribution.

DistributionDraws areParametersMeanUse it for
Gaussian N(μ, Σ)vectors in D dimensionsμ, Σμstate estimates, sensor noise, latent codes
Student-t(μ, Σ, ν)vectorsμ, Σ, νμ (ν > 1)data with glitches; predicting a new point
Dirichlet(α)probability vectorsα1..Kαi/∑αtopic shares, a prior on a die
Dirichlet process(α, G0)distributions with unlimited atomsα, base G0G0clustering with an unknown number of clusters
Wishart W(ν, V)positive definite matricesν, VνVscatter matrices; a prior on a precision
Inverse Wishart IW(ν, Ψ)covariance matricesν, ΨΨ/(ν − D − 1)a conjugate prior on Σ
Normal-inverse-Wishart(μ, Σ) pairsμ0, κ0, ν0, Ψ0μ0; Ψ0/(ν0 − D − 1)a conjugate prior when both are unknown
LKJ(η)correlation matricesη, size Dthe identitya prior on links, separate from the spreads
Gaussian process GP(m, k)functionsmean m(x), kernel k(x, x')m(x)regression with honest error bars; Bayesian optimisation
von Mises-Fisher(μ, κ)unit vectorsdirection μ, κdirection μ, length ID/2(κ)/ID/2−1(κ)directions, normalised embeddings

How they connect

Corrections to the old version of this page

The core as code

pythonimport numpy as np
from scipy import stats

Sigma = np.array([[4.0, 0.9], [0.9, 0.25]])       # position (m), speed (m/s), rho = 0.9
L = np.linalg.cholesky(Sigma)                       # [[2, 0], [0.45, 0.218]]
x = L @ np.random.default_rng(0).standard_normal((2, 1000))   # 1,000 correlated draws

def mahalanobis2(x, mu, S):
    d = x - mu
    return d @ np.linalg.solve(S, d)                  # solve, never invert

def condition(mu, S, b_idx, xb):
    """Gaussian conditioning: the Kalman update with zero noise."""
    a = [i for i in range(len(mu)) if i not in b_idx]
    G = S[np.ix_(a, b_idx)] @ np.linalg.inv(S[np.ix_(b_idx, b_idx)])
    return mu[a] + G @ (xb - mu[b_idx]), S[np.ix_(a, a)] - G @ S[np.ix_(b_idx, a)]

condition(np.zeros(2), Sigma, [0], np.array([3.0]))   # speed 0.675 m/s, spread 0.218
stats.chi2.ppf(0.95, df=2) ** 0.5                  # 2.45: the 95% gate in 2-D
np.random.default_rng(1).dirichlet([5, 4, 4])          # one die drawn from the posterior
stats.invwishart(df=24, scale=[[11, 4], [4, 17]]).mean()  # [[0.52, 0.19], [0.19, 0.81]]

def vmf_cosine(D, kappa, n, rng):
    """Wood (1994): draw the cosine to mu of n vMF samples in D dimensions."""
    b = (-2 * kappa + np.sqrt(4 * kappa**2 + (D - 1)**2)) / (D - 1)
    x0 = (1 - b) / (1 + b); c = kappa * x0 + (D - 1) * np.log(1 - x0**2)
    out = []
    while len(out) < n:
        z = rng.beta((D - 1) / 2, (D - 1) / 2)
        w = (1 - (1 + b) * z) / (1 - (1 - b) * z)
        if kappa * w + (D - 1) * np.log(1 - x0 * w) - c >= np.log(rng.uniform()):
            out.append(w)
    return np.array(out)                            # D=384, kappa=100: mean 0.245

Keep going

The takeaway. Linked numbers need a joint. For vectors, the covariance matrix holds the links, and conditioning moves news along them. For other objects, pick the distribution that lives on their shape: the simplex, the cone of covariance matrices, a space of functions, the sphere.

Now press Present or Teach and explain four things from memory. Explain why the point (1, −1) is 85 times less likely than (1, 1) at correlation 0.8. Explain how reading a position cuts the spread of a speed nobody measured. Explain how L z / √w builds both the Gaussian and the t. Explain why a Dirichlet update adds counts. Then go back to the hero, set the correlation to 0 and watch the speed curve refuse to move.

Multivariate Distributions
Next: Bayesian Distributions · Back to Gleams