Module contents
Lesson 20 of 27Advanced 120 min

Advanced Gaussian processes: classification, EP and scalability

We extend GPs beyond Gaussian regression on small datasets. GP classification requires approximate inference: Laplace and expectation propagation, presented generally as iterative moment matching. For scale we study inducing points with the Titsias variational bound and minibatch SVGP, and for long series a state-space formulation solving a Matérn GP in linear time with Kalman.

After this lesson you can

  • Implement GP classification with Laplace and EP.
  • Derive EP as iterative factor projection by moment matching and relate it to ADF and belief propagation.
  • Derive the inducing-point variational bound and train an SVGP with minibatches.
  • Write a Matérn 3/2 GP as a linear Gaussian model and solve it with Kalman and RTS in O(n).
  • Choose an appropriate approximation based on dataset size, likelihood and input structure.

Before you start

A posterior is not always Gaussian

In Gaussian process regression, a normal likelihood preserves conjugacy and allows posterior calculation by Cholesky factorization. In binary classification we choose latent GP ff and likelihood p(yi=1∣fi)=σ(fi)p(y_i=1\mid f_i)=\sigma(f_i). The product of sigmoids breaks conjugacy: p(f∣y)p(\vb f\mid\vb y) is no longer Gaussian. Predictive probability integrates the sigmoid under the latent distribution; applying sigmoid only to the mean ignores uncertainty.

GP classification can be approximated with Laplace: find log-posterior mode f^\hat{\vb f} and use the inverse of its local precision, Σ=(K−1+W)−1\mat\Sigma=(\mat K\inv+\mat W)\inv, with Wii=σ(f^i)(1−σ(f^i))W_{ii}=\sigma(\hat f_i)(1-\sigma(\hat f_i)). The approximation is local. To predict, condition the GP on f\vb f, integrate under the approximate Gaussian, then integrate the sigmoid under the predictive marginal. The figure uses numerical integration, not sigmoid applied to the mean.

InteractiveSquashing a GP with a sigmoid
  • Predictive probability
  • Labels
The latent mean uses a different scale: it is not a probability.
Inference
New label
0.0
Data6
Probability at x = 00.500
Add labels and compare Laplace and EP. Integrated probability is above and latent mean below; in each method the posterior is approximate.

EP may yield different uncertainty from Laplace; it does not itself guarantee better calibration or a universal direction of change. Evaluate log loss, Brier score and calibration on held-out data. If a class is rare, also inspect the number of examples per probability bin.

Expectation propagation

Expectation propagation (EP) approximates each likelihood factor with a Gaussian site. To update site ii, remove it from global approximation qq to obtain cavity q∖i∝q/t~iq^{\setminus i}\propto q/\tilde t_i. Multiply the cavity by exact factor tit_i and normalize: p^i∝q∖iti\hat p_i\propto q^{\setminus i}t_i. This is the tilted distribution. Projecting it onto an exponential family by minimizing KL⁡(p^i∥qnuevo)\KL(\hat p_i\|q_{\rm nuevo}) matches sufficient statistics; for a Gaussian it matches mean and covariance. The new site is proportional to ratio qnuevo/q∖iq_{\rm nuevo}/q^{\setminus i}.

InteractiveEP site by site
  • Cavity
  • Tilted
  • Gaussian projection
1
1
Label0
Tilted mean−0.413
Tilted variance0.829
Proposed site precision0.206
Change site and advance sweeps. Curves show cavity, tilted distribution and Gaussian projection for the site's last visit, with damping 0.5.

For scalar sites use natural parameters precision τ\tau and precision times mean ν\nu: τinuevo=1/vp^−1/v∖i\tau_i^{\rm nuevo}=1/v_{\hat p}-1/v_{\setminus i} and νinuevo=mp^/vp^−m∖i/v∖i\nu_i^{\rm nuevo}=m_{\hat p}/v_{\hat p}-m_{\setminus i}/v_{\setminus i}. The figure shows the proposal before damping. Sites can have negative precision in general models; verify that cavity and global approximation remain valid. Damping can help stabilize but does not guarantee convergence. At a valid fixed point each site’s tilted distribution and qq share projected moments.

ADF processes each factor once; EP revisits sites, so it can correct an earlier projection. As Minka explains, EP also relates to belief propagation: both organize information into messages, but EP approximates messages with a family of limited moments. Local KL matching does not mean minimizing one global KL at every step.

Inducing points and a variational bound

