Course contents 10 / 15

10 / 15 · Nonparametric and Topic Models

Gaussian processes

A prior placed directly on functions: kernels as covariances, the exact regression posterior, hyperparameters chosen by the marginal likelihood, inducing points, and classification by the Laplace approximation and by expectation propagation.

On this page 9

Twelve values of sin⁡x\sin x, with noise of standard deviation 0.10.1, lie between x=−4.5x = -4.5 and x=4.6x = 4.6. Fit them with Bayesian linear regression on nine Gaussian bumps ϕc(x)=e−(x−c)2/2\phi_c(x) = e^{-(x - c)^2/2} centred at c=−4,…,4c = -4, \dots, 4, with the prior w∼N(0,I)w \sim \mathcal N(0, I) on the weights. Near the data the posterior is sharp: the standard deviation of f(0)f(0) is 0.0770.077. At x=10x = 10 it is zero to three decimals. The model is certain that f(10)=0f(10) = 0, though no point lies anywhere near.

The certainty comes from the basis. The prior on the weights makes f(x)=w⊤ϕ(x)f(x) = w^\top \phi(x) random, and any two of its values are jointly Gaussian with

E[f(x)]=0,cov⁡(f(x),f(x′))=E[ϕ(x)⊤ww⊤ϕ(x′)]=ϕ(x)⊤ϕ(x′),\begin{aligned} \mathbb E[f(x)] &= 0, \\ \operatorname{cov}\big(f(x), f(x')\big) &= \mathbb E\big[\phi(x)^\top w w^\top \phi(x')\big] \\ &= \phi(x)^\top \phi(x') , \end{aligned}

because E[ww⊤]=I\mathbb E[w w^\top] = I. The prior variance of f(x)f(x) is ∑cϕc(x)2\sum_c \phi_c(x)^2: 1.771.77 at x=0x = 0, and below 10−1510^{-15} at x=10x = 10, where every bump has died out. The basis decides where the model may be uncertain, before any data arrive. More bumps over a wider range move the problem without removing it.

The covariance is all that the prediction uses. So why not write the covariance down directly and never choose a basis? A model built that way has one coefficient per data point instead of a fixed number of weights: its effective number of parameters grows with the data, which makes it nonparametric, like the Dirichlet process of the next note.

A distribution over functions#

A Gaussian process is a collection of random variables f(x)f(x), one for each input xx, any finite number of which have a joint Gaussian distribution (Rasmussen and Williams, 2006, Definition 2.1). It is specified by a mean function and a covariance function:

f∼GP(m(x),k(x,x′)),m(x)=E[f(x)],k(x,x′)=cov⁡(f(x),f(x′)).\begin{aligned} f &\sim \mathcal{GP}\big(m(x), k(x, x')\big), \\ m(x) &= \mathbb E[f(x)], \\ k(x, x') &= \operatorname{cov}\big(f(x), f(x')\big) . \end{aligned}

For any inputs x1,…,xnx_1, \dots, x_n, the vector (f(x1),…,f(xn))(f(x_1), \dots, f(x_n)) is N(m,K)\mathcal N(m, K) with Kij=k(xi,xj)K_{ij} = k(x_i, x_j). A function is an infinitely long vector, but we only ever ask finite-dimensional questions about it, and the marginals of a Gaussian are Gaussian with the corresponding sub-blocks: adding inputs never changes the distribution of the old ones (Cambridge 4F13, lecture on Gaussian processes). We take m=0m = 0 throughout; a known trend can be subtracted first.

The covariance function is the whole model. It must make every matrix KK symmetric positive semidefinite, which is exactly the condition for a function to be a kernel. The kernels note read k(x,x′)k(x, x') as an inner product of feature maps; here the same function is a covariance, and the opening model is the special case k(x,x′)=ϕ(x)⊤ϕ(x′)k(x, x') = \phi(x)^\top \phi(x'). The workhorse is the squared exponential or RBF kernel,

k(x,x′)=sf2exp⁡(−∥x−x′∥22ℓ2),k(x, x') = s_f^2 \exp\Big(-\frac{\lVert x - x' \rVert^2}{2 \ell^2}\Big) ,

where sf2s_f^2 is the prior variance of every f(x)f(x) and the length scale ℓ\ell is the distance over which the function keeps its value. The correlation of f(x)f(x) and f(x′)f(x') is e−1/2=0.607e^{-1/2} = 0.607 at distance ℓ\ell, e−2=0.135e^{-2} = 0.135 at 2ℓ2\ell and e−9/2=0.011e^{-9/2} = 0.011 at 3ℓ3\ell. Values a few length scales apart are nearly independent, so a draw from the prior wiggles on the scale ℓ\ell and rarely strays beyond ±2sf\pm 2 s_f: at any one xx, f(x)∼N(0,sf2)f(x) \sim \mathcal N(0, s_f^2) does so with probability 0.0460.046.

Unlike the nine bumps, the RBF kernel gives the prior variance sf2s_f^2 at every xx, near the data or a thousand units away. It corresponds to infinitely many Gaussian bumps placed densely everywhere (Rasmussen and Williams, 2006, Section 4.2.1), so there is no region where the prior is blind. A neural network with one hidden layer and a Gaussian prior on its weights also tends to a Gaussian process as the number of hidden units grows, a result of Neal that Bishop (2006, Section 6.4.7) recounts. The intuition is the central limit theorem: the output is a sum of many independent hidden-unit contributions, with prior variances scaled down as their number grows.

Why bumps everywhere give the RBF kernel

Let the bumps e−(x−c)2/(2b2)e^{-(x - c)^2/(2 b^2)} have centres cc spread over the whole line with unit density. The sum over centres in the covariance ϕ(x)⊤ϕ(x′)\phi(x)^\top \phi(x') becomes an integral. Completing the square in cc, (x−c)2+(x′−c)2=2(c−x+x′2)2+(x−x′)22(x - c)^2 + (x' - c)^2 = 2\big(c - \frac{x + x'}{2}\big)^2 + \frac{(x - x')^2}{2}, and the Gaussian integral over cc gives

∫e−(x−c)2+(x′−c)22b2 dc=π b  e−(x−x′)24b2,\int e^{-\frac{(x - c)^2 + (x' - c)^2}{2 b^2}}\, dc = \sqrt\pi\, b\; e^{-\frac{(x - x')^2}{4 b^2}} ,

the RBF kernel with ℓ=2 b\ell = \sqrt2\, b and the same variance at every xx.

Other kernels encode other beliefs: the Matérn family rougher functions, a periodic kernel repeating ones, the linear kernel x⊤x′x^\top x' straight lines. Sums and products of kernels are kernels, by the rules of the kernels note, so a trend plus a seasonal pattern plus noise is a sum of three.

Regression: the posterior in closed form#

Let the observations be yi=f(xi)+εiy_i = f(x_i) + \varepsilon_i with independent noise εi∼N(0,σn2)\varepsilon_i \sim \mathcal N(0, \sigma_n^2), and collect the training inputs in XX and the targets in y=(y1,…,yn)⊤y = (y_1, \dots, y_n)^\top. For a test input x∗x_*, write f∗=f(x∗)f_* = f(x_*), k∗∗=k(x∗,x∗)k_{**} = k(x_*, x_*), and k∗k_* for the vector of k(xi,x∗)k(x_i, x_*). The targets and f∗f_* are jointly Gaussian with zero mean:

(yf∗)∼N(0, (Kyk∗k∗⊤k∗∗)),\begin{pmatrix} y \\ f_* \end{pmatrix} \sim \mathcal N\left(0,\ \begin{pmatrix} K_y & k_* \\ k_*^\top & k_{**} \end{pmatrix}\right) ,

where Ky=K+σn2IK_y = K + \sigma_n^2 I. The noise adds σn2\sigma_n^2 to the variance of each yiy_i and nothing to the covariance between yy and f∗f_*, because it is independent of ff. The conditional of a Gaussian of f∗f_* given yy is Gaussian; KyK_y is invertible for σn>0\sigma_n \gt 0, and

fˉ∗=k∗⊤Ky−1y,var⁡(f∗)=k∗∗−k∗⊤Ky−1k∗\boxed{ \begin{aligned} \bar f_* &= k_*^\top K_y^{-1} y, \\ \operatorname{var}(f_*) &= k_{**} - k_*^\top K_y^{-1} k_* \end{aligned} }

(Rasmussen and Williams, 2006, Eq. 2.25–2.26).

The mean is a weighted sum of kernel functions centred at the training points, fˉ∗=∑iαik(xi,x∗)\bar f_* = \sum_i \alpha_i k(x_i, x_*) with α=Ky−1y\alpha = K_y^{-1} y. It is exactly the kernel ridge regression predictor k∗⊤(K+λI)−1yk_*^\top (K + \lambda I)^{-1} y with λ=σn2\lambda = \sigma_n^2, or with penalty λ=σn2/sf2\lambda = \sigma_n^2 / s_f^2 for the kernel scaled to unit variance, k/sf2k/s_f^2: it smooths instead of interpolating, and far from the data it returns to the prior mean 0.

The variance starts from the prior variance k∗∗k_{**} and subtracts what the data explain. It does not depend on yy at all, only on where the inputs are: small where x∗x_* is close to training points, back to k∗∗k_{**} far from them. A new noisy observation adds the noise, y∗∼N(fˉ∗,var⁡(f∗)+σn2)y_* \sim \mathcal N(\bar f_*, \operatorname{var}(f_*) + \sigma_n^2). For several test inputs at once the same conditional gives a covariance matrix, and drawing from it gives whole functions from the posterior.

Take the example of the kernels note: two training points x=0x = 0 and x=1x = 1 with targets 11 and 22, ℓ=sf=1\ell = s_f = 1 and σn2=0.1\sigma_n^2 = 0.1.

x∗x_*fˉ∗\bar f_*var⁡(f∗)\operatorname{var}(f_*)
0.50.51.5511.5510.0870.087
330.2550.2550.9780.978

Between the two points the function is pinned down, and the mean is the one kernel ridge regression gave. Two length scales from the nearest point the variance is almost the prior variance 1: the data say little, and the model says so.

In practice we never form Ky−1K_y^{-1}. A Cholesky factorization Ky=LL⊤K_y = L L^\top costs n3/3n^3/3 operations, and triangular solves give the rest (Rasmussen and Williams, 2006, Algorithm 2.1):

α=L−⊤L−1y,v=L−1k∗,fˉ∗=k∗⊤α,var⁡(f∗)=k∗∗−v⊤v,log⁡det⁡Ky=2∑ilog⁡Lii.\begin{aligned} \alpha &= L^{-\top} L^{-1} y, \qquad v = L^{-1} k_*, \\ \bar f_* &= k_*^\top \alpha, \\ \operatorname{var}(f_*) &= k_{**} - v^\top v, \\ \log \det K_y &= 2 \textstyle\sum_i \log L_{ii} . \end{aligned}
Figure

A Gaussian process before and after the data

Prior and posterior of a Gaussian processLeft, a wide band and three wavy curves around zero. Right, data points with a narrow band and three close curves through them; the band widens between x = 1.6 and 3.9 and past the ends.-6-3036-22-6-3036-22Prior: three draws of f1Posterior after 12 points234Prior and posterior of a Gaussian processLeft, a wide band and three wavy curves around zero. Right, data points with a narrow band and three close curves through them; the band widens between x = 1.6 and 3.9 and past the ends.-6-3036-22-6-3036-22Prior: three draws of f1Posterior after 12 points234
Left: the prior f ~ GP(0, k) with the RBF kernel, sf = 1, ℓ = 1.76; the band of ±1.96 is the same everywhere, and the three draws are smooth functions that vary on the scale ℓ (1). Right: 12 observations with noise σn = 0.1 (2), the posterior mean with the 95% band for f (3), and three draws from the posterior (4). The standard deviation is 0.068 at x = 0, 0.162 in the gap at x = 2.75 and 0.512 at x = 6, past the last point.

The figure uses the twelve values of sin⁡x\sin x and the length scale ℓ=1.76\ell = 1.76 chosen in the next section. After the data, the posterior standard deviation is 0.0680.068 at x=0x = 0, rises to 0.1620.162 in the middle of the gap between 1.61.6 and 3.93.9, reaches 0.5120.512 at x=6x = 6, past the last point, and is back at the prior value 1.001.00 at x=10x = 10, where the nine bumps claimed 00.

Choosing the kernel by the marginal likelihood#

The posterior depends on the hyperparameters θ=(ℓ,sf,σn)\theta = (\ell, s_f, \sigma_n). In the language of Bayesian model selection, each θ\theta is a model, and its evidence is the probability of the targets with the function integrated out. Under the prior y∼N(0,Ky)y \sim \mathcal N(0, K_y), so

log⁡p(y∣X,θ)=−12 y⊤Ky−1ydata fit−12log⁡det⁡Kycomplexity−n2log⁡2π\begin{aligned} \log p(y \mid X, \theta) ={}& -\tfrac12\, y^\top K_y^{-1} y && \text{data fit} \\ &- \tfrac12 \log \det K_y && \text{complexity} \\ &- \tfrac n2 \log 2\pi \end{aligned}

(Rasmussen and Williams, 2006, Eq. 5.8). The Gaussian did the integral over infinitely many function values: no sampling, no bound.

The two terms pull in opposite directions. A short length scale lets the mean bend through every point, so the data fit is good. But it makes KyK_y close to a multiple of the identity with a large determinant: the model could have produced many very different datasets, so it gives little density to any one of them. A long length scale has a small determinant but cannot follow the data. The maximum is the type-II maximum likelihood estimate, also called empirical Bayes, the evidence maximization of Bayesian linear regression with ℓ\ell added to the list.

Figure

Choosing the length scale by the evidence

The marginal likelihood as a function of the length scaleThe data fit falls as the length scale grows, the complexity term rises, and their sum peaks near 1.76. Three small plots show a too flexible, a fitting and a too stiff model.-30-20-10010200.20.5123length scale ℓ (log scale)1data fit2complexity3log evidenceℓ = 0.3: log evidence −13.94ℓ = 1.76: log evidence −3.9ℓ = 3: log evidence −23.9The marginal likelihood as a function of the length scaleThe data fit falls as the length scale grows, the complexity term rises, and their sum peaks near 1.76. Three small plots show a too flexible, a fitting and a too stiff model.-30-20-10010200.20.5123length scale ℓ (log scale)1data fit2complexity3log evidenceℓ = 0.3: log evidence −13.94ℓ = 1.76: log evidence −3.9ℓ = 3: log evidence −23.9
The log marginal likelihood of the 12 points as a function of the length scale ℓ of the RBF kernel, with sf = 1 and σn = 0.1. The data fit (1) is best at short length scales, the complexity penalty (2) shrinks as ℓ grows, and their sum (3) peaks at ℓ = 1.76 with −3.89 (the constant −6 log 2π = −11.03 is included in the sum). Right (4): the posterior mean and 95% band at ℓ = 0.3 (−13.90), 1.76 and 3 (−23.92).

For the twelve points with sf=1s_f = 1 and σn=0.1\sigma_n = 0.1 fixed, the terms are as follows; the constant −6log⁡2π=−11.03-6 \log 2\pi = -11.03 is included in the total:

ℓ\elldata fitcomplexitylog evidence
0.3−2.88-2.880.010.01−13.90-13.90
1.76−5.55-5.5512.6912.69−3.89-3.89
3−29.50-29.5016.6016.60−23.92-23.92

The short length scale fits best, by 2.7 nats, and loses 12.7 nats in complexity: its posterior mean, the top small panel of the figure, drops back to zero between neighbouring points and explains the sample as nearly independent noise. The long one cannot bend enough to follow the sine and pays 24 nats in data fit. The maximum, at ℓ=1.76\ell = 1.76, is the model that explains the data and could not have explained much else.

Optimizing all three hyperparameters on the log scale gives ℓ=1.633\ell = 1.633, sf=0.858s_f = 0.858 and σn=0.099\sigma_n = 0.099, with log evidence −3.81-3.81; scikit-learn’s GaussianProcessRegressor finds the same values. The noise level the data were generated with, 0.10.1, is recovered.

The gradient#

Optional depth: how the optimizer gets its gradient. The rest of the note does not depend on it.

The hyperparameters are found by gradient ascent, usually on log⁡θ\log \theta to keep them positive. We need two derivatives from the matrix calculus note, ∂Ky−1=−Ky−1(∂Ky)Ky−1\partial K_y^{-1} = -K_y^{-1} (\partial K_y) K_y^{-1} and ∂log⁡det⁡Ky=tr⁡(Ky−1 ∂Ky)\partial \log \det K_y = \operatorname{tr}(K_y^{-1}\, \partial K_y). With α=Ky−1y\alpha = K_y^{-1} y and ∂j=∂/∂θj\partial_j = \partial / \partial \theta_j,

∂jlog⁡p(y∣X,θ)=12 y⊤Ky−1(∂jKy)Ky−1y−12tr⁡(Ky−1 ∂jKy)=12tr⁡((αα⊤−Ky−1) ∂jKy)\begin{aligned} \partial_j \log p(y \mid X, \theta) &= \tfrac12\, y^\top K_y^{-1} (\partial_j K_y) K_y^{-1} y \\ &\quad - \tfrac12 \operatorname{tr}\big(K_y^{-1}\, \partial_j K_y\big) \\ &= \tfrac12 \operatorname{tr}\Big( \big(\alpha \alpha^\top - K_y^{-1}\big)\, \partial_j K_y \Big) \end{aligned}

(Rasmussen and Williams, 2006, Eq. 5.9). The last step writes the scalar α⊤(∂jKy) α\alpha^\top (\partial_j K_y)\, \alpha as its own trace and moves α\alpha around the trace, which is cyclic. Once Ky−1K_y^{-1} is known, each derivative costs O(n2)O(n^2). The evidence is not concave in θ\theta; the last section shows a second maximum on the same twelve points.

The cost, and inducing points#

Exact inference factorizes the n×nn \times n matrix KyK_y: O(n3)O(n^3) time and O(n2)O(n^2) memory, then O(n)O(n) per predictive mean and O(n2)O(n^2) per variance. For n=104n = 10^4 that is about 3×10113 \times 10^{11} operations and a matrix of 800 MB, and every step of the hyperparameter search repeats it. The kernels note met the same wall and climbed it with random features. Gaussian processes usually take another route: summarize the function by its values at m≪nm \ll n inducing inputs Z=(z1,…,zm)Z = (z_1, \dots, z_m) and let the data talk to each other only through them.

The simplest such approximation, the subset of regressors, replaces the kernel by its projection on the inducing points,

k(x,x′)≈k(x,Z) KZZ−1 k(Z,x′),k(x, x') \approx k(x, Z)\, K_{ZZ}^{-1}\, k(Z, x') ,

a kernel of rank mm: a Bayesian linear regression on the mm features k(x,zj)k(x, z_j) with the prior N(0,KZZ−1)\mathcal N(0, K_{ZZ}^{-1}) on the weights, since then the covariance ϕ(x)⊤Σpϕ(x′)\phi(x)^\top \Sigma_p \phi(x') is the projected kernel. The weight-space mean of the last section, with Φ=KXZ\Phi = K_{XZ} and Σp−1=KZZ\Sigma_p^{-1} = K_{ZZ}, multiplied through by σn2\sigma_n^2, is

fˉ∗=k(x∗,Z)(σn2KZZ+KZXKXZ)−1KZX y,\bar f_* = k(x_*, Z) \big(\sigma_n^2 K_{ZZ} + K_{ZX} K_{XZ}\big)^{-1} K_{ZX}\, y ,

which costs O(nm2)O(n m^2): for n=104n = 10^4 and m=100m = 100, about 10810^8 operations. On 20002000 noisy points of sin⁡x\sin x on [−5,5][-5, 5] with ℓ=1\ell = 1, the largest gap between this mean and the exact one on a grid shrinks fast with evenly spaced inducing points:

mm51020
largest difference from the exact mean0.6050.6050.0110.0110.00040.0004

A smooth function needs few inducing points. The subset of regressors still has the defect of the opening model: a degenerate kernel whose variance shrinks to zero far from the inducing points. Its refinements repair this. FITC keeps the exact prior variance at every training point, and the variational method of Titsias chooses the inducing inputs by maximizing a lower bound on the exact evidence, the variational inference of the previous section applied to function values (Murphy, 2023, Section 18.5).

Classification with the Laplace approximation#

For binary labels yi∈{0,1}y_i \in \{0, 1\} the process is placed on a latent function, and the label probability is a squashed version of it, p(yi=1∣fi)=σ(fi)p(y_i = 1 \mid f_i) = \sigma(f_i) with the logistic sigmoid of logistic regression. The likelihood is no longer Gaussian, and the posterior of the latent values f=(f1,…,fn)f = (f_1, \dots, f_n),

p(f∣X,y)∝N(f∣0,K)∏i=1nσ(fi)yi(1−σ(fi))1−yi,p(f \mid X, y) \propto \mathcal N(f \mid 0, K) \prod_{i=1}^n \sigma(f_i)^{y_i} \big(1 - \sigma(f_i)\big)^{1 - y_i} ,

has no closed form. It is log-concave, so it has a single mode, and the Laplace approximation replaces it by a Gaussian at that mode with the curvature there. Vetrov and Kropotov’s textbook stops at the mode, found by IRLS; the Gaussian around it also gives a probability.

Write Ψ(f)=log⁡p(y∣f)−12f⊤K−1f\Psi(f) = \log p(y \mid f) - \frac12 f^\top K^{-1} f for the unnormalized log posterior. Its gradient is y−σ(f)−K−1fy - \sigma(f) - K^{-1} f, the residuals of logistic regression with Φ=I\Phi = I, and its Hessian is −(W+K−1)-(W + K^{-1}) with the diagonal W=diag⁡(σ(fi)(1−σ(fi)))W = \operatorname{diag}\big(\sigma(f_i)(1 - \sigma(f_i))\big). The Newton step f−(∇∇Ψ)−1∇Ψf - (\nabla\nabla\Psi)^{-1} \nabla\Psi is (K−1+W)−1((K−1+W)f+y−σ(f)−K−1f)(K^{-1} + W)^{-1}\big((K^{-1} + W) f + y - \sigma(f) - K^{-1} f\big), which simplifies to

fnew=(K−1+W)−1(Wf+y−σ(f)),f^{\text{new}} = (K^{-1} + W)^{-1} \big(W f + y - \sigma(f)\big) ,

iterated to the mode f^\hat f. The approximate posterior is N(f^,(K−1+W)−1)\mathcal N\big(\hat f, (K^{-1} + W)^{-1}\big) (Rasmussen and Williams, 2006, Section 3.4). At the mode the gradient vanishes, so f^=K (y−σ(f^))\hat f = K\,(y - \sigma(\hat f)), and the latent value at x∗x_* has

E[f∗]=k∗⊤(y−σ(f^)),var⁡(f∗)=k∗∗−k∗⊤(K+W−1)−1k∗.\begin{aligned} \mathbb E[f_*] &= k_*^\top \big(y - \sigma(\hat f)\big), \\ \operatorname{var}(f_*) &= k_{**} - k_*^\top \big(K + W^{-1}\big)^{-1} k_* . \end{aligned}

The variance is the regression formula with W−1W^{-1} in place of the noise: a point the model already classifies confidently has a small WiiW_{ii}, a large effective noise, and little influence.

Derivation

Given ff, the prior conditional gives f∗f_* the mean k∗⊤K−1fk_*^\top K^{-1} f and the variance k∗∗−k∗⊤K−1k∗k_{**} - k_*^\top K^{-1} k_*. Average over q(f)=N(f^,Σ)q(f) = \mathcal N(\hat f, \Sigma) with Σ=(K−1+W)−1\Sigma = (K^{-1} + W)^{-1}. The mean is k∗⊤K−1f^=k∗⊤(y−σ(f^))k_*^\top K^{-1} \hat f = k_*^\top (y - \sigma(\hat f)). By the law of total variance,

var⁡(f∗)=k∗∗−k∗⊤K−1k∗+k∗⊤K−1ΣK−1k∗=k∗∗−k∗⊤(K−1−K−1(K−1+W)−1K−1)k∗=k∗∗−k∗⊤(K+W−1)−1k∗,\begin{aligned} \operatorname{var}(f_*) &= k_{**} - k_*^\top K^{-1} k_* + k_*^\top K^{-1} \Sigma K^{-1} k_* \\ &= k_{**} - k_*^\top \big(K^{-1} - K^{-1} (K^{-1} + W)^{-1} K^{-1}\big) k_* \\ &= k_{**} - k_*^\top (K + W^{-1})^{-1} k_* , \end{aligned}

where the last step is the Woodbury identity with A=KA = K, U=V=IU = V = I and C=W−1C = W^{-1}.

The probability of class 1 averages the sigmoid over this Gaussian,

p(y∗=1∣y)=∫σ(f∗) q(f∗) df∗,q(f∗)=N(f∗∣E[f∗],var⁡(f∗)).\begin{aligned} p(y_* = 1 \mid y) &= \int \sigma(f_*)\, q(f_*)\, df_* , \\ q(f_*) &= \mathcal N\big(f_* \mid \mathbb E[f_*], \operatorname{var}(f_*)\big) . \end{aligned}

It has no closed form, but the probit approximation of MacKay (1992), σ(E[f∗]/1+πvar⁡(f∗)/8)\sigma\big(\mathbb E[f_*] / \sqrt{1 + \pi \operatorname{var}(f_*)/8}\big), derived in the Laplace note, is close. The average is always less extreme than the plug-in σ(E[f∗])\sigma(\mathbb E[f_*]): uncertainty about f∗f_* pulls the probability toward 12\tfrac12.

Why the average is less extreme

Take a mean m≥0m \ge 0 and pair the values of the Gaussian at m±tm \pm t, which have equal density. Since σ′\sigma' is even and decreasing in ∣a∣\lvert a \rvert, and ∣m+t∣≥∣m−t∣\lvert m + t \rvert \ge \lvert m - t \rvert, the pair sum σ(m+t)+σ(m−t)\sigma(m + t) + \sigma(m - t) never grows with tt, so it stays at most 2σ(m)2\sigma(m). It is at least 1, because σ(a)+σ(b)≥1\sigma(a) + \sigma(b) \ge 1 whenever a+b≥0a + b \ge 0. Averaging over the pairs puts the probability between 12\frac12 and σ(m)\sigma(m); a negative mean is the mirror image.

As an example, take twenty points evenly spaced on [−3,3][-3, 3], labels drawn with probability σ(2sin⁡x)\sigma(2 \sin x), and the kernel 222^2 times the RBF with ℓ=1\ell = 1. Newton’s method converges in under 20 steps.

x∗x_*E[f∗]\mathbb E[f_*]var⁡(f∗)\operatorname{var}(f_*)plug-inprobit approx.exact average
−1.5-1.5−1.31-1.311.031.030.2120.2120.2480.2480.2510.251
1.51.51.201.200.890.890.7690.7690.7380.7380.7350.735
66−0.01-0.014.004.000.4960.4960.4980.4980.4980.498

Far from the data, at x∗=6x_* = 6, the latent variance is the prior variance 4 and every version is close to 12\tfrac12. scikit-learn’s GaussianProcessClassifier, which implements the same Laplace approximation, gives the exact averages of the last column.

Moment matching instead of a mode#

In classification the mode is the wrong centre. The posterior is a Gaussian prior centred at zero, multiplied by likelihood factors that each softly cut away the half-line where fif_i disagrees with its label. The density falls steeply toward the cut and slowly on the other side, so its mass lies farther from zero than its mode (Rasmussen and Williams, 2006, Section 3.8), the skewness of the Laplace note.

From here on we use the probit likelihood p(yi∣fi)=Φ(yifi)p(y_i \mid f_i) = \Phi(y_i f_i) with labels yi∈{−1,+1}y_i \in \{-1, +1\}, where Φ\Phi is the standard normal distribution function; it is close to the logistic sigmoid and integrates against Gaussians in closed form, ∫Φ(f) N(f∣m,v) df=Φ(m/1+v)\int \Phi(f)\, \mathcal N(f \mid m, v)\, df = \Phi\big(m/\sqrt{1 + v}\big), as the Laplace note shows. One latent value with the prior N(0,4)\mathcal N(0, 4) and one label y=1y = 1 already shows the problem:

centrestandard deviation
Laplace: mode and curvature1.0621.0621.2891.289
exact posterior1.4271.4271.4011.401

The Gaussian at the mode sits a quarter too close to zero and is too narrow.

Expectation propagation (EP) fits the mean and variance instead. It replaces each likelihood factor by an unnormalized Gaussian site in its own latent value, ti(fi)∝N(fi∣μ~i,σ~i2)t_i(f_i) \propto \mathcal N(f_i \mid \tilde\mu_i, \tilde\sigma_i^2), so that the approximate posterior is

q(f)∝N(f∣0,K)∏i=1nti(fi)=N(f∣μ,Σ),Σ=(K−1+Σ~−1)−1,μ=ΣΣ~−1μ~,\begin{aligned} q(f) &\propto \mathcal N(f \mid 0, K) \prod_{i=1}^n t_i(f_i) = \mathcal N(f \mid \mu, \Sigma), \\ \Sigma &= \big(K^{-1} + \tilde\Sigma^{-1}\big)^{-1}, \\ \mu &= \Sigma \tilde\Sigma^{-1} \tilde\mu , \end{aligned}

with Σ~=diag⁡(σ~i2)\tilde\Sigma = \operatorname{diag}(\tilde\sigma_i^2): GP regression with pseudo-targets μ~i\tilde\mu_i and noise variances σ~i2\tilde\sigma_i^2, so predictions use the regression formulas with K+Σ~K + \tilde\Sigma in place of KyK_y. The sites are refined one at a time, each in the context of all the others (Rasmussen and Williams, 2006, Section 3.6):

  1. Divide site ii out of the marginal N(μi,Σii)\mathcal N(\mu_i, \Sigma_{ii}) of qq, which subtracts precisions. What remains is the cavity N(μ−i,σ−i2)\mathcal N(\mu_{-i}, \sigma_{-i}^2): what the prior and the other sites say about fif_i.
  2. Multiply the cavity by the exact factor Φ(yifi)\Phi(y_i f_i). This tilted distribution is non-Gaussian, but for the probit its mean and variance have closed forms.
  3. Choose the Gaussian with that mean and variance, and divide the cavity out of it again. The quotient is the new site.

For step 2, let φ\varphi be the standard normal density and r(z)=φ(z)/Φ(z)r(z) = \varphi(z)/\Phi(z). The moments of the tilted distribution are

zi=yi μ−i1+σ−i2,μ^i=μ−i+yi σ−i2 r(zi)1+σ−i2,σ^i2=σ−i2−σ−i4 r(zi)(zi+r(zi))1+σ−i2.\begin{aligned} z_i &= \frac{y_i\, \mu_{-i}}{\sqrt{1 + \sigma_{-i}^2}}, \\ \hat\mu_i &= \mu_{-i} + \frac{y_i\, \sigma_{-i}^2\, r(z_i)}{\sqrt{1 + \sigma_{-i}^2}}, \\ \hat\sigma_i^2 &= \sigma_{-i}^2 - \frac{\sigma_{-i}^4\, r(z_i)\big(z_i + r(z_i)\big)}{1 + \sigma_{-i}^2} . \end{aligned}

With a single site the cavity is the prior and the tilted distribution is the exact posterior, so EP reproduces the exact row of the table above.

Derivation of the tilted moments and of the Laplace row

Write the cavity as N(f∣m,v)\mathcal N(f \mid m, v) and let Z(m)=∫Φ(yf) N(f∣m,v) df=Φ(z)Z(m) = \int \Phi(y f)\, \mathcal N(f \mid m, v)\, df = \Phi(z) with z=ym/1+vz = y m/\sqrt{1 + v}. Since ∂mN(f∣m,v)=f−mv N(f∣m,v)\partial_m \mathcal N(f \mid m, v) = \frac{f - m}{v}\, \mathcal N(f \mid m, v), differentiating ZZ under the integral gives the tilted moments:

∂mlog⁡Z=E[f]−mv,∂m2log⁡Z=Var⁡(f)v2−1v.\begin{aligned} \partial_m \log Z &= \frac{\mathbb E[f] - m}{v}, \\ \partial_m^2 \log Z &= \frac{\operatorname{Var}(f)}{v^2} - \frac1v . \end{aligned}

With φ′(z)=−zφ(z)\varphi'(z) = -z\varphi(z), the ratio r=φ/Φr = \varphi/\Phi has r′(z)=−r(z)(z+r(z))r'(z) = -r(z)\big(z + r(z)\big). So ∂mlog⁡Φ(z)=y r(z)/1+v\partial_m \log \Phi(z) = y\, r(z)/\sqrt{1 + v} and ∂m2log⁡Φ(z)=−r(z)(z+r(z))/(1+v)\partial_m^2 \log \Phi(z) = -r(z)\big(z + r(z)\big)/(1 + v), using y2=1y^2 = 1. Solving the two lines for E[f]\mathbb E[f] and Var⁡(f)\operatorname{Var}(f) gives μ^i\hat\mu_i and σ^i2\hat\sigma_i^2. The same rr gives the Laplace row: ddflog⁡Φ(f)=r(f)\frac{d}{df}\log\Phi(f) = r(f), so the mode solves r(f)=f/4r(f) = f/4, at 1.0621.062, and the curvature is 14+r(f)(f+r(f))\frac14 + r(f)\big(f + r(f)\big).

Over Gaussians, minimizing the forward divergence DKL(tilted ∥ q)D_{\mathrm{KL}}(\text{tilted} \,\|\, q) means matching the mean and variance (Bishop, 2006, Section 10.7): up to terms without qq, it is −Etilted[log⁡q]=12log⁡vq+Etilted[(f−mq)2]/(2vq)-\mathbb E_{\text{tilted}}[\log q] = \frac12 \log v_q + \mathbb E_{\text{tilted}}[(f - m_q)^2]/(2 v_q), minimized by the tilted mean mqm_q and then the tilted variance vqv_q. This is the local moment matching of the variational inference note: the global DKL(p ∥ q)D_{\mathrm{KL}}(p \,\|\, q) would need the exact posterior, so each step minimizes it for one factor, with the others held at their approximations.

Now return to the twenty points, with the probit likelihood and the same kernel. Laplace runs as in the previous section, with the probit’s curvature in WW; EP converges in 11 sweeps. The exact column comes from 200,000 importance samples drawn from a widened EP Gaussian (effective sample size about 31,000):

LaplaceEPexact
posterior mean of ff at x=−3x = -3−1.59-1.59−1.98-1.98−1.98-1.98
p(y∗=1)p(y_* = 1) at x∗=−1.5x_* = -1.50.2600.2600.2310.2310.2310.231
p(y∗=1)p(y_* = 1) at x∗=1.5x_* = 1.50.8070.8070.8330.8330.8330.833
log evidence−13.94-13.94−13.83-13.83−13.80-13.80

Laplace is too timid: its latent means are 8% to 20% closer to zero than the exact ones, its probabilities are pulled toward 12\tfrac12, and its evidence is too low. EP agrees with the exact posterior to the precision of the sampler. On handwritten digits, Laplace’s best evidence was about 9 nats below EP’s, and annealed importance sampling sided with EP (Rasmussen and Williams, 2006, Section 3.8).

Each sweep costs O(n3)O(n^3), like a Newton step, and nothing guarantees that the sweeps converge. For log-concave likelihoods such as the probit it converges in practice; with others a site can get a negative variance, and implementations damp the updates (Murphy, 2023, Section 10.7).

The same algorithm as message passing#

The model’s factor graph has a variable node for each fif_i, one prior factor N(f∣0,K)\mathcal N(f \mid 0, K) joined to all of them, and a likelihood factor joined to each fif_i alone. On a tree like this, the sum-product algorithm computes marginals by passing messages: a variable sends a factor the product of its other incoming messages, and a factor sends a variable its own function times the incoming messages, with the other variables integrated out (Cambridge 4F13, lecture on factor graphs).

Figure

EP as message passing on a factor graph

EP as message passing on a factor graphAt the top, a box for the prior factor N(f | 0, K), joined by lines to circles f₁, f₂, fᵢ and fₙ. Below each circle a small square is the likelihood factor Φ(yⱼfⱼ). In the column of fᵢ a blue arrow runs down from the prior factor to the square and an amber arrow runs back up.N(f | 0, K)prior factorf1Φ(y1 f1)f2Φ(y2 f2)fiΦ(yi fi)fnΦ(yn fn)⋯⋯1cavity: the prior andevery other site4new site tᵢ = Gaussian ÷ cavity2tilted: cavity × Φ(yᵢfᵢ)3match its mean and varianceEP as message passing on a factor graphAt the top, a box for the prior factor N(f | 0, K), joined by lines to circles f₁, f₂, fᵢ and fₙ. Below each circle a small square is the likelihood factor Φ(yⱼfⱼ). In the column of fᵢ a blue arrow runs down from the prior factor to the square and an amber arrow runs back up.N(f | 0, K)prior factorf1f2fiΦ(yi fi)fn⋯⋯1cavity: prior and other sites2tilted: cavity × Φ(yᵢfᵢ)3match its mean and variance4site tᵢ = Gaussian ÷ cavity
The factor graph of GP classification: the prior factor N(f | 0, K) joins all latent values, and each fⱼ has its own likelihood factor. The steps show one EP update of site i. Blue is the cavity, amber the new site; every other message is Gaussian and exact.

The cavity is the message from fif_i to its likelihood factor, and the site is the message back. The exact message back would be Φ(yifi)\Phi(y_i f_i) itself, which is not Gaussian and would make the prior factor’s integrals intractable. EP sends instead the Gaussian that, multiplied by the cavity, matches the moments of the tilted distribution. All other messages are computed exactly. EP is sum-product with one projection, iterated because each projection depends on the current messages.

Since Φ(yf)=P(sign⁡(f+ε)=y)\Phi(y f) = P\big(\operatorname{sign}(f + \varepsilon) = y\big) for ε∼N(0,1)\varepsilon \sim \mathcal N(0, 1), the label is the sign of a noisy copy of ff, and the moments above are those of a truncated Gaussian. In the TrueSkill model of 4F13 the noisy copy is a game’s performance difference, and message passing runs the same three steps over a graph of players and games (Cambridge 4F13, lectures on message passing in TrueSkill and moment matching); the Gibbs sampling note samples that model instead.

Bayesian linear regression is a GP with a linear kernel#

The opening model is itself a Gaussian process: with a prior w∼N(0,Σp)w \sim \mathcal N(0, \Sigma_p), its kernel is k(x,x′)=ϕ(x)⊤Σp ϕ(x′)k(x, x') = \phi(x)^\top \Sigma_p\, \phi(x'). Bayesian linear regression computes its predictive distribution in weight space, through the M×MM \times M posterior precision A=σn−2Φ⊤Φ+Σp−1A = \sigma_n^{-2} \Phi^\top \Phi + \Sigma_p^{-1}, where the rows of Φ\Phi are ϕ(xi)⊤\phi(x_i)^\top and ϕ∗=ϕ(x∗)\phi_* = \phi(x_*):

fˉ∗=σn−2 ϕ∗⊤A−1Φ⊤y,var⁡(f∗)=ϕ∗⊤A−1ϕ∗.\begin{aligned} \bar f_* &= \sigma_n^{-2}\, \phi_*^\top A^{-1} \Phi^\top y , \\ \operatorname{var}(f_*) &= \phi_*^\top A^{-1} \phi_* . \end{aligned}

The GP computes the same quantities in function space, through the n×nn \times n matrix Ky=ΦΣpΦ⊤+σn2IK_y = \Phi \Sigma_p \Phi^\top + \sigma_n^2 I. The means agree because

Φ⊤Ky=Φ⊤ΦΣpΦ⊤+σn2Φ⊤=σn2(σn−2Φ⊤Φ+Σp−1)ΣpΦ⊤=σn2A ΣpΦ⊤,\begin{aligned} \Phi^\top K_y &= \Phi^\top \Phi \Sigma_p \Phi^\top + \sigma_n^2 \Phi^\top \\ &= \sigma_n^2 \big(\sigma_n^{-2} \Phi^\top \Phi + \Sigma_p^{-1}\big) \Sigma_p \Phi^\top \\ &= \sigma_n^2 A\, \Sigma_p \Phi^\top , \end{aligned}

and multiplying by A−1A^{-1} on the left and Ky−1K_y^{-1} on the right gives σn−2A−1Φ⊤=ΣpΦ⊤Ky−1\sigma_n^{-2} A^{-1} \Phi^\top = \Sigma_p \Phi^\top K_y^{-1}. The variance follows from the Woodbury identity, A−1=Σp−ΣpΦ⊤Ky−1ΦΣpA^{-1} = \Sigma_p - \Sigma_p \Phi^\top K_y^{-1} \Phi \Sigma_p, so that ϕ∗⊤A−1ϕ∗=k∗∗−k∗⊤Ky−1k∗\phi_*^\top A^{-1} \phi_* = k_{**} - k_*^\top K_y^{-1} k_* (Rasmussen and Williams, 2006, Section 2.1). For straight lines, ϕ(x)=(1,x)\phi(x) = (1, x) and Σp=I\Sigma_p = I, the kernel is 1+xx′1 + x x', and the Code section checks that the two computations agree to 10−1210^{-12}.

Which view to compute in is a matter of cost: weight space costs O(nM2+M3)O(n M^2 + M^3), function space O(n3)O(n^3). With few features and many points, weights win; with infinitely many features, as for the RBF kernel, only function space is available. The same view explains the relevance vector machine: a linear model on kernel features with a prior precision αj\alpha_j per weight is a GP with the degenerate kernel ∑jαj−1ϕj(x)ϕj(x′)\sum_j \alpha_j^{-1} \phi_j(x) \phi_j(x'). When most αj\alpha_j go to infinity it inherits the defect of the opening, a predictive variance that shrinks away from the relevance vectors (Rasmussen and Williams, 2006, Section 6.6).

Where it breaks#

Start the optimizer of the marginal likelihood somewhere else. From ℓ=20\ell = 20, sf=0.5s_f = 0.5 and σn=0.7\sigma_n = 0.7, gradient ascent on the twelve points converges to

ℓ\ellsfs_fσn\sigma_nlog evidence
from ℓ=1\ell = 1, sf=1s_f = 1, σn=0.3\sigma_n = 0.31.6331.6330.8580.8580.0990.099−3.81-3.81
from ℓ=20\ell = 20, sf=0.5s_f = 0.5, σn=0.7\sigma_n = 0.721.321.30.0070.0070.7370.737−13.37-13.37

The second answer says that the function is flat and everything is noise. The optimizer stops at the lower bound we allow for sfs_f, e−5≈0.007e^{-5} \approx 0.007; without the bound sfs_f keeps falling and the evidence creeps up by less than 0.0010.001, to −13.372-13.372. That limit is the model y∼N(0,σn2I)y \sim \mathcal N(0, \sigma_n^2 I), whose log-likelihood is maximized by σn2=1n∑iyi2\sigma_n^2 = \frac1n \sum_i y_i^2: σn=0.737\sigma_n = 0.737 is the root mean square of the targets. So this is a maximum at the edge of the parameter space, 9.6 nats below the first, and every small step towards signal lowers the evidence, so a gradient method has no way to leave it. The evidence has a maximum for each explanation of the data, smooth signal with little noise or no signal with much noise. Several restarts from different initial values are the standard remedy (Rasmussen and Williams, 2006, Section 5.4.1); scikit-learn’s n_restarts_optimizer does exactly that.

The other failures belong to the kernel. A stationary RBF kernel assumes the same smoothness everywhere, so a function with a jump needs another kernel, and choosing among kernels is model selection again. In many dimensions a distance-based kernel makes all points nearly equidistant: with DD independent coordinates, ∥x−x′∥2\lVert x - x' \rVert^2 is a sum of DD independent terms, whose relative spread shrinks like 1/D1/\sqrt D; one length scale per input, the automatic relevance determination of the RVM, helps, but Gaussian processes are at their best with a few dozen inputs or fewer.

What you should remember#

  • A GP is a distribution over functions with jointly Gaussian values; its covariance is a positive semidefinite kernel, and the kernel is the model.
  • Regression: fˉ∗=k∗⊤Ky−1y\bar f_* = k_*^\top K_y^{-1} y and var⁡(f∗)=k∗∗−k∗⊤Ky−1k∗\operatorname{var}(f_*) = k_{**} - k_*^\top K_y^{-1} k_*, small near the data and back to the prior far away.
  • The evidence −12y⊤Ky−1y−12log⁡det⁡Ky−n2log⁡2π-\tfrac12 y^\top K_y^{-1} y - \tfrac12 \log\det K_y - \tfrac n2 \log 2\pi trades data fit against complexity; restart its optimizer.
  • Exact inference costs O(n3)O(n^3); mm inducing points bring it to O(nm2)O(n m^2).
  • Classification: Laplace centres on the mode, too close to zero; EP matches the moments of each tilted factor and is nearly exact.
  • Bayesian linear regression is a GP with the kernel ϕ(x)⊤Σpϕ(x′)\phi(x)^\top \Sigma_p \phi(x').

Code#

GP regression by hand, the evidence and a second local maximum, the linear kernel, inducing points, and classification by the Laplace approximation and by EP, checked against importance sampling. It runs in about two seconds; exact numbers can vary in the last digit across platforms and library versions.

import numpy as np
from scipy.optimize import minimize, minimize_scalar, brentq
from scipy.special import expit, log_ndtr
from scipy.stats import norm
from sklearn.gaussian_process import GaussianProcessRegressor, GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF, ConstantKernel as C, WhiteKernel

def rbf(a, b, ell=1.0, sf=1.0):                      # squared exponential kernel on 1-D inputs
    return sf**2 * np.exp(-(a[:, None] - b[None, :]) ** 2 / (2 * ell**2))

def gp_predict(X, y, Xs, ell, sf, sn):               # posterior mean and variance of f at Xs
    L = np.linalg.cholesky(rbf(X, X, ell, sf) + sn**2 * np.eye(len(X)))
    alpha = np.linalg.solve(L.T, np.linalg.solve(L, y))
    Ks = rbf(X, Xs, ell, sf)
    v = np.linalg.solve(L, Ks)
    return Ks.T @ alpha, sf**2 - (v**2).sum(axis=0)

def log_evidence(X, y, ell, sf, sn):                 # data fit, complexity, total
    L = np.linalg.cholesky(rbf(X, X, ell, sf) + sn**2 * np.eye(len(X)))
    a = np.linalg.solve(L, y)
    fit, comp = -0.5 * a @ a, -np.log(np.diag(L)).sum()
    return np.array([fit, comp, fit + comp - len(X) / 2 * np.log(2 * np.pi)])

# the kernel: correlation of f(x) and f(x') at distances ell, 2 ell, 3 ell
print(np.exp(-np.array([1, 2, 3]) ** 2 / 2).round(3))                  # [0.607 0.135 0.011]

# two training points x = 0, 1 with y = 1, 2; ell = sf = 1, noise variance 0.1
m, v = gp_predict(np.array([0.0, 1.0]), np.array([1.0, 2.0]), np.array([0.5, 3.0]), 1.0, 1.0, np.sqrt(0.1))
print(m.round(3), v.round(3))                                          # [1.551 0.255] [0.087 0.978]

# the data of the figures: 12 noisy values of sin(x), noise standard deviation 0.1
X = np.array([-4.5, -3.8, -3.0, -2.4, -1.5, -0.9, -0.2, 0.5, 1.1, 1.6, 3.9, 4.6])
y = np.array([0.91, 0.59, 0.03, -0.61, -1.16, -0.78, -0.26, 0.49, 0.73, 1.02, -0.66, -0.84])
xs = np.array([0.0, 2.75, 6.0, 10.0])

# Bayesian linear regression on 9 Gaussian bumps centred at -4, ..., 4, prior w ~ N(0, I)
Phi = lambda x: np.exp(-(x[:, None] - np.arange(-4, 5)) ** 2 / 2)
A = Phi(X).T @ Phi(X) / 0.1**2 + np.eye(9)                             # posterior precision of w
print((Phi(xs) ** 2).sum(axis=1).round(4),                             # prior variance of f(x)
      np.sqrt(np.einsum('ij,jk,ik->i', Phi(xs), np.linalg.inv(A), Phi(xs))).round(3))   # posterior sd of f(x)
# [1.7726 1.7661 0.0184 0.    ] [0.077 0.232 0.026 0.   ]
print(np.sqrt(gp_predict(X, y, xs, 1.76, 1.0, 0.1)[1]).round(3))       # the GP: [0.068 0.162 0.512 1.   ]

# the length scale by the marginal likelihood, with sf = 1 and sn = 0.1 fixed
best = minimize_scalar(lambda t: -log_evidence(X, y, np.exp(t), 1.0, 0.1)[2], bounds=(np.log(0.2), np.log(5)), method='bounded')
print(round(np.exp(best.x), 2), round(-best.fun, 2))                   # 1.76 -3.89
for ell in (0.3, 1.76, 3.0):
    print(ell, log_evidence(X, y, ell, 1.0, 0.1).round(2).tolist())
# 0.3 [-2.88, 0.01, -13.9] | 1.76 [-5.55, 12.69, -3.89] | 3.0 [-29.5, 16.6, -23.92]

# all three hyperparameters, on the log scale, from two starts, and scikit-learn's answer
for start in ([1.0, 1.0, 0.3], [20.0, 0.5, 0.7]):
    res = minimize(lambda p: -log_evidence(X, y, *np.exp(p))[2], np.log(start), method='L-BFGS-B', bounds=[(-5, 6)] * 3)
    print(start, np.exp(res.x).round(3), round(-res.fun, 2))           # ell, sf, sn and the log evidence
# [1.0, 1.0, 0.3] [1.633 0.858 0.099] -3.81
# [20.0, 0.5, 0.7] [2.1251e+01 7.0000e-03 7.3700e-01] -13.37: everything is noise
print(round(np.sqrt(np.mean(y**2)), 3))                                # 0.737, the root mean square of the targets
gpr = GaussianProcessRegressor(C(1.0) * RBF(1.0) + WhiteKernel(0.1), n_restarts_optimizer=5, random_state=0).fit(X[:, None], y)
print(gpr.kernel_, round(gpr.log_marginal_likelihood_value_, 2))
# 0.858**2 * RBF(length_scale=1.63) + WhiteKernel(noise_level=0.00975) -3.81

# the linear kernel k(x, x') = 1 + x x' is Bayesian linear regression with features (1, x), prior N(0, I), noise sd 0.5
F = lambda x: np.stack([np.ones_like(x), x], axis=1)
A = F(X).T @ F(X) / 0.5**2 + np.eye(2)
mw = F(xs) @ np.linalg.solve(A, F(X).T @ y) / 0.5**2                   # weight space: a 2 x 2 system
vw = np.einsum('ij,jk,ik->i', F(xs), np.linalg.inv(A), F(xs))
K, Ks = F(X) @ F(X).T + 0.5**2 * np.eye(len(X)), F(X) @ F(xs).T          # function space: a 12 x 12 system
mg, vg = Ks.T @ np.linalg.solve(K, y), (F(xs) ** 2).sum(axis=1) - np.einsum('ij,ij->j', Ks, np.linalg.solve(K, Ks))
print(np.abs(mw - mg).max() < 1e-12, np.abs(vw - vg).max() < 1e-12)    # True True

# a sparse GP (subset of regressors) with m inducing points on n = 2000 points, against the exact mean
rng = np.random.default_rng(0)
Xb = rng.uniform(-5, 5, 2000)
yb = np.sin(Xb) + 0.1 * rng.normal(size=2000)
grid = np.linspace(-5, 5, 201)
exact = gp_predict(Xb, yb, grid, 1.0, 1.0, 0.1)[0]                     # one 2000 x 2000 Cholesky factorization
for m in (5, 10, 20):
    Z = np.linspace(-5, 5, m)                                          # inducing inputs
    Kmn = rbf(Z, Xb)
    sparse = rbf(grid, Z) @ np.linalg.solve(0.1**2 * rbf(Z, Z) + Kmn @ Kmn.T, Kmn @ yb)   # an m x m system
    print(m, round(np.abs(sparse - exact).max(), 4))
# 5 0.6051 | 10 0.0107 | 20 0.0004

# classification with the Laplace approximation (Rasmussen and Williams, Algorithms 3.1 and 3.2), kernel 2^2 RBF(1)
Xc = np.linspace(-3, 3, 20)
yc = (rng.uniform(size=20) < expit(2 * np.sin(Xc))).astype(float)     # labels in {0, 1}
Kc = rbf(Xc, Xc, 1.0, 2.0)
f = np.zeros(20)
for _ in range(20):                                                    # Newton's method for the posterior mode
    p = expit(f); W = p * (1 - p); sW = np.sqrt(W)
    B = np.linalg.cholesky(np.eye(20) + sW[:, None] * Kc * sW[None, :])
    b = W * f + (yc - p)
    a = b - sW * np.linalg.solve(B.T, np.linalg.solve(B, sW * (Kc @ b)))
    step, f = np.abs(Kc @ a - f).max(), Kc @ a
print(yc.astype(int), step < 1e-10)                # [0 0 0 0 0 1 0 0 0 0 1 0 1 1 1 1 0 1 0 0] True
xt = np.array([-1.5, 0.0, 1.5, 6.0])
kt = rbf(Xc, xt, 1.0, 2.0)
p = expit(f); sW = np.sqrt(p * (1 - p))
B = np.linalg.cholesky(np.eye(20) + sW[:, None] * Kc * sW[None, :])
mu = kt.T @ (yc - p)                                                   # predictive mean of the latent f
var = 4.0 - (np.linalg.solve(B, sW[:, None] * kt) ** 2).sum(axis=0)    # and its variance
print(mu.round(2), var.round(2))                                       # [-1.31 -0.56  1.2  -0.01] [1.03 0.84 0.89 4.  ]
z = np.linspace(-12, 12, 4001)
averaged = [np.trapezoid(expit(m_ + np.sqrt(s) * z) * np.exp(-z**2 / 2), z) / np.sqrt(2 * np.pi) for m_, s in zip(mu, var)]
gpc = GaussianProcessClassifier(C(4.0, 'fixed') * RBF(1.0, 'fixed'), optimizer=None).fit(Xc[:, None], yc)
print(expit(mu).round(3), expit(mu / np.sqrt(1 + np.pi * var / 8)).round(3))   # plug-in, probit approximation
print(np.round(averaged, 3), gpc.predict_proba(xt[:, None])[:, 1].round(3))    # exact average, scikit-learn
# [0.212 0.364 0.769 0.496] [0.248 0.381 0.738 0.498]
# [0.251 0.384 0.735 0.498] [0.251 0.384 0.735 0.498]

# the probit likelihood Phi(y f) with y in {-1, +1}: Psi = N(z) / Phi(z), and -d^2/df^2 log Phi(y f) = Psi (z + Psi)
Psi = lambda z: np.exp(norm.logpdf(z) - log_ndtr(z))
s = np.array([-1.0, 1.0])[yc.astype(int)]

# one label y = 1 with the prior N(0, 4): mode and curvature (Laplace) against the exact mean and sd (moment matching)
mode = brentq(lambda f_: Psi(f_) - f_ / 4, 0, 5)
cav_m, cav_v = 0.0, 4.0
zz = cav_m / np.sqrt(1 + cav_v)
mean1 = cav_m + cav_v * Psi(zz) / np.sqrt(1 + cav_v)
var1 = cav_v - cav_v**2 * Psi(zz) * (zz + Psi(zz)) / (1 + cav_v)
print(round(mode, 3), round(1 / np.sqrt(1 / 4 + Psi(mode) * (mode + Psi(mode))), 3), round(mean1, 3), round(np.sqrt(var1), 3))
# 1.062 1.289 1.427 1.401

def post_cov(Kmat, prec):                            # (K^-1 + diag(prec))^-1 without inverting the ill-conditioned K
    r = np.sqrt(prec); Bm = np.eye(len(prec)) + r[:, None] * Kmat * r[None, :]
    return Kmat - (Kmat * r[None, :]) @ np.linalg.solve(Bm, r[:, None] * Kmat)

# Laplace with the probit likelihood: Newton's method, then the regression formulas with noise 1 / W
f = np.zeros(20)
for _ in range(30):
    g, Wp = s * Psi(s * f), Psi(s * f) * (s * f + Psi(s * f))
    f = post_cov(Kc, Wp) @ (Wp * f + g)
g, Wp = s * Psi(s * f), Psi(s * f) * (s * f + Psi(s * f))
lap_m = kt.T @ g
lap_v = 4.0 - np.einsum('ij,ij->j', kt, np.linalg.solve(Kc + np.diag(1 / Wp), kt))
Bl = np.eye(20) + np.sqrt(Wp)[:, None] * Kc * np.sqrt(Wp)[None, :]
lap_logZ = log_ndtr(s * f).sum() - 0.5 * f @ g - 0.5 * np.linalg.slogdet(Bl)[1]
lap_f = f

# expectation propagation (Rasmussen and Williams, Algorithm 3.5): sites with precisions tau and tau * mean nu
# (this loop recomputes the covariance after each site, O(n^4) per sweep; the book's rank-one updates give O(n^3))
tau, nu = np.zeros(20), np.zeros(20)
Sig, mvec = Kc.copy(), np.zeros(20)
for sweep in range(100):
    old = np.r_[tau, nu]
    for i in range(20):
        tc = 1 / Sig[i, i] - tau[i]                                    # cavity: remove site i
        cm, cv = (mvec[i] / Sig[i, i] - nu[i]) / tc, 1 / tc
        zi = s[i] * cm / np.sqrt(1 + cv)                               # tilted: cavity times Phi(y_i f_i); its moments
        hm = cm + s[i] * cv * Psi(zi) / np.sqrt(1 + cv)
        hv = cv - cv**2 * Psi(zi) * (zi + Psi(zi)) / (1 + cv)
        tau[i], nu[i] = 1 / hv - 1 / cv, hm / hv - cm / cv             # new site = matched Gaussian / cavity
        Sig = post_cov(Kc, tau); mvec = Sig @ nu
    if np.abs(np.r_[tau, nu] - old).max() < 1e-10: break
print(sweep + 1, (1 / tau).min().round(2))                             # 11 sweeps; every site variance positive
ep_m = kt.T @ np.linalg.solve(Kc + np.diag(1 / tau), nu / tau)         # regression formulas, targets nu / tau, noise 1 / tau
ep_v = 4.0 - np.einsum('ij,ij->j', kt, np.linalg.solve(Kc + np.diag(1 / tau), kt))
cav_t = 1 / np.diag(Sig) - tau
cav_m, cav_v, st_m, st_v = (mvec / np.diag(Sig) - nu) / cav_t, 1 / cav_t, nu / tau, 1 / tau
Ks_ = Kc + np.diag(st_v)
ep_logZ = (-0.5 * np.linalg.slogdet(Ks_)[1] - 0.5 * st_m @ np.linalg.solve(Ks_, st_m) + log_ndtr(s * cav_m / np.sqrt(1 + cav_v)).sum()
           + 0.5 * np.log(cav_v + st_v).sum() + ((cav_m - st_m) ** 2 / (2 * (cav_v + st_v))).sum())   # Eq. 3.65

# the exact answer, by importance sampling: f = L u with u ~ N(0, I) a priori; proposal = EP widened by 1.3
L = np.linalg.cholesky(Kc + 1e-9 * np.eye(20))
Su = np.linalg.inv(np.eye(20) + L.T @ (tau[:, None] * L)); mu_u = Su @ (L.T @ nu)
Lq = np.linalg.cholesky(1.3**2 * Su)
E = np.random.default_rng(1).normal(size=(200_000, 20))
U = mu_u + E @ Lq.T
Fs = U @ L.T
logw = (-0.5 * (U**2).sum(1) + log_ndtr(s * Fs).sum(1)) - (-0.5 * (E**2).sum(1) - np.log(np.diag(Lq)).sum())
w = np.exp(logw - logw.max())
ex_logZ = logw.max() + np.log(w.mean()); w /= w.sum()
Af = np.linalg.solve(Kc + 1e-9 * np.eye(20), kt)
fm, fv = Fs @ Af, 4.0 - np.einsum('ij,ij->j', kt, Af)                 # f* given f is Gaussian with this mean and variance
ex_p = w @ norm.cdf(fm / np.sqrt(1 + fv))
ex_f = w @ Fs
print(round(1 / (w**2).sum()))                                         # effective sample size, about 31,000

for name, fx, mm, vv, lz in (('Laplace', lap_f, lap_m, lap_v, lap_logZ), ('EP', mvec, ep_m, ep_v, ep_logZ)):
    print(name, fx[0].round(2), norm.cdf(mm / np.sqrt(1 + vv))[[0, 2]].round(3), round(lz, 2))
print('exact', ex_f[0].round(2), ex_p[[0, 2]].round(3), round(ex_logZ, 2))
# Laplace -1.59 [0.26  0.807] -13.94
# EP -1.98 [0.231 0.833] -13.83
# exact -1.98 [0.231 0.833] -13.8

Next#

A Gaussian process lets the complexity of a regression function grow with the data: one coefficient per point, and a kernel instead of a fixed basis. Clustering has the same problem in a discrete form. A mixture model fixes the number of components KK in advance and compares a few values of KK by their evidence afterwards, although new data may well reveal new clusters. The next note puts a prior on mixtures with infinitely many components, of which the data use only finitely many: the Dirichlet process.

References#

  • C. E. Rasmussen, C. K. I. Williams. Gaussian Processes for Machine Learning. MIT Press, 2006. Definition 2.1; Sections 2.1–2.2 (weight-space and function-space views; Eq. 2.25–2.26, Algorithm 2.1); Section 3.4 (the Laplace approximation); Section 3.6 (expectation propagation, Eq. 3.58 and Algorithm 3.5); Section 3.8 (Laplace against EP and MCMC); Section 4.2 (covariance functions); Sections 5.4–5.4.1 (the marginal likelihood, Eq. 5.8–5.9, multiple local optima); Section 6.6 (the relevance vector machine).
  • C. M. Bishop. Pattern Recognition and Machine Learning. Springer, 2006. Section 6.4 (Gaussian processes; 6.4.7, the connection to neural networks); Section 10.7 (expectation propagation, moment matching and EP on factor graphs).
  • K. P. Murphy. Probabilistic Machine Learning: Advanced Topics. MIT Press, 2023. Section 10.7 (expectation propagation, damping); Chapter 18 (Gaussian processes; 18.4, non-Gaussian likelihoods; 18.5, inducing points, FITC and sparse variational methods).
  • D. J. C. MacKay. The Evidence Framework Applied to Classification Networks. Neural Computation, 4(5), 720–736, 1992.
  • Cambridge University Engineering Department, 4F13 Probabilistic Machine Learning, 2025/26. Course page; lectures on Gaussian processes, the marginal likelihood, factor graphs, message passing in TrueSkill and moment matching.
  • D. P. Vetrov, D. A. Kropotov. Байесовские методы машинного обучения, textbook, part 2 (MSU, 2007), Section 12.3, Gaussian processes for regression and classification; lecture 9 of the 2015 course.