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
- 14Gaussian process regressionGaussian process marginal likelihoodKernel design for Gaussian processesLaplace approximationProbit approximation to the predictiveAssumed density filteringMoment-matching (M-) projectionVariational inferenceStochastic variational inferenceKalman filterRauch-Tung-Striebel smoother
- 26Linear SDEsOrnstein-Uhlenbeck process
- 03Matrix exponentialLinear ODE systems
- 07Forward versus reverse KLKullback-Leibler divergence (relative entropy)
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 and likelihood . The product of sigmoids breaks conjugacy: 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 and use the inverse of its local precision, , with . The approximation is local. To predict, condition the GP on , integrate under the approximate Gaussian, then integrate the sigmoid under the predictive marginal. The figure uses numerical integration, not sigmoid applied to the mean.
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 , remove it from global approximation to obtain cavity . Multiply the cavity by exact factor and normalize: . This is the tilted distribution. Projecting it onto an exponential family by minimizing matches sufficient statistics; for a Gaussian it matches mean and covariance. The new site is proportional to ratio .
For scalar sites use natural parameters precision and precision times mean : and . 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 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 and general factorization costs ; thus introduce inducing values . Define . SoR replaces the kernel with , 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 , the sparse variational bound of Titsias is
Residual is positive semidefinite. The trace penalty recognizes GP variance unexplained by inducing points, rather than treating 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.
For large datasets, SVGP explicitly retains and sums expected log likelihoods per observation. A uniform minibatch rescaled by estimates that sum, while KL against is calculated once. This supports non-Gaussian likelihoods and stochastic training. Costs depend on factorization and parameterization: typically per step and 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 , , with has an exact two-state SDE representation. This state-space GP uses :
Stationary covariance satisfies . For interval , and . 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 , although storing all states for smoothing still costs .
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 . 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.
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,psy1,lap1,ep1,sk1=compare(1)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.
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 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.
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]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.
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 and . 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 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.
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)npm run lab and open the connection link.Exercises
Step 1 of 2. What conditions does Gaussian projection satisfy?
Step 1 of 3. What covariance does have?
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):
passSummary
- 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.