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.
Bayesian linear regression · The Laplace approximation and Bayesian classification · Kernels · The multivariate Gaussian
On this page 9
Twelve values of , with noise of standard deviation , lie between and . Fit them with Bayesian linear regression on nine Gaussian bumps centred at , with the prior on the weights. Near the data the posterior is sharp: the standard deviation of is . At it is zero to three decimals. The model is certain that , though no point lies anywhere near.
The certainty comes from the basis. The prior on the weights makes random, and any two of its values are jointly Gaussian with
because . The prior variance of is : at , and below at , 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 , one for each input , 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:
For any inputs , the vector is with . 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 throughout; a known trend can be subtracted first.
The covariance function is the whole model. It must make every matrix symmetric positive semidefinite, which is exactly the condition for a function to be a kernel. The kernels note read as an inner product of feature maps; here the same function is a covariance, and the opening model is the special case . The workhorse is the squared exponential or RBF kernel,
where is the prior variance of every and the length scale is the distance over which the function keeps its value. The correlation of and is at distance , at and at . Values a few length scales apart are nearly independent, so a draw from the prior wiggles on the scale and rarely strays beyond : at any one , does so with probability .
Unlike the nine bumps, the RBF kernel gives the prior variance at every , 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 have centres spread over the whole line with unit density. The sum over centres in the covariance becomes an integral. Completing the square in , , and the Gaussian integral over gives
the RBF kernel with and the same variance at every .
Other kernels encode other beliefs: the Matérn family rougher functions, a periodic kernel repeating ones, the linear kernel 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 with independent noise , and collect the training inputs in and the targets in . For a test input , write , , and for the vector of . The targets and are jointly Gaussian with zero mean:
where . The noise adds to the variance of each and nothing to the covariance between and , because it is independent of . The conditional of a Gaussian of given is Gaussian; is invertible for , and
(Rasmussen and Williams, 2006, Eq. 2.25–2.26).
The mean is a weighted sum of kernel functions centred at the training points, with . It is exactly the kernel ridge regression predictor with , or with penalty for the kernel scaled to unit variance, : it smooths instead of interpolating, and far from the data it returns to the prior mean 0.
The variance starts from the prior variance and subtracts what the data explain. It does not depend on at all, only on where the inputs are: small where is close to training points, back to far from them. A new noisy observation adds the noise, . 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 and with targets and , and .
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 . A Cholesky factorization costs operations, and triangular solves give the rest (Rasmussen and Williams, 2006, Algorithm 2.1):
A Gaussian process before and after the data
The figure uses the twelve values of and the length scale chosen in the next section. After the data, the posterior standard deviation is at , rises to in the middle of the gap between and , reaches at , past the last point, and is back at the prior value at , where the nine bumps claimed .
Choosing the kernel by the marginal likelihood#
The posterior depends on the hyperparameters . In the language of Bayesian model selection, each is a model, and its evidence is the probability of the targets with the function integrated out. Under the prior , so
(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 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 added to the list.
Choosing the length scale by the evidence
For the twelve points with and fixed, the terms are as follows; the constant is included in the total:
| data fit | complexity | log evidence | |
|---|---|---|---|
| 0.3 | |||
| 1.76 | |||
| 3 |
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 , is the model that explains the data and could not have explained much else.
Optimizing all three hyperparameters on the log scale gives , and , with log evidence ; scikit-learn’s GaussianProcessRegressor finds the same values. The noise level the data were generated with, , 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 to keep them positive. We need two derivatives from the matrix calculus note, and . With and ,
(Rasmussen and Williams, 2006, Eq. 5.9). The last step writes the scalar as its own trace and moves around the trace, which is cyclic. Once is known, each derivative costs . The evidence is not concave in ; the last section shows a second maximum on the same twelve points.
The cost, and inducing points#
Exact inference factorizes the matrix : time and memory, then per predictive mean and per variance. For that is about 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 inducing inputs 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,
a kernel of rank : a Bayesian linear regression on the features with the prior on the weights, since then the covariance is the projected kernel. The weight-space mean of the last section, with and , multiplied through by , is
which costs : for and , about operations. On noisy points of on with , the largest gap between this mean and the exact one on a grid shrinks fast with evenly spaced inducing points:
| 5 | 10 | 20 | |
|---|---|---|---|
| largest difference from the exact mean |
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 the process is placed on a latent function, and the label probability is a squashed version of it, with the logistic sigmoid of logistic regression. The likelihood is no longer Gaussian, and the posterior of the latent values ,
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 for the unnormalized log posterior. Its gradient is , the residuals of logistic regression with , and its Hessian is with the diagonal . The Newton step is , which simplifies to
iterated to the mode . The approximate posterior is (Rasmussen and Williams, 2006, Section 3.4). At the mode the gradient vanishes, so , and the latent value at has
The variance is the regression formula with in place of the noise: a point the model already classifies confidently has a small , a large effective noise, and little influence.
Derivation
Given , the prior conditional gives the mean and the variance . Average over with . The mean is . By the law of total variance,
where the last step is the Woodbury identity with , and .
The probability of class 1 averages the sigmoid over this Gaussian,
It has no closed form, but the probit approximation of MacKay (1992), , derived in the Laplace note, is close. The average is always less extreme than the plug-in : uncertainty about pulls the probability toward .
Why the average is less extreme
Take a mean and pair the values of the Gaussian at , which have equal density. Since is even and decreasing in , and , the pair sum never grows with , so it stays at most . It is at least 1, because whenever . Averaging over the pairs puts the probability between and ; a negative mean is the mirror image.
As an example, take twenty points evenly spaced on , labels drawn with probability , and the kernel times the RBF with . Newton’s method converges in under 20 steps.
| plug-in | probit approx. | exact average | |||
|---|---|---|---|---|---|
Far from the data, at , the latent variance is the prior variance 4 and every version is close to . 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 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 with labels , where is the standard normal distribution function; it is close to the logistic sigmoid and integrates against Gaussians in closed form, , as the Laplace note shows. One latent value with the prior and one label already shows the problem:
| centre | standard deviation | |
|---|---|---|
| Laplace: mode and curvature | ||
| exact posterior |
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, , so that the approximate posterior is
with : GP regression with pseudo-targets and noise variances , so predictions use the regression formulas with in place of . The sites are refined one at a time, each in the context of all the others (Rasmussen and Williams, 2006, Section 3.6):
- Divide site out of the marginal of , which subtracts precisions. What remains is the cavity : what the prior and the other sites say about .
- Multiply the cavity by the exact factor . This tilted distribution is non-Gaussian, but for the probit its mean and variance have closed forms.
- 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 be the standard normal density and . The moments of the tilted distribution are
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 and let with . Since , differentiating under the integral gives the tilted moments:
With , the ratio has . So and , using . Solving the two lines for and gives and . The same gives the Laplace row: , so the mode solves , at , and the curvature is .
Over Gaussians, minimizing the forward divergence means matching the mean and variance (Bishop, 2006, Section 10.7): up to terms without , it is , minimized by the tilted mean and then the tilted variance . This is the local moment matching of the variational inference note: the global 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 ; 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):
| Laplace | EP | exact | |
|---|---|---|---|
| posterior mean of at | |||
| at | |||
| at | |||
| log evidence |
Laplace is too timid: its latent means are 8% to 20% closer to zero than the exact ones, its probabilities are pulled toward , 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 , 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 , one prior factor joined to all of them, and a likelihood factor joined to each 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).
EP as message passing on a factor graph
The cavity is the message from to its likelihood factor, and the site is the message back. The exact message back would be 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 for , the label is the sign of a noisy copy of , 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 , its kernel is . Bayesian linear regression computes its predictive distribution in weight space, through the posterior precision , where the rows of are and :
The GP computes the same quantities in function space, through the matrix . The means agree because
and multiplying by on the left and on the right gives . The variance follows from the Woodbury identity, , so that (Rasmussen and Williams, 2006, Section 2.1). For straight lines, and , the kernel is , and the Code section checks that the two computations agree to .
Which view to compute in is a matter of cost: weight space costs , function space . 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 per weight is a GP with the degenerate kernel . When most 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 , and , gradient ascent on the twelve points converges to
| log evidence | ||||
|---|---|---|---|---|
| from , , | ||||
| from , , |
The second answer says that the function is flat and everything is noise. The optimizer stops at the lower bound we allow for , ; without the bound keeps falling and the evidence creeps up by less than , to . That limit is the model , whose log-likelihood is maximized by : 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 independent coordinates, is a sum of independent terms, whose relative spread shrinks like ; 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: and , small near the data and back to the prior far away.
- The evidence trades data fit against complexity; restart its optimizer.
- Exact inference costs ; inducing points bring it to .
- 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 .
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 in advance and compares a few values of 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.