A dense GP stores a matrix n×nn\times n and general factorization costs O(n3)O(n^3); thus introduce M≪nM\ll n inducing values u=f(Z)\vb u=f(\vb Z). Define Qnn=KnmKmm−1Kmn\mat Q_{nn}=\mat K_{nm}\mat K_{mm}\inv\mat K_{mn}. SoR replaces the kernel with Q\mat Q, which has limited rank; FITC also keeps a diagonal residual correction. These are different approximations and can change the effective model.

For Gaussian observations with variance σ2\sigma^2, the sparse variational bound of Titsias is

L=log⁡N(y∣0,Qnn+σ2I)−tr⁡(Knn−Qnn)2σ2≤log⁡p(y).\mathcal L=\log\Normal(\vb y\mid\vb0,\mat Q_{nn}+\sigma^2\mat I) -\frac{\operatorname{tr}(\mat K_{nn}-\mat Q_{nn})}{2\sigma^2}\le\log p(\vb y).

Residual K−Q\mat K-\mat Q is positive semidefinite. The trace penalty recognizes GP variance unexplained by inducing points, rather than treating Q\mat Q as the full kernel. Reducing that trace can improve the bound but does not guarantee no overfitting in finite optimization. Optimizing inducing points and kernel maximizes a bound, not exact evidence.

InteractiveMoving inducing points
  • Exact GP
  • Variational GP
  • Data
  • Draggable inducing points
4
1
-1.8
Titsias bound−6.14
Exact log evidence−4.87
Gap1.27
Drag points or use controls. Posterior means are compared with the same kernel and noise; bound and exact evidence are evaluated on the displayed data.

For large datasets, SVGP explicitly retains q(u)q(\vb u) and sums expected log likelihoods per observation. A uniform minibatch rescaled by n/Bn/B estimates that sum, while KL against p(u)p(\vb u) is calculated once. This supports non-Gaussian likelihoods and stochastic training. Costs depend on factorization and parameterization: typically O(BM2+M3)O(BM^2+M^3) per step and O(M2)O(M^2) for variational covariance, in addition to data. Poorly placed inducing points can waste capacity.

A temporal Matérn as a state-space system

