Module contents
Lesson 16 of 27Core 120 min

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

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.

InteractiveFunctions before observing data
  • Sample 1
  • Sample 2
  • Sample 3
1.0
1.0
Covariance at x = 01.00
Choose kernel, length and variance. Change the seed to see three other functions. Lines connect 100 jointly simulated values: factorization jitter is 10⁻⁸ on the diagonal.

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 k(x,x′)=a(1+xx′/9)k(x,x')=a(1+xx'/9), 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 nn points means factoring K=LL⊤\mat K=\mat L\mat L\T and forming f=m+Lz\vb f=\vb m+\mat L\vb z, z∼N(0,I)\vb z\sim\Normal(\vb0,\mat I). 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 ρ\rho, matrix [1ρρ1]\begin{bmatrix}1&\rho\\\rho&1\end{bmatrix} has eigenvalues 1+ρ1+\rho and 1−ρ1-\rho. It is valid only if ∣ρ∣≤1|\rho|\le1. When ρ\rho 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 f(x)=ϕ(x)⊤wf(x)=\vb\phi(x)\T\vb w, w∼N(0,Σw)\vb w\sim\Normal(\vb0,\mat\Sigma_w). For any finite collection, its values are a linear Gaussian transform with covariance

k(x,x′)=ϕ(x)⊤Σwϕ(x′).k(x,x')=\vb\phi(x)\T\mat\Sigma_w\vb\phi(x').

This is weight-space and function-space duality: conditioning w\vb w and projecting, or conditioning values of ff 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 fH(x)=H−1/2∑j=1Hajφ(wj⊤x+bj)f_H(x)=H^{-1/2}\sum_{j=1}^H a_j\varphi(\vb w_j\T x+b_j), with iid neurons, centered independent aja_j, and finite second moments. The multivariate central limit theorem gives Gaussianity of any finite collection as H→∞H\to\infty. Its covariance is the expectation of the product of activations times the variance of aja_j. 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 x1,…,xnx_1,\dots,x_n and group one neuron’s outputs into a vector of nn components. Vectors from distinct neurons are iid and centered; their sum scaled by 1/H1/\sqrt H tends to a multivariate normal with one vector’s covariance. The same construction works for any finite input collection. Scale 1/H1/\sqrt H 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 1/H1/\sqrt H, independent Gaussian biases and widths tending to infinity, covariances propagate layer by layer:

K(ℓ+1)(x,x′)=σb2+σw2E(U,V)∼N(0,C)[φ(U)φ(V)],C=[K(ℓ)(x,x)K(ℓ)(x,x′)K(ℓ)(x′,x)K(ℓ)(x′,x′)].K^{(\ell+1)}(x,x')=\sigma_b^2+\sigma_w^2\E_{(U,V)\sim\Normal(0,\mat C)}[\varphi(U)\varphi(V)],\quad \mat C=\begin{bmatrix}K^{(\ell)}(x,x)&K^{(\ell)}(x,x')\\K^{(\ell)}(x',x)&K^{(\ell)}(x',x')\end{bmatrix}.

For ReLU, if q=K(x,x)q=K(x,x), q′=K(x′,x′)q'=K(x',x') and θ=arccos⁡(K(x,x′)/qq′)\theta=\arccos(K(x,x')/\sqrt{qq'}), the expectation equals qq′[sin⁡θ+(π−θ)cos⁡θ]/(2π)\sqrt{qq'}[\sin\theta+(\pi-\theta)\cos\theta]/(2\pi) when q,q′>0q,q'>0, 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 yi=f(xi)+ϵiy_i=f(x_i)+\epsilon_i, with ϵi∼iidN(0,σn2)\epsilon_i\iid\Normal(0,\sigma_n^2) independent of ff. Define K=k(X,X)\mat K=k(X,X), K∗=k(X,X∗)\mat K_*=k(X,X_*), K∗∗=k(X∗,X∗)\mat K_{**}=k(X_*,X_*) and C=K+σn2I\mat C=\mat K+\sigma_n^2\mat I. For simplicity use zero mean; with nonzero mean subtract m(X)m(X) before solving and add m(X∗)m(X_*) at the end. By Gaussian conditioning, GP regression gives

