From Bayesian linear regression to kernels, exact conditioning, the marginal likelihood and a working implementation. Every step derived, nothing skipped; every idea interactive.
A Gaussian process (GP) is a prior over functions that stays tractable after conditioning on data. It returns a full predictive distribution at every input, so it reports where it is uncertain, not only what it predicts. Click to add data, drag a point, or switch the kernel:
The band is ±2 posterior standard deviations. It is narrow near data and returns to the prior away from it. Drag a point vertically and watch the band.
Matérn 5/2: sample paths are twice differentiable. Same data, a rougher belief than RBF.
Matérn 1/2: the Ornstein–Uhlenbeck process; continuous, nowhere differentiable.
Periodic: the prior encodes repetition, so the model extrapolates with confidence.
Non-stationary: the length-scale grows from left to right; the function is rough on the left and smooth on the right.
The band did not move. The posterior variance depends on the observation locations, not their values (Section 5).
Prior: no data; the samples show what the kernel assumes before observing anything.
The post builds the GP from Bayesian linear regression, derives the posterior and the marginal likelihood, and ends with an implementation and its failure modes. Everything rests on eight facts about Gaussians, proved in Section 1; later derivations cite them by number. Proofs are folded and written as numbered steps, each with its justification, so that no step is left to the reader.
Notation
Plain italic letters (a, s, σn) are scalars. Bold italic lower-case letters (x, y, μ) are column vectors; the dimension is stated where each is introduced. Bold upright capitals (K, X, Σ, Φ) are matrices. I is the identity and 0 a zero vector or matrix.
Symbol
Meaning
X∈RN×D, y∈RN
training inputs (one per row), noisy observations
xi∈RD, yi∈R
the i-th input and observation
x∗∈RD, f∗=f(x∗)
a test input, the latent value there
fX=f(X)∈RN
latent function values at the training inputs
σn2
observation-noise variance
k(x,x′), K=k(X,X)
kernel, Gram matrix with entries Kij=k(xi,xj)
k∗=k(X,x∗)∈RN, k∗∗=k(x∗,x∗)
cross-covariance vector, prior variance at x∗
Ky=K+σn2I
covariance of the observations
μ∗, σ∗2
posterior mean and variance of f∗
σf2, ℓ, θ
kernel amplitude, length-scale, all hyperparameters
ϕ(x)∈RM, Φ∈RN×M
feature map, design matrix with rows ϕ(xi)⊤
w∼N(0,Σw)
weights and their prior
P, h
a precision matrix and a linear coefficient (information form)
All covariance matrices are symmetric and positive definite unless stated. N(a∣μ,Σ) is the Gaussian density in a∈RD:
N(a∣μ,Σ)=(2π)−D/2∣Σ∣−1/2exp(−21(a−μ)⊤Σ−1(a−μ)).
1. Gaussian facts you will need
Every result in this post is a sequence of the eight facts below.
The first line multiplies out the product. The second uses μ⊤Σ−1a=a⊤Σ−1μ, which holds because μ⊤Σ−1a is a scalar, a scalar equals its own transpose, and (Σ−1)⊤=Σ−1. So the coefficient of the quadratic term is the precisionΣ−1, and the coefficient of the linear term is Σ−1μ. The converse is the workhorse of every Bayesian calculation below.
Lemma 1 (Completing the square)
Let P be symmetric positive definite and h a vector. For all a,
−21a⊤Pa+a⊤h=−21(a−P−1h)⊤P(a−P−1h)+21h⊤P−1h.
Consequently, a density with p(a)∝exp(−21a⊤Pa+a⊤h) is N(P−1h,P−1).
Reasons, line by line: (1) multiply out; (2) substitute the three identities of Step 1; (3) h⊤a=a⊤h, the same scalar.
Step 3. Rearrange. Add 21h⊤P−1h to both sides of Step 2. This is the identity.
Step 4. The consequence. The term 21h⊤P−1h does not contain a, so it is absorbed into the proportionality constant:
p(a)∝exp(−21(a−a0)⊤P(a−a0)).
Step 5. Identify the density. The right-hand side of Step 4 is the density of N(a0,P−1) without its constant. Two densities that are proportional and both integrate to one are equal, so p(a)=N(a∣P−1h,P−1).
Linear maps and sums: convolution
Lemma 2 (Affine transformation)
If a∼N(μ,Σ) and b=Ca+d for a fixed matrix C and vector d, then b∼N(Cμ+d,CΣC⊤).
Proof
Step 1. The mean. Expectation is linear, and C, d are constants:
E[b]=E[Ca+d]=CE[a]+d=Cμ+d.
Step 2. The centred variable. Subtract the mean:
b−E[b]=Ca+d−Cμ−d=C(a−μ).
Step 3. The covariance.
Cov[b]=E[(b−E[b])(b−E[b])⊤]=E[C(a−μ)(a−μ)⊤C⊤]=CE[(a−μ)(a−μ)⊤]C⊤=CΣC⊤.definitionStep 2, and (Cu)⊤=u⊤C⊤linearity
Step 4. The distribution is Gaussian. A distribution is determined by its characteristic function φ(t)=E[eit⊤(⋅)], and for a∼N(μ,Σ) it is φa(t)=exp(it⊤μ−21t⊤Σt). Then
which is the characteristic function of N(Cμ+d,CΣC⊤).
Lemma 3 (Sum of independent Gaussians (convolution))
If a∼N(μ1,Σ1) and b∼N(μ2,Σ2) are independent, then a+b∼N(μ1+μ2,Σ1+Σ2). Equivalently, the convolution of two Gaussian densities is a Gaussian density:
Step 1. Stack the two variables. Independent Gaussians are jointly Gaussian, with zero cross-covariance:
[ab]∼N([μ1μ2],[Σ100Σ2]).
Step 2. Write the sum as a linear map. With C=[II],
a+b=[II][ab].
Step 3. Apply Lemma 2 for the mean.C[μ1μ2]=μ1+μ2.
Step 4. Apply Lemma 2 for the covariance. Multiply the blocks:
[II][Σ100Σ2][II]=[Σ1Σ2][II]=Σ1+Σ2.
Step 5. Why this is a convolution. The event a+b=z happens for every pair (a,b=z−a). Summing the probability of all such pairs, and using independence to factor the joint density,
pa+b(z)=∫pa(a)pb(z−a)da,
which is the convolution integral in the statement. Steps 3 and 4 evaluate it.
Example 1 (The convolution integral, computed by hand in one dimension)
Take independent scalars a∼N(μ1,s12) and b∼N(μ2,s22). We compute p(z)=∫N(a∣μ1,s12)N(z−a∣μ2,s22)da directly, without Lemma 2.
Step 1. Write out the integrand. Let r=z−μ2, so that (z−a)−μ2=r−a:
Step 1. Add the exponents. A product of exponentials is the exponential of the sum. Expanding each exponent as in “Reading a Gaussian off its exponent”,
Step 2. Read off the information form. Step 1 is −21a⊤Pa+a⊤h+const with
P=Σ1−1+Σ2−1,h=Σ1−1μ1+Σ2−1μ2.
Step 3. Complete the square (Lemma 1). As a function of a, the product is proportional to N(a∣P−1h,P−1)=N(a∣μc,Σc). Call the constant of proportionality Z.
Step 4. Find Z by integrating both sides over a. The right-hand side integrates to Z, since a density integrates to one:
Z=∫N(a∣μ1,Σ1)N(a∣μ2,Σ2)da.
Step 5. Swap the arguments of the second factor. The Gaussian density depends on its two arguments only through (a−μ2)⊤Σ2−1(a−μ2), which is unchanged when a and μ2 swap. So N(a∣μ2,Σ2)=N(μ2∣a,Σ2) and
Z=∫N(a∣μ1,Σ1)N(μ2∣a,Σ2)da.
Step 6. Recognise a convolution. Consider the two-stage experiment a∼N(μ1,Σ1), then v=a+u with independent u∼N(0,Σ2). Given a, v∼N(a,Σ2), so the integral in Step 5 is ∫p(a)p(v∣a)da=p(v) evaluated at v=μ2.
Note (Product, convolution and mixture are different operations)
Product of two densities in the same variable (Lemma 4): precisions add, so the result is narrower than either factor. This is Bayes’ rule combining two sources of information. It sharpens.
Convolution, the density of a sum of independent variables (Lemma 3): covariances add, so the result is wider. This is adding noise. It blurs.
Mixtureπ1N(μ1,Σ1)+π2N(μ2,Σ2), a weighted sum of densities: not Gaussian in general (it can have two modes).
Steps 4 to 7 of Lemma 4 link the first two: the normaliser of a product is a convolution evaluated at a point.
Conditioning
Lemma 5 (Gaussian conditioning)
If
[ab]∼N([μaμb],[ΣaaΣbaΣabΣbb])
with Σaa invertible, then
b∣a∼N(μb+ΣbaΣaa−1(a−μa),Σbb−ΣbaΣaa−1Σab).
Proof
Step 1. Remove from b the part predictable from a. Define
G=ΣbaΣaa−1,r=b−Ga.
Step 2. The residual is uncorrelated with a. Covariance is linear in each argument:
Step 3. Uncorrelated implies independent here. The pair (r,a) is a linear map of (a,b):
[ra]=[−GII0][ab],
so it is jointly Gaussian (Lemma 2). By Step 2 its covariance is block diagonal, so its density factorises into a function of r times a function of a. Hence r and a are independent, and conditioning on a does not change the distribution of r.
Step 4. The mean of r.E[r]=μb−Gμa.
Step 5. The covariance of r. Expand Cov[b−Ga] by bilinearity, then substitute G:
Here G⊤=(Σaa−1)⊤Σba⊤=Σaa−1Σab, because a covariance matrix is symmetric, which makes Σaa−1 symmetric and Σba⊤=Σab.
Step 6. Put b back.b=r+Ga. Given a, the term Ga is a constant, and adding a constant to a Gaussian shifts its mean only. So b∣a is Gaussian with the covariance of Step 5 and mean
μb−Gμa+Ga=μb+ΣbaΣaa−1(a−μa).
Matrix identities
Lemma 6 (Push-through and Woodbury)
Let Σw be M×M and positive definite, Φ be N×M, σn2>0, and write
Step 2. Insert an identity. Write Φ⊤=Σw−1ΣwΦ⊤ in the second term, then factor ΣwΦ⊤ out on the right:
σn−2Φ⊤G=(σn−2Φ⊤Φ+Σw−1)ΣwΦ⊤=AΣwΦ⊤.
Step 3. Multiply by the inverses. Both A and G are positive definite, hence invertible. Multiply Step 2 by A−1 on the left and G−1 on the right:
σn−2A−1Φ⊤=ΣwΦ⊤G−1.
Woodbury.
Step 4. Name the candidate. Let R=Σw−ΣwΦ⊤G−1ΦΣw. For square matrices, AR=I implies R=A−1, so it suffices to compute AR.
Step 5. Multiply out.
AR=AΣw−AΣwΦ⊤G−1ΦΣw=(σn−2Φ⊤ΦΣw+I)−AΣwΦ⊤G−1ΦΣw=σn−2Φ⊤ΦΣw+I−σn−2Φ⊤GG−1ΦΣw=σn−2Φ⊤ΦΣw+I−σn−2Φ⊤ΦΣw=I.definition of AStep 2: AΣwΦ⊤=σn−2Φ⊤GGG−1=I
Lemma 7 (Derivatives of the inverse and the log-determinant)
For a symmetric positive definite K(θ) that depends smoothly on a scalar θ,
∂θ∂K−1=−K−1∂θ∂KK−1,∂θ∂log∣K∣=tr(K−1∂θ∂K).
Proof
Write ∂ for ∂/∂θ.
Inverse.
Step 1. Differentiate the identity KK−1=I with the product rule; the right-hand side is constant:
(∂K)K−1+K(∂K−1)=0.
Step 2. Solve for ∂K−1. Move the first term across and multiply on the left by K−1:
∂K−1=−K−1(∂K)K−1.
Log-determinant.
Step 3. Perturb and factor. For a small ϵ and E=∂K, K(θ+ϵ)=K+ϵE+O(ϵ2)=K(I+ϵK−1E)+O(ϵ2).
Step 4. Take the log-determinant. The determinant of a product is the product of determinants:
log∣K+ϵE∣=log∣K∣+log∣I+ϵK−1E∣.
Step 5. Use eigenvalues. Let λ1,…,λN be the eigenvalues of K−1E (they are real: the matrix is similar to the symmetric K−1/2EK−1/2). The eigenvalues of I+ϵK−1E are 1+ϵλi, and a determinant is the product of the eigenvalues:
using log(1+u)=u+O(u2) and that the trace is the sum of the eigenvalues.
Step 6. Take the limit. Subtract log∣K∣, divide by ϵ and let ϵ→0: ∂log∣K∣=tr(K−1∂K).
Putting it together: the linear-Gaussian model
Lemma 4 multiplies two densities in the same variable. The product that appears most often in practice has two different variables: a prior over a hidden x, times a likelihood for an observation y whose mean depends linearly on x. Bayesian linear regression, the GP and every step of a Kalman filter are this product.
Step 5. The marginal of y. Selecting a block of a Gaussian vector is the linear map [0I], so by Lemma 2 the marginal keeps the bottom block of the mean and the bottom-right block of the covariance: p(y)=N(Cμx+d,CΣxC⊤+S).
Step 6. The conditional of x. Apply Lemma 5 with a=y and b=x, reading the blocks from Step 4:
Σaa=CΣxC⊤+S,Σba=ΣxC⊤,Σab=CΣx,Σbb=Σx.
This gives the moment form.
Step 7. Joint equals marginal times conditional.p(y∣x)p(x)=p(x,y)=p(y)p(x∣y), which is the identity in the statement.
Information form: treat the likelihood as a function of x.
Step 8. Expand the likelihood exponent in x. Write e=y−d. Exactly as in Step 3 of Proposition 1 below,
As a function of x, the likelihood is a Gaussian in information form with precision C⊤S−1C and linear coefficient C⊤S−1e.
Step 9. Expand the prior exponent (“Reading a Gaussian off its exponent”): −21x⊤Σx−1x+x⊤Σx−1μx+const.
Step 10. Add and complete the square. The log of the product is −21x⊤Px+x⊤h+const with P=Σx−1+C⊤S−1C and h=Σx−1μx+C⊤S−1e. Lemma 1 gives the information form.
Step 11. The two forms agree. Steps 6 and 10 describe the same density p(x∣y), so their means and covariances are equal. (Equating the two covariances is the Woodbury identity in general form; Lemma 6 is the case Σx=Σw, C=Φ, S=σn2I.)
Two special cases are worth seeing at once. With C=I and d=0, Lemma 8 is Lemma 4: the same-variable product is the case where the observation is a noisy copy of the hidden variable. With C=Φ, it is Bayesian linear regression (Section 2).
Remark (Two coordinate systems for one Gaussian)
A Gaussian can be stored in moment form(μ,Σ) or in information form(h,P)=(Σ−1μ,Σ−1). Each makes a different half of the toolkit trivial:
Moment form. Marginalising is reading off blocks (Step 5 above). Sums of independent variables add covariances (Lemma 3). Conditioning needs an inverse (the Schur complement of Lemma 5).
Information form. Products in the same variable add h and P (Lemma 4). Conditioning is reading off blocks: fix a in the joint exponent −21[a;b]⊤P[a;b], and the term quadratic in b is −21b⊤Pbbb, so the conditional precision is the block Pbb. Marginalising needs the inverse.
The same split explains why zeros mean different things: a zero in Σ is marginal independence, a zero in P is conditional independence given all other variables. Sparse precisions are what make Gaussian Markov random fields, and information filters for large spatial fields, cheap.
The characteristic function gives a third view. For independent a and b, φa+b(t)=E[eit⊤a]E[eit⊤b]=φa(t)φb(t), and multiplying two Gaussian characteristic functions adds the exponents: exp(it⊤(μ1+μ2)−21t⊤(Σ1+Σ2)t). That is Lemma 3 in one line. Convolution of densities is multiplication of their Fourier transforms, and a Gaussian keeps its shape in both domains, which is why both operations stay Gaussian.
Note (When to think in precision, when in covariance)
Covariance answers a global question; precision answers a local one.Σij is how xi and xj co-vary when every other variable is unknown (marginalised out). Pij describes how xi and xj relate when every other variable is known (held fixed). Concretely, 1/Pii is the variance of xi given all the others (the conditional precision of one variable is its diagonal block, by the remark above), and −Pij/PiiPjj is their partial correlation.
A worked example. Take a random walk: x1∼N(0,1), x2=x1+e2, x3=x2+e3, with independent e2,e3∼N(0,1). Then
Σ=111122123,P=Σ−1=2−10−12−10−11.
(Check: multiply them; every row of Σ times every column of P gives 1 on the diagonal and 0 off it.) The covariance is dense: x1 and x3 are correlated, because x3 inherits x1. The precision has P13=0: once x2 is known, x1 tells you nothing more about x3. The precision shows the model’s wiring (each variable talks only to its neighbours); the covariance shows its consequences.
Rules of thumb.
Information adds in precision; noise adds in covariance. Combining evidence (multiplying likelihoods, Bayes’ rule, Lemma 4) adds precisions. Adding independent noise or propagating forward in time (sums, Lemma 3) adds covariances. A Kalman filter does both: the predict step adds process noise to Σ, the update step adds measurement information to P.
Local models are sparse in precision. Markov chains, PDE stencils, spatial grids and graphs couple each variable to a few neighbours, so P is sparse even though Σ is dense. Matérn-21 GPs on sorted 1-D inputs have tridiagonal precision, as in the example; Matérn fields in two and three dimensions have sparse precision through the SPDE link (Lindgren, Rue and Lindström, 2011). Kernels, in contrast, specify Σ directly, which is why GP code works in covariance form.
The extremes live on opposite sides. “Know nothing” is P=0, which has no covariance (Σ=∞); “know exactly” is Σ=0, which has no precision. A flat prior or a likelihood that constrains only some directions of x (a singular C⊤S−1C in Lemma 8) is natural in precision form; noise-free interpolation and hard constraints are natural in covariance form.
Invert the smaller matrix. The moment form of Lemma 8 inverts a matrix the size of y, the information form one the size of x. Section 3 is this choice: function space (N×N) versus weight space (M×M).
2. Bayesian linear regression
We observe {(xi,yi)}i=1N with
yi=f(xi)+εi,εi∼iidN(0,σn2),f(x)=ϕ(x)⊤w.
Stacking the N equations, y=Φw+ε with ε∼N(0,σn2I), so the likelihood is p(y∣X,w)=N(y∣Φw,σn2I). Least squares returns one w and hides how many others fit almost as well; the Bayesian treatment keeps a distribution over w, starting from the prior w∼N(0,Σw).
Proposition 1 (Posterior over weights)
p(w∣X,y)=N(w∣σn−2A−1Φ⊤y,A−1),A=σn−2Φ⊤Φ+Σw−1.
Proof
Step 1. Bayes’ rule. The evidence p(y∣X) does not depend on w:
p(w∣X,y)=p(y∣X)p(y∣X,w)p(w)∝p(y∣X,w)p(w).
Step 2. Take logs. Keep only the terms that depend on w:
Step 5. Complete the square (Lemma 1 with P=A): the posterior is N(A−1h,A−1)=N(σn−2A−1Φ⊤y,A−1).
Proposition 2 (Predictive distribution)
For f∗=ϕ∗⊤w with ϕ∗=ϕ(x∗),
p(f∗∣x∗,X,y)=N(σn−2ϕ∗⊤A−1Φ⊤y,ϕ∗⊤A−1ϕ∗).
Proof
Step 1. The posterior over w is N(wˉ,A−1) with wˉ=σn−2A−1Φ⊤y (Proposition 1).
Step 2. f∗ is a linear map of w.f∗=ϕ∗⊤w is Lemma 2 with the 1×M matrix C=ϕ∗⊤ and d=0.
Step 3. The mean.Cwˉ=ϕ∗⊤wˉ=σn−2ϕ∗⊤A−1Φ⊤y.
Step 4. The variance.CA−1C⊤=ϕ∗⊤A−1ϕ∗.
Remark (One lemma does it all)
Propositions 1 and 2 are Lemma 8 with x=w, μx=0, Σx=Σw, C=Φ, d=0 and S=σn2I. Its information form is Proposition 1 (A is the posterior precision). Its marginal gives, at no extra cost, the evidence p(y∣X)=N(0,ΦΣwΦ⊤+σn2I), which Section 7 will recognise as N(0,Ky).
A is a precision: the prior contributes Σw−1 and each observation adds σn−2ϕ(xi)ϕ(xi)⊤, so uncertainty can only shrink as data arrive. In the figure the input is a scalar x and ϕ(x)=[1,x]⊤; each line is a posterior sample of w and the band is ±2 predictive standard deviations.
N = 0 (prior) · Click to add observations.
The samples agree near the data and disagree away from it, which is what we want. The limitation is the model class: no amount of data makes a line fit a curve. The next section removes that limitation without losing tractability.
3. From weight space to function space
Rewrite the predictive distribution so that the features appear only through inner products.
Proposition 3 (Kernel form of the predictive)
Define k(x,x′)=ϕ(x)⊤Σwϕ(x′). Then the predictive mean and variance of Proposition 2 are
That is, ΦΣwΦ⊤=K, ΦΣwϕ∗=k∗, and the matrix G of Lemma 6 is K+σn2I.
Step 2. One transpose we need. Because Σw is symmetric,
ϕ∗⊤ΣwΦ⊤=(ΦΣw⊤ϕ∗)⊤=(ΦΣwϕ∗)⊤=k∗⊤.
Step 3. The mean.
μ∗=ϕ∗⊤(σn−2A−1Φ⊤)y=ϕ∗⊤ΣwΦ⊤G−1y=k∗⊤(K+σn2I)−1yProposition 2push-through (Lemma 6)Steps 1 and 2.
Step 4. The variance.
σ∗2=ϕ∗⊤A−1ϕ∗=ϕ∗⊤Σwϕ∗−ϕ∗⊤ΣwΦ⊤G−1ΦΣwϕ∗=k∗∗−k∗⊤(K+σn2I)−1k∗Proposition 2Woodbury (Lemma 6)Steps 1 and 2.
The features no longer appear; only k does. This is the kernel trick: any feature space, including an infinite-dimensional one, can be used as long as k can be evaluated. Notice also the size of the matrix being inverted: A is M×M (number of features), K+σn2I is N×N (number of data points). The function-space form is the one to use when features outnumber data.
Example 2 (Infinitely many Gaussian features give the RBF kernel)
In one dimension, let ϕc(x)=exp(−2s2(x−c)2) for every centre c∈R, with independent weights of equal prior variance. A sum over features becomes an integral over centres:
The first factor does not depend on c and moves outside the integral.
Step 6. Do the remaining integral. Substitute c=cˉ+st, so dc=sdt, and use ∫−∞∞e−t2dt=π:
∫−∞∞exp(−s2(c−cˉ)2)dc=s∫−∞∞e−t2dt=sπ.
Step 7. Match the RBF form.4s2(x−x′)2=2ℓ2(x−x′)2 exactly when ℓ2=2s2.
Increase the number of features M; the random functions converge to samples from the RBF GP.
Faint curves (bottom) are the individual features, shown up to $M = 16$.
4. Gaussian processes
The kernel form suggests placing the prior directly on functions.
Definition 1 (Gaussian process)
A Gaussian process is a collection of random variables, any finite subset of which is jointly Gaussian. A GP over f:X→R is specified by a mean function and a kernel, f∼GP(m,k), where m(x)=E[f(x)] and k(x,x′)=Cov[f(x),f(x′)]. For any inputs X,
fX=f(X)∼N(m(X),K).
Definition 2 (Positive-definite kernel)
A symmetric function k:X×X→R is positive definite if, for every finite set {xi}i=1N and every c∈RN, ∑i,jcicjk(xi,xj)≥0; that is, every Gram matrix is positive semidefinite. Exactly these functions are covariance functions of GPs.
We take m≡0 from now on; a known trend can be subtracted first.
Sampling a function on a grid takes three steps:
Evaluate the Gram matrix K on the grid and factor it as K=LL⊤ (Cholesky; L is lower triangular).
Draw z∼N(0,I), one independent standard normal per grid point.
Set fX=Lz. By Lemma 2 it is Gaussian with mean L0=0 and covariance LIL⊤=K, as required.
Note
Smooth kernels make K numerically singular on fine grids (nearby columns are almost identical). Add a small jitter, K+ϵI with ϵ≈10−6, before factoring.
5. Kernels encode assumptions
The kernel determines which functions are plausible a priori. Select a kernel to see three prior samples; the inset plots k(0.5,x).
The squared-exponential (RBF) kernel is
kRBF(x,x′)=σf2exp(−2ℓ2∥x−x′∥2).
Its sample paths are infinitely differentiable. The length-scale ℓ sets the distance over which values decorrelate; σf2 is the prior variance at every input.
The Matérn family adds a smoothness parameter ν>0. With r=∥x−x′∥, the three common members are
Sample paths are ⌈ν⌉−1 times mean-square differentiable, and ν→∞ recovers the RBF. Physical signals are rarely infinitely smooth, so Matérn is the usual default. The periodic kernel encodes exact repetition, the linear kernel k(x,x′)=x⊤x′ recovers Bayesian linear regression (Section 2), and sums and products build structure: a sum models superposed effects (a trend plus variation), a product modulates one structure by another (a slowly changing periodic pattern).
Proposition 4 (Closure under sums and products)
If k1 and k2 are positive definite, so are k1+k2 and k1k2.
Proof
Step 1. Reduce to matrices. Fix any inputs x1,…,xN and let K1, K2 be the Gram matrices of k1, k2. Both are positive semidefinite by assumption. We must show that the Gram matrices of k1+k2 and k1k2 are too.
Sum.
Step 2. The Gram matrix of k1+k2 is K1+K2, and for any c,
c⊤(K1+K2)c=≥0c⊤K1c+≥0c⊤K2c≥0.
Product.
Step 3. The Gram matrix of k1k2 has entries k1(xp,xq)k2(xp,xq): it is the elementwise (Hadamard) product K1∘K2.
Step 4. Decompose each factor. Symmetric positive semidefinite matrices have eigendecompositions with non-negative eigenvalues:
K1=i∑λiuiui⊤,K2=j∑κjvjvj⊤,λi,κj≥0.
Step 5. Hadamard product of two rank-one matrices. Entry (p,q) of (uu⊤)∘(vv⊤) is upuqvpvq=(upvp)(uqvq), which is entry (p,q) of (u∘v)(u∘v)⊤. So
(uu⊤)∘(vv⊤)=(u∘v)(u∘v)⊤.
Step 6. Expand. The Hadamard product is linear in each factor, so by Steps 4 and 5
K1∘K2=i,j∑λiκj(ui∘vj)(ui∘vj)⊤.
Step 7. Conclude. For any c, c⊤(K1∘K2)c=∑i,jλiκj((ui∘vj)⊤c)2≥0, a sum of non-negative terms. (This is the Schur product theorem.)
A kernel is stationary if k(x,x′)=κ(x−x′); every example above except the linear kernel is stationary.
Theorem 1 (Bochner)
A continuous function κ:RD→R defines a positive-definite stationary kernel if and only if it is the Fourier transform of a finite non-negative measure μ:
κ(τ)=∫RDeiω⊤τμ(dω).
A stationary kernel is therefore a spectrum. The RBF has a Gaussian spectral density; Matérn has heavier, Student-t-like tails. Sampling frequencies from μ gives random Fourier features, and the stationarity assumption is what From Fourier to wavelets relaxes.
6. Conditioning
We now derive the posterior directly in function space, with no features.
Step 1. The joint prior. By Definition 1, fX and f∗ are jointly Gaussian, with every covariance given by the kernel:
[fXf∗]∼N(0,[Kk∗⊤k∗k∗∗]).
Step 2. Add the noise. The observations are y=fX+ε, with ε∼N(0,σn2I) independent of f. The test value receives no noise, so
[yf∗]=[fXf∗]+[ε0],[ε0]∼N(0,[σn2I0⊤00]).
Step 3. Sum of independent Gaussians (Lemma 3): the covariances add.
For a noisy test observation y∗=f∗+ε∗, Lemma 3 adds σn2 to the variance.
These are the formulas of Proposition 3, obtained here without any reference to features. The two derivations are two views of one model:
Weight space and function space meet through the kernel.Remark (The mean is a weighted sum of kernels)
With α=Ky−1y, the posterior mean at any x is μ(x)=k(X,x)⊤α=∑i=1Nαik(xi,x): one kernel-shaped bump per observation. This is the kernel ridge regression predictor with regulariser σn2, an instance of the representer theorem.
Remark (The variance does not depend on y)
σ∗2 involves only X and x∗, never y. The uncertainty after an experiment is known before the experiment is run, which is why GPs are used to decide where to measure next (active learning, Bayesian optimisation).
Remark (The posterior is a GP)
Applying Step 4 to any finite set of test inputs at once shows f∣y∼GP(μ,kpost) with kpost(x,x′)=k(x,x′)−k(X,x)⊤Ky−1k(X,x′). Conditioning can be repeated as data arrive.
Sampling the posterior: Matheron’s rule
Proposition 5 describes the posterior as a distribution. To draw a posterior sample at N∗ test inputs from it, the obvious route is to compute the N∗×N∗ posterior covariance and factor it, at cost O(N∗3); the result is a vector of values, not a function. Matheron’s rule conditions samples instead.
Let f∼GP(0,k) and ε∼N(0,σn2I) be independent. For observed data y, the random function
(f∣y)(⋅)=f(⋅)+k(⋅,X)Ky−1(y−fX−ε)
is distributed as the GP posterior. In words: draw a prior function, simulate the observations it would have produced, and correct the function by the kernel-weighted mismatch with the real data.
Proof
Step 1. Fix test inputs. A GP is determined by its finite-dimensional distributions, so it suffices to check any finite set of test inputs X∗. Write K∗X=k(X∗,X), K∗∗=k(X∗,X∗), and let b=f(X∗).
Step 2. Name the simulated observation. Let a=fX+ε: what the prior sample would have produced as data. By Steps 1 to 3 of this section (with many test inputs instead of one), (a,b) is jointly Gaussian with zero mean and
Σaa=Ky,Σba=K∗X,Σbb=K∗∗.
Step 3. Write the rule at the test inputs. With G=ΣbaΣaa−1=K∗XKy−1, the rule evaluated at X∗ is
b~=b+G(y−a).
Here y is the real data, a fixed vector; a and b are random.
Step 4. Regroup. Collect the random terms:
b~=r(b−Ga)+Gy.
r is exactly the residual of Lemma 5, Step 1.
Step 5. The law of the residual. By Lemma 5, Steps 4 and 5 (with zero means), r∼N(0,K∗∗−K∗XKy−1K∗X⊤).
Step 6. Add the constant.Gy is fixed, so it shifts the mean only:
b~∼N(K∗XKy−1y,K∗∗−K∗XKy−1K∗X⊤).
Step 7. Compare. This is the posterior at X∗ (Proposition 5, applied to all test inputs at once). Since X∗ was arbitrary, the two processes have the same finite-dimensional distributions, hence the same law.
The proof is the conditioning proof of Lemma 5 read backwards. There, the residual r is independent of the data, so conditioning only moves its mean; here, we build r from a prior sample and add the data’s contribution Gy by hand.
Remark (Why this matters)
The sample is a function. The prior sample f(⋅) can be drawn once as an explicit function, for example with random Fourier features from Bochner’s theorem (Section 5), and the correction k(⋅,X)v with v=Ky−1(y−fX−ε) is a fixed weighted sum of kernels. The result can be evaluated anywhere, at cost linear in the number of test points, and differentiated. Thompson sampling in Bayesian optimisation needs exactly this: maximise one posterior sample.
Prior and data are decoupled. The prior term can use a cheap approximation (random features), while the update uses the exact kernel or inducing points. Wilson et al. (2020) call this decoupled sampling; it keeps the error where the data are, and stays accurate far from them, where random-feature posteriors alone break down.
Uncertainty through a simulator. Push each pathwise sample through any downstream computation (a PDE solver, a planner, a cost function) and the outputs are samples of the propagated uncertainty, with no further Gaussian algebra.
The rule comes from geostatistics, where Matheron used it for conditional simulation of ore deposits. Cosmology rediscovered it for constrained realisations of the early universe (Hoffman and Ribak, 1991). James T. Wilson, Viacheslav Borovitskiy, Alexander Terenin, Peter Mostowsky and Marc Deisenroth brought it to machine learning (ICML 2020; JMLR 2021).
The animation uses this rule. Six prior functions are drawn once. As each observation arrives, every curve is updated by Matheron’s rule, so you can follow each one as it bends towards the data; the band is the exact posterior of Proposition 5.
7. The marginal likelihood
The hyperparameters θ=(σf,ℓ,σn) are chosen by maximising the probability of the data with f integrated out.
Step 2. Recognise a sum. This is the density of y=fX+ε with independent fX∼N(0,K) and ε∼N(0,σn2I), the convolution of prior and noise.
Step 3. Apply Lemma 3.y∼N(0,K+σn2I)=N(0,Ky).
Step 4. Take the log of the density in Notation with D=N:
logN(y∣0,Ky)=−2Nlog2π−21log∣Ky∣−21y⊤Ky−1y.
Route 2: as a product (a check, and a bonus).
Step 5. Swap arguments in the likelihood. By the symmetry in Step 5 of Lemma 4, N(y∣fX,σn2I)=N(fX∣y,σn2I), so the integrand of Step 1 is a product of two Gaussian densities in the same variablefX.
Step 6. Apply Lemma 4 with (μ1,Σ1)=(y,σn2I) and (μ2,Σ2)=(0,K):
Step 7. Integrate over fX. The second factor integrates to one, leaving p(y∣X)=N(y∣0,Ky): the same answer as Step 3. (Route 2 is Lemma 8 with x=fX, C=I, d=0.)
Remark (Bayes’ rule in one identity)
Route 2 delivers more than the evidence. Prior times likelihood equals evidence times posterior, so the factor N(fX∣μc,Σc) in Step 6 is the posterior over the latent values at the training inputs, with Σc=(K−1+σn−2I)−1 and μc=σn−2Σcy. The product of Gaussians is Bayes’ rule: its shape is the posterior and its normaliser is the marginal likelihood.
The two terms pull in opposite directions. A short length-scale fits the data closely (large data-fit term), but makes Ky close to diagonal with a large determinant (large penalty). The maximiser balances them. Move the slider:
Remark (Why the marginal likelihood generalises)
By the chain rule of probability,
logp(y∣X,θ)=n=1∑Nlogp(yn∣y1,…,yn−1,X,θ).
Each term scores the prediction of an observation that has not yet been conditioned on. The marginal likelihood is therefore a sum of one-step-ahead predictive scores, a built-in measure of generalisation: an overly flexible kernel fits each point once it is seen, but predicts the next one poorly. (This reading follows Marc Deisenroth’s GP lectures.)
Proposition 8 (Gradient)
With α=Ky−1y,
∂θj∂logp(y∣X,θ)=21tr((αα⊤−Ky−1)∂θj∂Ky).
Proof
Write ∂ for ∂/∂θj. The constant −2Nlog2π has zero derivative.
Step 1. Differentiate the data-fit term (Lemma 7, inverse):
Optimise over logℓ, logσf and logσn to keep them positive. The objective is non-convex; distinct optima correspond to distinct explanations of the data (a short length-scale with low noise, or a long length-scale with high noise), so use several restarts.
8. Implementation
Never form Ky−1 explicitly. Factor Ky=LL⊤ once, then every quantity is a triangular solve:
α=L−⊤(L−1y), since Ky−1=(LL⊤)−1=L−⊤L−1.
μ∗=k∗⊤α.
v=L−1k∗, so that k∗⊤Ky−1k∗=k∗⊤L−⊤L−1k∗=v⊤v and σ∗2=k∗∗−v⊤v.
log∣Ky∣=2∑ilogLii, since ∣LL⊤∣=∣L∣2 and the determinant of a triangular matrix is the product of its diagonal.
import numpy as npfrom scipy.linalg import cho_solve, solve_triangulardef rbf(A, B, ell=0.2, sf=1.0): d2 = ((A[:, None, :] - B[None, :, :]) ** 2).sum(-1) return sf**2 * np.exp(-0.5 * d2 / ell**2)def gp_predict(X, y, Xs, ell=0.2, sf=1.0, sn=0.1, jitter=1e-8): N = len(X) L = np.linalg.cholesky(rbf(X, X, ell, sf) + (sn**2 + jitter) * np.eye(N)) alpha = cho_solve((L, True), y) Ks = rbf(X, Xs, ell, sf) # N x N* mu = Ks.T @ alpha V = solve_triangular(L, Ks, lower=True) var = sf**2 - (V**2).sum(0) # diagonal of the posterior covariance lml = -0.5 * y @ alpha - np.log(np.diag(L)).sum() - 0.5 * N * np.log(2 * np.pi) return mu, var, lml
Note (Practical defaults)
Adapted from Marc Deisenroth’s lectures:
Standardise inputs and targets; initialise ℓ≈0.5 and σf≈1.
Initialise the noise high, σn≈0.5σf, even for clean data; the optimiser moves more easily and can reduce it.
Use random restarts.
If Cholesky fails repeatedly, penalise large signal-to-noise ratios σf/σn rather than only increasing the jitter.
Cost.O(N3) time and O(N2) memory. Standard routes to scale:
Stationarity. A single length-scale is often wrong for real signals; non-stationary kernels, input warping and multi-scale features address this.
High-dimensional inputs. Euclidean distances between raw inputs are rarely meaningful; deep kernels and deep GPs learn a representation.
Function-valued inputs and outputs. Mapping one function to another (for example, PDE coefficients to solutions) requires operator-valued kernels, the subject of the next post in this series.
Questions
Question 1
Why does the posterior variance not depend on the observed values y?
Answer
In Lemma 5 the conditional covariance Σbb−ΣbaΣaa−1Σab involves only covariances, and for a GP these depend only on the inputs.
Question 2
You multiply two Gaussian densities in the same variable and, separately, add two independent Gaussian variables. Which result is narrower, and why?
Answer
The product is narrower: its precision is the sum of the two precisions (Lemma 4), so its covariance is smaller than either. The sum is wider: its covariance is the sum of the two covariances (Lemma 3).
Question 3
Which kernel reduces a GP to Bayesian linear regression with features ϕ?
Answer
k(x,x′)=ϕ(x)⊤Σwϕ(x′) (Proposition 3). With ϕ(x)=x and Σw=I this is the linear kernel.
Question 4
The optimiser returns a very short length-scale and near-zero noise. What has happened, and what should you check?
Answer
The model interpolates the data and treats noise as signal. Compare with the optimum at a longer length-scale and larger noise, place a prior on σn, and use several initialisations.
Question 5
How do you multiply N(y∣Cx+d,S) by N(x∣μx,Σx), when the two densities are in different variables?
Answer
Read the product as a joint p(x,y), compute the joint by stacking (Lemma 2), then factor it the other way as p(y)p(x∣y) (Lemma 5). Alternatively, read the likelihood as an information-form Gaussian in x and add precisions. Both routes are Lemma 8.
Question 6
Matheron’s rule never computes the posterior covariance. Where does it come from?
Answer
From the prior sample itself. The residual b−Ga of a prior draw already has the posterior covariance (Lemma 5, Step 5); the rule only adds the deterministic shift Gy.
Y. Hoffman, E. Ribak. Constrained realizations of Gaussian fields: a simple algorithm. The Astrophysical Journal Letters, 1991.
A. Doucet. A note on efficient conditional simulation of Gaussian distributions. Technical note, 2010.
F. Lindgren, H. Rue, J. Lindström. An explicit link between Gaussian fields and Gaussian Markov random fields: the stochastic partial differential equation approach. Journal of the Royal Statistical Society B, 2011.