The Matérn kernel 3/23/2, k(τ)=a2(1+λ∣τ∣)e−λ∣τ∣k(\tau)=a^2(1+\lambda|\tau|)e^{-\lambda|\tau|}, with λ=3/ℓ\lambda=\sqrt3/\ell has an exact two-state SDE representation. This state-space GP uses s=(f,f′)⊤\vb s=(f,f')\T:

 ⁣ds=Fs ⁣dt+L ⁣dβ,F=[01−λ2−2λ],L=[01],Qc=4a2λ3,H=[10].\dd\vb s=\mat F\vb s\dd t+\mat L\dd\beta,\quad \mat F=\begin{bmatrix}0&1\\-\lambda^2&-2\lambda\end{bmatrix},\quad \mat L=\begin{bmatrix}0\\1\end{bmatrix},\quad Q_c=4a^2\lambda^3,\quad \mat H=\begin{bmatrix}1&0\end{bmatrix}.

Stationary covariance P∞\mat P_\infty satisfies FP∞+P∞F⊤+LQcL⊤=0\mat F\mat P_\infty+\mat P_\infty\mat F\T+\mat LQ_c\mat L\T=0. For interval Δ\Delta, A=eFΔ\mat A=e^{\mat F\Delta} and Q=P∞−AP∞A⊤\mat Q=\mat P_\infty-\mat A\mat P_\infty\mat A\T. With normal observations, Kalman and RTS produce the same posterior at observed times as the exact Matérn GP. For fixed state dimension the pass is O(n)O(n), although storing all states for smoothing still costs O(n)O(n).

InteractiveCubic versus linear
  • Dense Cholesky (mean)
  • Kalman and RTS (mean and variance)
View
Maximum mean error1.67e-15
Times are actual measurements on one machine, not extrapolations. The second view overlays posterior means; constants and hardware affect the crossover.

Measurements use one reference run per configuration repeated three times: median dense Cholesky for mean versus Kalman plus RTS for mean and variance. Python and single-thread BLAS were used; generation code and data are in the repository. At small sizes vectorized dense computation can win despite worse asymptotic order. RBF has no exact finite SDE representation of this type; an approximation is needed for such treatment. For ordered inputs, structured matrices, GPyTorch and deep kernels offer other options with their own assumptions and costs.

Labs

Logistic classification: Laplace and EP from scratch

The likelihood is logistic and EP’s tilted distribution is integrated with 40 Gauss-Hermite nodes. We use damping 0.5, fixed-scale RBF kernel 1 and jitter 10−710^{-7}. Convergence is controlled by precision changes and limited to 25 sweeps; inspect and adjust for other problems. The lab uses 36 training and 400 test observations per dimension, with fixed seeds. Prediction integrates the sigmoid; scikit-learn uses a different numerical approximation for that integral, so exact equality is not required.

[ ]Laplace, EP and predictionBrowser
import numpy as np
from scipy.special import expit
from numpy.polynomial.hermite import hermgauss
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF, ConstantKernel
from sklearn.metrics import log_loss, brier_score_loss

def kernel(X,Y,ell=1.):
    d=((X[:,None,:]-Y[None,:,:])**2).sum(axis=2)
    return np.exp(-d/(2*ell**2))

def laplace(X,y):
    n=len(y); K=kernel(X,X)+1e-7*np.eye(n); Ki=np.linalg.inv(K); f=np.zeros(n)
    for _ in range(60):
        p=expit(f); W=p*(1-p); g=y-p-Ki@f
        step=np.linalg.solve(Ki+np.diag(W),g); f+=step
        if np.max(np.abs(step))<1e-8: break
    cov=np.linalg.inv(Ki+np.diag(W))
    return K,Ki,f,cov

nodes,weights=hermgauss(40); weights=weights/np.sqrt(np.pi)
def ep(X,y,sweeps=25,damping=.5):
    n=len(y); K=kernel(X,X)+1e-7*np.eye(n); Ki=np.linalg.inv(K)
    tau=np.zeros(n); nu=np.zeros(n)
    for _ in range(sweeps):
        old=tau.copy()
        for i in range(n):
            cov=np.linalg.inv(Ki+np.diag(tau)); mean=cov@nu
            v=1/(1/cov[i,i]-tau[i]); m=v*(mean[i]/cov[i,i]-nu[i])
            z=m+np.sqrt(2*v)*nodes; w=weights*expit((2*y[i]-1)*z); w=w/w.sum()
            mt=w@z; vt=w@((z-mt)**2)
            tau[i]=(1-damping)*tau[i]+damping*(1/vt-1/v)
            nu[i]=(1-damping)*nu[i]+damping*(mt/vt-m/v)
        if np.max(np.abs(tau-old))<1e-7: break
    cov=np.linalg.inv(Ki+np.diag(tau));mean=cov@nu
    return K,Ki,mean,cov

def predict(X,Xs,Ki,mean,cov):
    cross=kernel(X,Xs); alpha=Ki@mean; A=Ki@cross
    m=cross.T@alpha; v=np.maximum(1-(cross*A).sum(0)+(A*(cov@A)).sum(0),0)
    return (expit(m[:,None]+np.sqrt(2*v[:,None])*nodes)*weights).sum(1)

def compare(dim):
    rg=np.random.default_rng(80+dim);X=rg.normal(size=(36,dim)); Xt=rg.normal(size=(400,dim))
    latent=lambda X:1.3*X[:,0]-(.7*X[:,1] if dim==2 else .4)
    y=(rg.random(len(X))<expit(latent(X))).astype(int);yt=(rg.random(len(Xt))<expit(latent(Xt))).astype(int)
    _,ki,m,c=laplace(X,y);pl=predict(X,Xt,ki,m,c)
    _,ki,m,c=ep(X,y);pe=predict(X,Xt,ki,m,c)
    model=GaussianProcessClassifier(kernel=ConstantKernel(1.,constant_value_bounds='fixed')*RBF(1.,length_scale_bounds='fixed'),optimizer=None,max_iter_predict=100).fit(X,y)
    ps=model.predict_proba(Xt)[:,1]
    print('dim',dim,'logloss Laplace EP sklearn',*[round(log_loss(yt,p),5) for p in (pl,pe,ps)],'Brier',*[round(brier_score_loss(yt,p),5) for p in (pl,pe,ps)],'max Laplace-sklearn',np.max(np.abs(pl-ps)))
    return yt,pl,pe,ps
[ ]Comparison in 1DBrowser
y1,lap1,ep1,sk1=compare(1)
[ ]Comparison in 2DBrowser
y2,lap2,ep2,sk2=compare(2)

Log loss and Brier summarize the set. To inspect calibration, bin probabilities without hiding the observation count per bin; an empty bin provides no evidence and 400 cases are few for general conclusions.

[ ]Calibration binsBrowser
edges=np.linspace(0,1,6)
for lo,hi in zip(edges[:-1],edges[1:]):
    mask=(ep2>=lo)&(ep2<(hi if hi<1 else hi+1e-12))
    if mask.any(): print(round(lo,1),round(hi,1),'n',mask.sum(),'predicha',round(ep2[mask].mean(),3),'observada',round(y2[mask].mean(),3))

Matérn 3/2 via Kalman and RTS

With n=500n=500 compare mean and variance at every point with the dense GP. The filter uses initial stationary covariance and exact discretization; RTS smoothing incorporates later observations. The test signal is deterministic and Gaussian noise is added with seed 20. Timings depend on environment and are not an algorithm property.

[ ]Matérn matrices and smootherBrowser
import numpy as np
from scipy.linalg import expm, solve_continuous_lyapunov, cho_factor, cho_solve
from time import perf_counter

def matern32_matrices(ell,variance):
    a=np.sqrt(3)/ell
    F=np.array([[0.,1.],[-a*a,-2*a]])
    L=np.array([[0.],[1.]])
    qc=4*variance*a**3
    H=np.array([[1.,0.]])
    P=solve_continuous_lyapunov(F,-qc*(L@L.T))
    return F,L,qc,H,P

def discretize(F,P,dt):
    A=expm(F*dt); Q=P-A@P@A.T
    return A,(Q+Q.T)/2

def smooth(y,dt,noise,ell=1.,variance=1.):
    F,L,qc,H,P=matern32_matrices(ell,variance)
    A,Q=discretize(F,P,dt); n=len(y)
    m=np.zeros(2); C=P.copy()
    mf=np.zeros((n,2)); Cf=np.zeros((n,2,2)); mp=np.zeros((n,2)); Cp=np.zeros((n,2,2))
    for i in range(n):
        if i: m=A@m; C=A@C@A.T+Q
        mp[i]=m; Cp[i]=C
        innovation=y[i]-m[0]; S=C[0,0]+noise
        gain=C[:,0]/S; m=m+gain*innovation
        C=C-np.outer(gain,C[0,:]); C=(C+C.T)/2
        mf[i]=m;Cf[i]=C
    ms=mf.copy(); Cs=Cf.copy()
    for i in range(n-2,-1,-1):
        p=Cp[i+1]; determinant=p[0,0]*p[1,1]-p[0,1]*p[1,0]
        inverse=np.array([[p[1,1],-p[0,1]],[-p[1,0],p[0,0]]])/determinant
        gain=Cf[i]@A.T@inverse
        ms[i]=mf[i]+gain@(ms[i+1]-mp[i+1])
        Cs[i]=Cf[i]+gain@(Cs[i+1]-Cp[i+1])@gain.T
    return ms[:,0],Cs[:,0,0]
[ ]Comparison with exact GPBrowser
rg=np.random.default_rng(20); n=500; x=np.arange(n)*.025
y=np.sin(x)+.2*rg.normal(size=n); r=.04
start=perf_counter(); mean,var=smooth(y,.025,r); print('kalman+RTS n=500',round(perf_counter()-start,3),'s')
d=np.abs(x[:,None]-x[None,:]); a=np.sqrt(3)*d; K=(1+a)*np.exp(-a)
start=perf_counter(); cf=cho_factor(K+r*np.eye(n),lower=True); exact=K@cho_solve(cf,y); V=K-K@cho_solve(cf,K)
print('dense n=500',round(perf_counter()-start,3),'s','max mean err',np.max(np.abs(mean-exact)),'max variance err',np.max(np.abs(var-np.diag(V))))

The following cell processes 100,000 observations in linear time and memory for fixed state. It may take longer in the browser than in local Python.

[ ]100,000-point seriesBrowser
n=100000;y=np.sin(np.arange(n)*.025)+.2*rg.normal(size=n)
start=perf_counter(); large_mean,large_var=smooth(y,.025,r); print('kalman+RTS n=100000',round(perf_counter()-start,3),'s','last',large_mean[-1],large_var[-1])

SVGP on GPU

The local cell generates 100,000 synthetic noisy pairs, trains with minibatches of 1024 and compares M=16M=16 and M=32M=32. SVGP mean is compared with an exact GP on the first 300 data points using hyperparameters learned by each fit: the difference also reflects the dataset change, not just sparse approximation. True reference sin⁡(6x)\sin(6x) applies to this simulated problem.

It ran on CUDA with GPyTorch 1.15.2 for 80 steps per configuration. Mean absolute errors against the generating function were 0.0614 and 0.0793; mean differences against the 300-point GP were 0.0603 and 0.0766. The displayed ELBO comes from the last minibatch and is not directly a stable convergence measure. This is a short check, not a claim that 16 inducing points are better than 32 or about performance on other hardware.

[ ]SVGP with 100,000 data pointsLocal GPU
import time
import numpy as np
import torch,gpytorch
from scipy.linalg import cho_factor,cho_solve
torch.set_num_threads(1)
torch.manual_seed(20)
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
n=100000
X=torch.rand(n,1,device=device);y=torch.sin(6*X[:,0])+.15*torch.randn(n,device=device)
Xt=torch.linspace(0,1,400,device=device).unsqueeze(-1)

class SVGP(gpytorch.models.ApproximateGP):
    def __init__(self,m):
        z=torch.linspace(0,1,m,device=device).unsqueeze(-1)
        q=gpytorch.variational.CholeskyVariationalDistribution(m)
        super().__init__(gpytorch.variational.VariationalStrategy(self,z,q,learn_inducing_locations=True))
        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))