f∗∣y∼N(K∗⊤C−1y, K∗∗−K∗⊤C−1K∗).\vb f_*\mid\vb y\sim\Normal(\mat K_*\T\mat C\inv\vb y,\ \mat K_{**}-\mat K_*\T\mat C\inv\mat K_*).

The formula assumes C\mat C invertible, for example if σn2>0\sigma_n^2>0. This is the latent function distribution; for an independent future observation add σn2I\sigma_n^2\mat I 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 r=f∗−K∗⊤C−1y\vb r=\vb f_*-\mat K_*\T\mat C\inv\vb y. It is Gaussian and its covariance with y\vb y is K∗⊤−K∗⊤C−1C=0\mat K_*\T-\mat K_*\T\mat C\inv\mat C=0. Being jointly Gaussian, r\vb r and y\vb y are independent. Residual covariance is the Schur complement above, and once y\vb y 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.

InteractiveConditioning on observations
  • Posterior mean
  • ±2 standard deviation band
  • Posterior samples
  • Data
0.05
1.0
0.0
Data3
Log evidence−3.91
Click the plane or add a datum with keyboard-accessible controls. Reduce noise to zero and observe the band close at the data. The widget adds jitter 10⁻⁸ for factorization.

The band represents mean plus or minus two marginal standard deviations of f(x)f(x): 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 aa and noise σn2\sigma_n^2, posterior mean at that point is ay/(a+σn2)a y/(a+\sigma_n^2) and latent variance is aσn2/(a+σn2)a\sigma_n^2/(a+\sigma_n^2). 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 a>0a>0, the mean tends to yy 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 C=LL⊤\mat C=\mat L\mat L\T, solve Lv=y\mat L\vb v=\vb y and L⊤α=v\mat L\T\vb\alpha=\vb v, and for each test point Lv∗=k(X,x∗)\mat L\vb v_*=k(X,x_*). Then mean is k(x∗,X)αk(x_*,X)\vb\alpha and latent variance k(x∗,x∗)−v∗⊤v∗k(x_*,x_*)-\vb v_*\T\vb v_*. Do not form the inverse. Dense factorization costs O(n3)\bigO(n^3) and uses O(n2)\bigO(n^2) 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 r=∣x−x′∣r=|x-x'|, RBF is aexp⁡(−r2/(2ℓ2))a\exp(-r^2/(2\ell^2)); Matérn 1/2 is aexp⁡(−r/ℓ)a\exp(-r/\ell), Matérn 3/2 is a(1+3r/ℓ)exp⁡(−3r/ℓ)a(1+\sqrt3r/\ell)\exp(-\sqrt3r/\ell) and Matérn 5/2 adds term 5r2/(3ℓ2)5r^2/(3\ell^2). 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 pp can be written aexp⁡[−2sin⁡2(π(x−x′)/p)/ℓ2]a\exp[-2\sin^2(\pi(x-x')/p)/\ell^2]. The rational quadratic (1+r2/(2αℓ2))−α(1+r^2/(2\alpha\ell^2))^{-\alpha}, with α>0\alpha>0, 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.

InteractiveBuilding a kernel
  • Mean
  • ±2 standard deviation band
  • Synthetic data
0.04
Log evidence−15.27
Enable trend and local periodicity, change noise and observe mean and band outside the data interval. The series is synthetic and its rule appears below.

The figure’s 16 data points are y(x)=0.25x+0.8sin⁡(πx)+0.12sin⁡(13x)y(x)=0.25x+0.8\sin(\pi x)+0.12\sin(13x) 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 θ\theta determining C\mat C, the marginal log likelihood integrates the latent function:

log⁡p(y∣X,θ)=−12y⊤C−1y−12log⁡det⁡C−n2log⁡(2π).\log p(\vb y\mid X,\theta)=-\tfrac12\vb y\T\mat C\inv\vb y-\tfrac12\log\det\mat C-\tfrac n2\log(2\pi).

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 α=C−1y\vb\alpha=\mat C\inv\vb y and Cj=∂C/∂θj\mat C_j=\partial\mat C/\partial\theta_j, then

