Gaussian processes for regression
A Gaussian process is a prior directly on functions, specified by a mean function and kernel. We derive GP regression by Gaussian conditioning, design priors by choosing and combining kernels, learn hyperparameters by maximizing marginal likelihood with its gradient, and prove equivalence with Bayesian linear regression in feature space.
After this lesson you can
- Define a GP and sample prior functions with different kernels.
- Derive and implement predictive mean and variance with Cholesky (Rasmussen and Williams algorithm 2.1).
- Design composite kernels (sums and products) for trends, seasonality and noise.
- Calculate marginal log likelihood and its hyperparameter gradient and optimize it.
- Prove equivalence between the weight-space and function-space views.
Before you start
- 14Bayesian linear regressionEvidence approximation (type-II maximum likelihood)Equivalent kernel
- 04Gaussian conditioning
- 09Cholesky in finite precision: stability and jitter
- 02Cholesky decompositionDerivatives of the inverse and log-determinantTrace trick
- 11Common kernels and construction rulesGaussian RBF kernelKernel trick
- 13Reproducing kernel Hilbert spaceMercer's theorem
- 06Limited-memory BFGS
A prior over functions
An expensive simulator returns a few values at points you chose. You want to interpolate between them, estimate where you know least and decide where to run the next experiment. A line with a narrow band helps only if the line reasonably describes the phenomenon. A Gaussian process expresses hypotheses about possible shapes through covariance between pairs of inputs and updates those hypotheses with data.
RBF produces visually smooth curves; Matérn 1/2 shows rough paths. Length controls the distance over which values resemble one another for these stationary kernels. A particular sample does not prove a regularity property: it is one realization on a finite grid. The figure’s linear kernel is , in which length scale does not enter.
The definition specifies compatible finite distributions, not an infinite table of stored values. A valid covariance expresses similarity, but intuitive “likeness” is insufficient: the Gram matrix of every set of points must be positive semidefinite. Sampling at points means factoring and forming , . If the matrix is singular, spectral factorization can also generate the degenerate Gaussian; numerical jitter slightly changes the covariance.
For example, for two points with unit variance and correlation , matrix has eigenvalues and . It is valid only if . When is near 1, both heights tend to move together; near 0, one value says little about the other under the Gaussian. A kernel prescribes all these correlations at once, coherently for any number of points.
From weights to functions
In Bayesian linear regression, take , . For any finite collection, its values are a linear Gaussian transform with covariance
This is weight-space and function-space duality: conditioning and projecting, or conditioning values of directly, gives the same distribution. A GP operates with the Gram matrix without enumerating features, as in the kernel trick. Some covariances admit an infinite-dimensional representation under appropriate assumptions; not every arbitrary function is a valid kernel, nor must its features be explicitly built to predict.
A different construction leads to a GP from networks. For fixed inputs, consider , with iid neurons, centered independent , and finite second moments. The multivariate central limit theorem gives Gaussianity of any finite collection as . Its covariance is the expectation of the product of activations times the variance of . This is the NNGP limit: a prior of an infinite-width random network, not a claim that every finite trained network is a GP.
To see this, fix and group one neuron’s outputs into a vector of components. Vectors from distinct neurons are iid and centered; their sum scaled by tends to a multivariate normal with one vector’s covariance. The same construction works for any finite input collection. Scale is essential to keep variance of order one: without it the sum’s variance normally grows with width.
In a deep fully connected network with weight scaling , independent Gaussian biases and widths tending to infinity, covariances propagate layer by layer:
For ReLU, if , and , the expectation equals when , with the continuous limit if a variance is zero. This is the arccosine kernel recursion. Lee and colleagues develop the deep correspondence; independence, scaling and limit assumptions matter.
Conditioning the joint Gaussian
Let observations be , with independent of . Define , , and . For simplicity use zero mean; with nonzero mean subtract before solving and add at the end. By Gaussian conditioning, GP regression gives
The formula assumes invertible, for example if . This is the latent function distribution; for an independent future observation add to its covariance. The mean depends on observed values; covariance, with fixed hyperparameters, depends only on their locations and noise.
The derivation requires no memorized formula. Define residual . It is Gaussian and its covariance with is . Being jointly Gaussian, and are independent. Residual covariance is the Schur complement above, and once is fixed only that residual remains random. The expression is positive semidefinite because it is a covariance, though subtracting nearly equal matrices can yield a small negative value through rounding.
The band represents mean plus or minus two marginal standard deviations of : it is not a simultaneous band for the whole function. The figure uses RBF with variance and length 1; far from data its covariance with them tends to zero, so it returns to the prior. That is not true of every kernel: a periodic one retains correlations at period-separated distances and a linear one does not decay.
At one training point with kernel variance and noise , posterior mean at that point is and latent variance is . With positive noise the curve need not pass exactly through the datum: some discrepancy is attributed to the sensor. If noise tends to zero and , the mean tends to and variance to zero. Adding observation noise to latent variance answers a different question: how much a new sensor reading will vary.
Compute the Cholesky factorization , solve and , and for each test point . Then mean is and latent variance . Do not form the inverse. Dense factorization costs and uses space; small jitter can help with repeated points, but changes the matrix, so document it and check sensitivity.
Designing and combining kernels
Kernel construction translates assumptions into covariances. With distance , RBF is ; Matérn 1/2 is , Matérn 3/2 is and Matérn 5/2 adds term . Their smoothness properties differ: RBF admits derivatives of all orders in mean square, while Matérn 1/2 does not admit the first. Matérn 3/2 and 5/2 have one and two mean-square derivatives respectively.
A periodic kernel with period can be written . The rational quadratic , with , is a continuous mixture of RBFs at different scales, with appropriate normalization. A linear kernel introduces trend; observation-noise covariance is diagonal in observation indices, not a periodic signal.
Sums and products of valid kernels are valid: a sum combines independent components; a product requires both similarities simultaneously. Thus periodic times RBF describes repetition that loses correlation over large separations. It is not equivalent to extrapolating identical seasonality forever.
The first rule is direct: a sum of positive semidefinite matrices is positive semidefinite. The second follows from the Schur product theorem: the entrywise product of two positive semidefinite Gram matrices is also positive semidefinite. Multiplying two arbitrary distance functions does not itself guarantee this property; here we start from valid kernels. A constant kernel added to a linear one represents a random intercept, different from asserting that the prior mean is a known constant.
The figure’s 16 data points are on an equally spaced grid from 0 to 6. Perturbation is deterministic, not a sample of real noise. Extrapolation depends on components and the zero-mean prior: it is not guaranteed to reflect the mechanism that produced the series.
Evidence and hyperparameter choice
For determining , the marginal log likelihood integrates the latent function:
The first term measures fit under the covariance, the second depends on volume and the third normalizes. Do not assess just one: evidence compares all three. If and , then
To derive it use and , together with the trace trick. The inverse-containing matrix form is an identity, not an instruction to implement it explicitly: solve systems with Cholesky. Optimizing log parameters keeps length, signal variance and noise variance positive.
The first identity comes from differentiating . The quadratic term’s differential is then . The determinant term contributes ; collecting the coefficient of gives the formula. If a parameterized mean also depends on , there is an additional term: the expression shown assumes a fixed mean.
In the lab, with and , the chain rule gives , and . Here is the componentwise product. Checking these derivatives against finite differences helps detect a factor 2 or wrong sign before trusting the optimizer.
The data reproduce the scikit-learn example: 20 uniform inputs generated with RandomState(0) and responses , with of RandomState(1). The map uses a grid and fixed amplitude, while the original example also optimizes amplitude. A short-scale region explains structure and a long-scale region explains much as noise; the long optimum may lie on a plateau or at the domain boundary. Restarts explore multiple solutions but do not guarantee a global optimum.
If instead of fixing you integrate its posterior, total predictive variance decomposes into expected conditional variances plus variance of conditional means. The latter expresses uncertainty across models with different parameters and vanishes when a single estimate is fixed. Even integrating it, the band remains conditional on the model family and assumed noise distribution; a wrong family may be overconfident out of sample.
Lab: Cholesky, evidence and gradient
The lab uses the figure’s reproducible series. Parameterization contains log signal variance, log length and log noise variance. The function returns evidence and its gradient; a multiple-right-hand-side solve is used for the trace term. Then compare the gradient with central differences and run L-BFGS from three starts. The solution can depend on initialization and imposed bounds.
import numpy as np
from scipy.linalg import cho_factor, cho_solve, solve_triangular
from scipy.optimize import minimize
X = np.random.RandomState(0).uniform(0, 5, size=20)
y = 0.5 + np.sin(3*X) + np.random.RandomState(1).normal(0, 0.3, size=20)
D2 = (X[:, None]-X[None, :])**2
def evidence(logtheta):
signal, length, noise = np.exp(logtheta)
K = signal*np.exp(-D2/(2*length**2))
C = K + (noise + 1e-8)*np.eye(len(X))
cf = cho_factor(C, lower=True)
alpha = cho_solve(cf, y)
value = -0.5*y@alpha - np.log(np.diag(cf[0])).sum() - len(y)*np.log(2*np.pi)/2
derivatives = [K, K*D2/length**2, noise*np.eye(len(X))]
grad = np.array([0.5*(alpha@[email protected](cho_solve(cf, d))) for d in derivatives])
return value, grad
def predict_gp(xs, logtheta):
signal, length, noise = np.exp(logtheta)
C = signal*np.exp(-D2/(2*length**2)) + (noise + 1e-8)*np.eye(len(X))
L = np.linalg.cholesky(C)
Kstar = signal*np.exp(-(X[:, None]-xs[None, :])**2/(2*length**2))
alpha = solve_triangular(L.T, solve_triangular(L, y, lower=True))
v = solve_triangular(L, Kstar, lower=True)
return Kstar.T@alpha, signal-np.sum(v*v, axis=0)
z = np.log([1.0, 0.7, 0.2])
eps = 1e-5
fd = np.array([(evidence(z+np.eye(3)[j]*eps)[0]-evidence(z-np.eye(3)[j]*eps)[0])/(2*eps) for j in range(3)])
print("error máximo del gradiente", np.max(np.abs(fd-evidence(z)[1])))
fits = []
for start in ([1, 0.2, 0.05], [1, 1, 0.2], [1, 100, 1]):
result = minimize(lambda t: (-evidence(t)[0], -evidence(t)[1]), np.log(start), jac=True, method='L-BFGS-B', bounds=[(-5, 5), (-4, 9), (-8, 3)])
fits.append(result)
print("parámetros", np.round(np.exp(result.x), 4), "log evidencia", round(-result.fun, 4), "éxito", result.success)
best = min(fits, key=lambda r: r.fun)The trace is calculated by solving systems with each kernel derivative, without forming the inverse. Large datasets avoid dense matrices or approximate traces. Now compare mean and latent variance with GaussianProcessRegressor at fixed parameters. alpha represents noise variance and jitter, and return_std returns function uncertainty for this kernel, not noise of a new observation.
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF, ConstantKernel
signal, length, noise = np.exp(best.x)
xs = np.linspace(0, 5, 30)
ours_mean, ours_var = predict_gp(xs, best.x)
sk = GaussianProcessRegressor(kernel=ConstantKernel(signal, constant_value_bounds='fixed')*RBF(length, length_scale_bounds='fixed'), alpha=noise+1e-8, optimizer=None, normalize_y=False)
sk.fit(X[:, None], y)
sk_mean, sk_std = sk.predict(xs[:, None], return_std=True)
print("máxima diferencia de medias", np.max(np.abs(ours_mean-sk_mean)))
print("máxima diferencia de varianzas", np.max(np.abs(ours_var-sk_std**2)))The GP mean with these hyperparameters solves the same system as kernel ridge regression with a penalty corresponding to noise variance, under the chosen loss-scale convention. A GP adds a predictive distribution; identifying the means does not automatically make every uncertainty interpretation equivalent.
Local lab: GPyTorch and GPU
The GPyTorch guide uses ExactGP, Gaussian likelihood and a scaled kernel. This cell is independent of browser cells. It trains a short run on 2000 points and compares exact GPU prediction with SciPy Cholesky at several sizes, with identical parameters and data. Short iterations verify the workflow and correspondence, not guaranteed hyperparameter convergence. Increase steps for longer fitting; measure on the machine where you work, since load, precision and hardware affect timings.
import time
import numpy as np
import torch
import gpytorch
from scipy.linalg import cho_factor, cho_solve
assert torch.cuda.is_available(), "Este laboratorio necesita una GPU CUDA"
torch.manual_seed(7)
torch.set_default_dtype(torch.float64)
device = torch.device('cuda')
class ExactModel(gpytorch.models.ExactGP):
def __init__(self, x, y, likelihood):
super().__init__(x, y, likelihood)
self.mean_module = gpytorch.means.ZeroMean()
self.covar_module = gpytorch.kernels.ScaleKernel(gpytorch.kernels.RBFKernel())
def forward(self, x):
return gpytorch.distributions.MultivariateNormal(self.mean_module(x), self.covar_module(x))
train_x = torch.linspace(0, 1, 2000, device=device)
train_y = torch.sin(2*torch.pi*train_x) + 0.15*torch.randn_like(train_x)
likelihood = gpytorch.likelihoods.GaussianLikelihood().to(device)
model = ExactModel(train_x, train_y, likelihood).to(device)
model.train(); likelihood.train()
optimizer = torch.optim.Adam(model.parameters(), lr=0.08)
mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, model)
steps = 6
with gpytorch.settings.max_cholesky_size(4096):
for _ in range(steps):
optimizer.zero_grad()
loss = -mll(model(train_x), train_y)
loss.backward()
optimizer.step()
torch.cuda.synchronize()
print("pasos", steps, "última pérdida evaluada", float(loss.detach().cpu()))
signal = float(model.covar_module.outputscale.detach().cpu())
length = float(model.covar_module.base_kernel.lengthscale.detach().cpu().item())
noise = float(likelihood.noise.detach().cpu().item())
print("varianza señal, longitud, ruido", signal, length, noise)
for n in (250, 1000, 2000):
xt, yt = train_x[:n], train_y[:n]
lk = gpytorch.likelihoods.GaussianLikelihood().to(device)
gp = ExactModel(xt, yt, lk).to(device)
gp.covar_module.outputscale = signal
gp.covar_module.base_kernel.lengthscale = length
lk.noise = noise
gp.eval(); lk.eval()
test = torch.linspace(0, 1, 50, device=device)
torch.cuda.synchronize(); start = time.perf_counter()
with torch.no_grad(), gpytorch.settings.max_cholesky_size(4096), gpytorch.settings.fast_pred_var(False):
out = gp(test)
gpu_mean = out.mean.cpu().numpy()
gpu_var = out.variance.cpu().numpy()
torch.cuda.synchronize(); gpu_time = time.perf_counter()-start
xx, yy, ss = xt.cpu().numpy(), yt.cpu().numpy(), test.cpu().numpy()
start = time.perf_counter()
K = signal*np.exp(-(xx[:, None]-xx[None, :])**2/(2*length**2)) + noise*np.eye(n)
Ks = signal*np.exp(-(xx[:, None]-ss[None, :])**2/(2*length**2))
cf = cho_factor(K, lower=True)
cpu_mean = Ks.T@cho_solve(cf, yy)
cpu_var = signal-np.sum(Ks*cho_solve(cf, Ks), axis=0)
cpu_time = time.perf_counter()-start
print("n", n, "errores media y varianza", np.max(np.abs(gpu_mean-cpu_mean)), np.max(np.abs(gpu_var-cpu_var)), "tiempos CPU/GPU", cpu_time/gpu_time)npm run lab and open the connection link.Exercises
Step 1 of 2. What is the cross-covariance between observations and test latent values?
Step 1 of 3. What is the derivative of the inverse?
gp_predict(X, y, Xs, kernel, noise) for zero mean. Inputs are arrays of shape (n,d) and (m,d); kernel(A,B) returns a covariance matrix. noise is positive observation variance. Return mean (m,) and latent variances (m,), without inverting matrices.import numpy as np
def gp_predict(X, y, Xs, kernel, noise):
passSummary
- The Gaussian weight view produces a kernel; the wide-network limit produces another under its assumptions.
- Cholesky calculates mean, covariance and log determinant without inverting the observation matrix. Latent variance excludes future noise.
- Sums and products of kernels encode structure. Scale, smoothness and mean determine interpolation and extrapolation.
- Evidence balances fit and volume, has local optima and can be optimized in log parameters. Validate the model and its bands out of sample.