for m in (16,32):
    torch.manual_seed(30);model=SVGP(m).to(device);likelihood=gpytorch.likelihoods.GaussianLikelihood().to(device)
    model.train();likelihood.train();optimizer=torch.optim.Adam(list(model.parameters())+list(likelihood.parameters()),lr=.03)
    objective=gpytorch.mlls.VariationalELBO(likelihood,model,num_data=n)
    if device.type=='cuda':torch.cuda.synchronize()
    start=time.perf_counter()
    for t in range(80):
        idx=torch.randint(n,(1024,),device=device);optimizer.zero_grad()
        loss=-objective(model(X[idx]),y[idx]);loss.backward();optimizer.step()
    if device.type=='cuda':torch.cuda.synchronize()
    elapsed=time.perf_counter()-start;model.eval();likelihood.eval()
    with torch.no_grad(): pred=model(Xt).mean.cpu().numpy()
    ell=model.covar_module.base_kernel.lengthscale.item();amp=model.covar_module.outputscale.item();noise=likelihood.noise.item()
    train=X[:300,0].cpu().numpy();obs=y[:300].cpu().numpy();test=Xt[:,0].cpu().numpy()
    k=lambda a,b:amp*np.exp(-.5*((a[:,None]-b[None,:])/ell)**2)
    K=k(train,train)+noise*np.eye(len(train)); exact=k(test,train)@cho_solve(cho_factor(K,lower=True),obs)
    print('M',m,'steps',80,'ELBO minibatch',round(-loss.item(),4),'lengthscale',round(ell,4),'noise',round(noise,4),'MAE true',round(np.mean(np.abs(pred-np.sin(6*test))),4),'mean difference vs exact 300',round(np.mean(np.abs(pred-exact)),4),'seconds',round(elapsed,2))