∂log⁡p(y∣θ)∂θj=12tr⁡[(αα⊤−C−1)Cj].\frac{\partial\log p(\vb y\mid\theta)}{\partial\theta_j}=\tfrac12\tr[(\vb\alpha\vb\alpha\T-\mat C\inv)\mat C_j].

To derive it use  ⁣dC−1=−C−1( ⁣dC)C−1\dd\mat C\inv=-\mat C\inv(\dd\mat C)\mat C\inv and  ⁣dlog⁡det⁡C=tr⁡(C−1 ⁣dC)\dd\log\det\mat C=\tr(\mat C\inv\dd\mat C), 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 CC−1=I\mat C\mat C\inv=\mat I. The quadratic term’s differential is then 12y⊤C−1( ⁣dC)C−1y=12tr⁡(αα⊤ ⁣dC)\tfrac12\vb y\T\mat C\inv(\dd\mat C)\mat C\inv\vb y=\tfrac12\tr(\vb\alpha\vb\alpha\T\dd\mat C). The determinant term contributes −12tr⁡(C−1 ⁣dC)-\tfrac12\tr(\mat C\inv\dd\mat C); collecting the coefficient of  ⁣dθj\dd\theta_j gives the formula. If a parameterized mean also depends on θj\theta_j, there is an additional term: the expression shown assumes a fixed mean.

In the lab, with Kij=aexp⁡[−dij2/(2ℓ2)]K_{ij}=a\exp[-d_{ij}^2/(2\ell^2)] and s=σn2s=\sigma_n^2, the chain rule gives ∂K/∂log⁡a=K\partial K/\partial\log a=K, ∂K/∂log⁡ℓ=K⊙D2/ℓ2\partial K/\partial\log\ell=K\odot D^2/\ell^2 and ∂C/∂log⁡s=sI\partial\mat C/\partial\log s=s\mat I. Here ⊙\odot is the componentwise product. Checking these derivatives against finite differences helps detect a factor 2 or wrong sign before trusting the optimizer.

InteractiveTwo explanations of the same data

Log evidence, visually clipped between −40 and −20. The vertical axis is log10 noise, from −2 at bottom to 1 at top.

≤ −40≥ −20
−2log10 length4
  • Posterior mean
  • Observations
-0.35
-0.82
Length0.447
Noise variance0.151
Log evidence−20.37
Click the map or move controls. Shading shows evidence on a 30 × 30 grid, with fixed signal variance 0.36. The lower panel recalculates the mean for the selected point.

The data reproduce the scikit-learn example: 20 uniform inputs generated with RandomState(0) and responses 0.5+sin⁡(3x)+ϵ0.5+\sin(3x)+\epsilon, with ϵ∼N(0,0.32)\epsilon\sim\Normal(0,0.3^2) 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 θ\theta 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.

[ ]GP from scratch and gradientBrowser
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.

[ ]Compare with scikit-learnBrowser
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.

[ ]Exact GP with GPyTorchLocal GPU
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)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

NumericUncertainty between two observations
For a zero-mean GP with RBF kernel of variance 1 and length 1, observe points at x=0x=0 and x=1x=1 with noise variance 0.01. Calculate the latent posterior variance at x=0.5x=0.5.
QuizPrior smoothness
Which kernel from the lesson would you use to model a continuous but non-differentiable function, and why?
ProofConditioning the GP
Prove: Derive posterior mean and covariance of test latent values.
0
The joint distribution of y\vb y and f∗\vb f_* is zero-mean Gaussian with blocks C\mat C, K∗\mat K_* and K∗∗\mat K_{**}; assume C≻0\mat C\succ0.

Step 1 of 2. What is the cross-covariance between observations and test latent values?

ProofEvidence gradient
Prove: Derive the log-evidence gradient with respect to a parameter of C\mat C.
0
Write α=C−1y\vb\alpha=\mat C\inv\vb y and Cj=∂C/∂θj\mat C_j=\partial\mat C/\partial\theta_j.

Step 1 of 3. What is the derivative of the inverse?

CodePrediction with Cholesky
Implement 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):
  pass
Shift+Enter to run

Summary

Key idea
A GP combines a prior covariance between function values with Gaussian conditioning. Its bands reflect assumptions of that prior and chosen noise, not a model-independent guarantee.
  • 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.