print('device',device,'N',n)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

NumericMemory of two matrices
In float64, compare memory of a dense covariance matrix of n=50 000n=50\,000 with an inducing matrix of M=500M=500. How many times larger is the first, counting only square matrices?
QuizThe trace term
What role does the trace play in the Titsias variational bound?
ProofMoments at an EP fixed point
Prove: At a valid EP fixed point with Gaussian sites, the tilted and global approximations have the same projected moments.
0
Assume normalizable cavities, finite moments and Gaussian projection by minimizing KL⁡(p^i∥q)\KL(\hat p_i\|q).

Step 1 of 2. What conditions does Gaussian projection satisfy?

ProofInducing-point bound
Prove: Obtain the collapsed Titsias bound for Gaussian noise.
0
Use q(f,u)=p(f∣u)q(u)q(\vb f,\vb u)=p(\vb f\mid\vb u)q(\vb u) and define Q=KnmKmm−1Kmn\mat Q=\mat K_{nm}\mat K_{mm}\inv\mat K_{mn}.

Step 1 of 3. What covariance does p(f∣u)p(\vb f\mid\vb u) have?

CodeDiscretize Matérn 3/2
Implement matern_matrices(ell, variance, dt) and return F, L, qc, H, A, Q. Use stationary covariance and matrix exponential for transition noise. All arguments are positive except dt, which may be zero.
def matern_matrices(ell, variance, dt):
  pass
Shift+Enter to run

Summary

Key idea
A non-Gaussian likelihood requires posterior approximation, and scale demands exploiting structure or reducing the GP representation.
  • Laplace fits a Gaussian around the mode; EP updates sites via cavities and moment matching.
  • The inducing-point variational bound penalizes residual variance and SVGP supports minibatches.
  • A temporal Matérn with finite SDE representation is solved with Kalman and RTS in linear time for fixed state.

Sources: Rasmussen and Williams, chapter 3; Minka, EP; Titsias, variational inducing points; Hensman and colleagues, GP for big data; GPyTorch.