Gaussian Process Classification (Laplace Approximation)¶
Course: MCE5919 — Gaussian Process for Machine Learning and Signal Processing
Topic: GP Classification (Lecture 5)
Instructor: Wenqiang PU
Date: March 2026
Learning Objectives¶
- Understand GP classification as a GP prior on a latent function $f(\mathbf{x})$ combined with a non-Gaussian (Bernoulli) likelihood
- See why the posterior $p(\mathbf{f}\mid X,\mathbf{y})$ is no longer Gaussian (unlike GP regression)
- Implement the Laplace approximation: find the mode $\hat{\mathbf{f}}$ via Newton's method, then fit a Gaussian around it
- Derive and code predictive mean, predictive variance, and class probabilities (averaged vs MAP)
- Understand the role of the marginal likelihood for hyperparameter selection
- Appreciate the practical implementation via Cholesky of $B=I+W^{1/2}KW^{1/2}$
Environment / Packages¶
Required: numpy, matplotlib, scipy.
This notebook intentionally avoids heavy dependencies so students can run it anywhere.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm # for probit Φ and φ
from scipy.special import expit as logistic # σ(z) = 1/(1+exp(-z))
plt.style.use('seaborn-v0_8-whitegrid')
plt.rcParams.update({
'axes.grid': True,
'grid.alpha': 0.35,
'grid.linestyle': '--',
'legend.frameon': True,
'legend.loc': 'best',
})
rng = np.random.default_rng(42)
Notation Cheat Sheet¶
- $X=\lbrace\mathbf{x}_i\rbrace_{i=1}^n$ — Training inputs, $\mathbf{x}_i\in\mathbb{R}^d$
- $y_i\in\lbrace+1,-1\rbrace$ — Binary class labels
- $f_i\triangleq f(\mathbf{x}_i)$ — Latent function value at $\mathbf{x}_i$
- $\mathbf{f}=[f_1,\dots,f_n]^\top$ — Vector of latent values
- $\sigma(\cdot)$ — Response (link) function: $\mathbb{R}\to[0,1]$
- $\pi(\mathbf{x})=\sigma(f(\mathbf{x}))$ — Class probability $p(y{=}+1\mid\mathbf{x})$
- $k(\mathbf{x},\mathbf{x}')$ — Kernel / covariance function
- $K=k(X,X)$ — $n\times n$ kernel (Gram) matrix
- $W=-\nabla\nabla\log p(\mathbf{y}\mid\mathbf{f})$ — Diagonal matrix of neg. second derivatives of log-likelihood
- $B=I+W^{1/2}KW^{1/2}$ — Key matrix for stable Cholesky implementation
- $\hat{\mathbf{f}}$ — Mode of the unnormalized log posterior
1. Background — From Regression to Classification¶
GP Regression predicts continuous outputs $y\in\mathbb{R}$ using a Gaussian likelihood: $$y_i = f(\mathbf{x}_i)+\epsilon_i, \quad \epsilon_i\sim\mathcal{N}(0,\sigma_n^2).$$ The posterior $p(\mathbf{f}\mid X,\mathbf{y})$ is Gaussian → closed-form mean and variance.
GP Classification predicts discrete labels $y_i\in\lbrace+1,-1\rbrace$. The key idea:
- Place a GP prior on a latent function: $f(\cdot)\sim\mathcal{GP}(0,k)$.
- "Squash" $f$ through a response function $\sigma(\cdot)$ to get a class probability: $$\pi(\mathbf{x}) \triangleq p(y{=}+1\mid \mathbf{x}) = \sigma(f(\mathbf{x})).$$
- The likelihood becomes Bernoulli, not Gaussian: $$p(y_i\mid f_i) = \sigma(y_i f_i).$$
Because the likelihood is non-Gaussian, the posterior $p(\mathbf{f}\mid X,\mathbf{y})$ is no longer Gaussian → we need approximations!
Example: Binary Linear Logistic Regression¶
Before jumping to GP classification, it helps to see that even a linear classifier already leads to an intractable posterior once we use a logistic/Bernoulli likelihood.
Setup (2D, labels $\pm1$):
- Prior on weights: $$\mathbf{w}\sim\mathcal{N}(\mathbf{0}, I), \qquad \mathbf{w}\in\mathbb{R}^2.$$
- Linear score: $$f(\mathbf{x})=\mathbf{x}^\top\mathbf{w}.$$
- Logistic likelihood: $$p(y_i\mid \mathbf{x}_i,\mathbf{w})=\sigma\big(y_i\,\mathbf{x}_i^\top\mathbf{w}\big).$$
What you would visualize:
(a) Prior contours in $\mathbf{w}$-space: an isotropic Gaussian centered at the origin.
(b) Data in $\mathbb{R}^2$: a two-class scatter plot (e.g., $n=20$).
(c) Posterior contours in $\mathbf{w}$-space: the prior is "squeezed" toward weight directions that better separate the classes.
(d) Predictive contours in input space: decision boundary (where $p(y{=}+1\mid\mathbf{x})=0.5$) with calibrated class probabilities.
Take-away: The logistic likelihood is non-Gaussian, so $$p(\mathbf{w}\mid X,\mathbf{y})\propto p(\mathbf{w})\prod_i \sigma\big(y_i\mathbf{x}_i^\top\mathbf{w}\big)$$ is not Gaussian. We already need approximation (Laplace / VI / EP) for this simple linear model — and GP classification inherits the same challenge.
From Linear Classifiers to GP Classification¶
Linear model (parametric): the score is constrained to be linear, $f(\mathbf{x})=\mathbf{x}^\top\mathbf{w}$, so posterior inference is over a small parameter vector $\mathbf{w}$.
GP model (nonparametric): replace the parametric form with a GP prior over functions, $$f(\cdot)\sim\mathcal{GP}(0,k),\qquad p(y_i\mid f_i)=\sigma(y_i f_i),$$ so posterior inference is over the training latents $\mathbf{f}=[f(\mathbf{x}_1),\dots,f(\mathbf{x}_n)]^\top$.
# ── 2D toy example: Bayesian linear logistic regression (Laplace) ──
def make_toy_2d_classification(n=20, mean_pos=(1.2, 0.8), mean_neg=(-1.2, -0.8), std=1.7, rng=None):
"""Return X in R^{n×2}, y in {+1,-1}."""
if rng is None:
rng = np.random.default_rng(0)
n_pos = n // 2
n_neg = n - n_pos
mean_pos = np.asarray(mean_pos, dtype=float)
mean_neg = np.asarray(mean_neg, dtype=float)
cov = (std ** 2) * np.eye(2)
X_pos = rng.multivariate_normal(mean_pos, cov, size=n_pos)
X_neg = rng.multivariate_normal(mean_neg, cov, size=n_neg)
X = np.vstack([X_pos, X_neg])
y = np.hstack([np.ones(n_pos), -np.ones(n_neg)])
perm = rng.permutation(n)
return X[perm], y[perm]
def laplace_logistic_regression_2d(X, y, max_iter=50, tol=1e-10):
"""Laplace approximation for p(w|X,y) with w~N(0,I), p(y|x,w)=σ(y x^T w)."""
X = np.asarray(X, dtype=float)
y = np.asarray(y, dtype=float)
n, d = X.shape
assert d == 2, "This helper is for 2D weights."
w = np.zeros(d)
for it in range(max_iter):
z = y * (X @ w)
s = logistic(z) # σ(z)
# log posterior gradient: ∇ log p(w|D) = -w + Σ_i (1-σ(z_i)) y_i x_i
grad = -w + (X * (y * (1.0 - s))[:, None]).sum(axis=0)
# Hessian of log posterior (negative definite): H = -I - X^T diag(r) X, r = σ(z)(1-σ(z))
r = s * (1.0 - s)
H = -np.eye(d) - X.T @ (r[:, None] * X)
step = np.linalg.solve(H, grad)
w_new = w - step
if np.linalg.norm(w_new - w) < tol:
w = w_new
break
w = w_new
# Laplace covariance: Σ = (-H)^{-1} at the mode
z = y * (X @ w)
s = logistic(z)
r = s * (1.0 - s)
H = -np.eye(d) - X.T @ (r[:, None] * X)
Sigma = np.linalg.inv(-H)
info = {"iters": it + 1, "w_hat": w, "Sigma": Sigma}
return w, Sigma, info
def gaussian_contour_level_set(grid_x1, grid_x2, mu, Sigma):
"""Return unnormalized Gaussian density on a meshgrid."""
mu = np.asarray(mu)
Sigma = np.asarray(Sigma)
Sinv = np.linalg.inv(Sigma)
dx1 = grid_x1 - mu[0]
dx2 = grid_x2 - mu[1]
quad = (Sinv[0, 0] * dx1**2 + 2 * Sinv[0, 1] * dx1 * dx2 + Sinv[1, 1] * dx2**2)
return np.exp(-0.5 * quad)
# Generate data and fit Laplace posterior in w-space
X_lr, y_lr = make_toy_2d_classification(n=20, rng=rng)
w_hat, Sigma_hat, info = laplace_logistic_regression_2d(X_lr, y_lr)
print(f"Laplace MAP w_hat = {w_hat}, iters = {info['iters']}")
# (a) Prior contours in w-space: N(0, I)
# Choose w-grid based on posterior spread (robust range)
w_std = np.sqrt(np.diag(Sigma_hat))
w_margin = 3.0
w1 = np.linspace(min(-4, w_hat[0] - w_margin * w_std[0]), max(4, w_hat[0] + w_margin * w_std[0]), 220)
w2 = np.linspace(min(-4, w_hat[1] - w_margin * w_std[1]), max(4, w_hat[1] + w_margin * w_std[1]), 220)
W1, W2 = np.meshgrid(w1, w2)
prior_den = np.exp(-0.5 * (W1**2 + W2**2))
post_den = gaussian_contour_level_set(W1, W2, w_hat, Sigma_hat)
# (d) Predictive contours in x-space using logistic-Gaussian integral approximation (MacKay)
x_margin = 1.2
x1 = np.linspace(X_lr[:, 0].min() - x_margin, X_lr[:, 0].max() + x_margin, 240)
x2 = np.linspace(X_lr[:, 1].min() - x_margin, X_lr[:, 1].max() + x_margin, 240)
XX1, XX2 = np.meshgrid(x1, x2)
Xgrid = np.column_stack([XX1.ravel(), XX2.ravel()])
mu_f = Xgrid @ w_hat
s2_f = np.sum((Xgrid @ Sigma_hat) * Xgrid, axis=1) # x^T Σ x
p_pos = logistic(mu_f / np.sqrt(1.0 + (np.pi / 8.0) * s2_f))
P = p_pos.reshape(XX1.shape)
# Plot (a)-(d)
fig, axes = plt.subplots(2, 2, figsize=(11.5, 9.2))
ax = axes[0, 0]
cs = ax.contour(W1, W2, prior_den, levels=8, cmap='Blues')
ax.clabel(cs, inline=True, fontsize=8)
ax.set_title(r'(a) Prior over $\mathbf{w}$: $\mathcal{N}(0, I)$')
ax.set_xlabel('$w_1$')
ax.set_ylabel('$w_2$')
ax.scatter([0], [0], c='k', s=25, label='prior mean')
ax.legend()
ax = axes[0, 1]
mask_p = (y_lr == 1)
mask_n = (y_lr == -1)
ax.scatter(X_lr[mask_p, 0], X_lr[mask_p, 1], c='C0', s=55, edgecolor='k', label='$y=+1$')
ax.scatter(X_lr[mask_n, 0], X_lr[mask_n, 1], c='C3', s=55, edgecolor='k', label='$y=-1$')
ax.set_title(r'(b) Toy data in $\mathbb{R}^2$ (n=20)')
ax.set_xlabel('$x_1$')
ax.set_ylabel('$x_2$')
ax.legend()
ax = axes[1, 0]
cs = ax.contour(W1, W2, post_den, levels=10, cmap='Purples')
ax.clabel(cs, inline=True, fontsize=8)
ax.scatter([w_hat[0]], [w_hat[1]], c='k', s=30, label=r'$\hat{\mathbf{w}}$ (MAP)')
ax.set_title(r'(c) Laplace posterior in $\mathbf{w}$-space')
ax.set_xlabel('$w_1$')
ax.set_ylabel('$w_2$')
ax.legend()
ax = axes[1, 1]
im = ax.contourf(XX1, XX2, P, levels=np.linspace(0, 1, 21), cmap='RdBu_r', alpha=0.9)
ax.contour(XX1, XX2, P, levels=[0.5], colors='k', linewidths=2.0)
ax.scatter(X_lr[mask_p, 0], X_lr[mask_p, 1], c='C0', s=55, edgecolor='k')
ax.scatter(X_lr[mask_n, 0], X_lr[mask_n, 1], c='C3', s=55, edgecolor='k')
ax.set_title(r'(d) Predictive $p(y=+1\mid x)$ (Laplace + MacKay approx)')
ax.set_xlabel('$x_1$')
ax.set_ylabel('$x_2$')
cbar = fig.colorbar(im, ax=ax)
cbar.set_label(r'$p(y=+1\mid x)$')
plt.tight_layout()
plt.show()
Laplace MAP w_hat = [0.67684382 0.43998697], iters = 6
Response Functions: Logistic vs Probit¶
Two standard choices to map latent values $f\in\mathbb{R}$ to probabilities $[0,1]$:
Logistic:
- Definition: $\sigma(f)=\dfrac{1}{1+e^{-f}}$
- Shape: S-curve, heavier tails
- Analytic integral? No (use approximation)
Probit:
- Definition: $\Phi(f)=\displaystyle\int_{-\infty}^{f}\mathcal{N}(t\mid 0,1)\,dt$
- Shape: S-curve, lighter tails
- Analytic integral? Yes (with Gaussian)
Both satisfy the symmetry $\sigma(f)=1-\sigma(-f)$, so $p(y_i\mid f_i)=\sigma(y_i f_i)$ works for both classes.
Let's visualize them side by side:
# ── Response functions and their derivatives (no log) ──
def sigmoid(z):
"""Logistic sigmoid σ(z) = 1/(1+exp(-z))."""
return logistic(z)
def probit(z):
"""Probit Φ(z) = CDF of standard normal."""
return norm.cdf(z)
# ── Visualization ──
z = np.linspace(-6, 6, 400)
# Response functions p(y=+1|f)
p_logistic = sigmoid(z)
p_probit = probit(z)
# First derivatives: dp/df
dp_logistic = p_logistic * (1.0 - p_logistic) # σ'(f) = σ(1-σ)
dp_probit = norm.pdf(z) # Φ'(f) = φ(f)
# Second derivatives: d²p/df²
d2p_logistic = dp_logistic * (1.0 - 2.0 * p_logistic) # σ''(f) = σ(1-σ)(1-2σ)
d2p_probit = -z * norm.pdf(z) # Φ''(f) = φ'(f) = -f φ(f)
fig, axes = plt.subplots(1, 3, figsize=(13, 3.8))
# Panel 1: response functions
axes[0].plot(z, p_logistic, lw=2.2, label=r'Logistic $\sigma(f)$')
axes[0].plot(z, p_probit, lw=2.2, ls='--', label=r'Probit $\Phi(f)$')
axes[0].axhline(0.5, color='gray', lw=0.8, ls=':')
axes[0].set_title('Response functions')
axes[0].set_xlabel('$f$')
axes[0].set_ylabel('$p$')
axes[0].set_ylim(-0.02, 1.02)
axes[0].grid(True, alpha=0.35, linestyle='--')
axes[0].legend(fontsize=9)
# Panel 2: first derivative dp/df
axes[1].plot(z, dp_logistic, lw=2.2, label=r'Logistic $\sigma(1-\sigma)$')
axes[1].plot(z, dp_probit, lw=2.2, ls='--', label=r'Probit $\phi(f)$')
axes[1].set_title(r'First derivative $\,d\sigma/df$')
axes[1].set_xlabel('$f$')
axes[1].set_ylabel(r'$d\sigma/df$')
axes[1].set_ylim(-0.01, 0.45)
axes[1].grid(True, alpha=0.35, linestyle='--')
axes[1].legend(fontsize=9)
# Panel 3: second derivative d²p/df²
axes[2].plot(z, d2p_logistic, lw=2.2, label=r'Logistic $\sigma(1-\sigma)(1-2\sigma)$')
axes[2].plot(z, d2p_probit, lw=2.2, ls='--', label=r'Probit $-f\,\phi(f)$')
axes[2].axhline(0.0, color='gray', lw=0.8, ls=':')
axes[2].set_title(r'Second derivative $\,d^2\sigma/df^2$')
axes[2].set_xlabel('$f$')
axes[2].set_ylabel(r'$d^2\sigma/df^2$')
axes[2].set_ylim(-0.3, 0.3)
axes[2].grid(True, alpha=0.35, linestyle='--')
axes[2].legend(fontsize=8)
plt.suptitle(r'Response function and its derivatives (for $y=+1$)', y=1.03, fontsize=12)
plt.tight_layout()
plt.show()
Likelihood Derivatives — Explicit Formulas¶
For binary labels $y_i\in\lbrace+1,-1\rbrace$, the likelihood is $p(y_i\mid f_i)=\sigma(y_i f_i)$. Define $t_i\triangleq y_if_i$ and $\pi_i\triangleq\sigma(t_i)=\sigma(y_if_i)$.
Logistic $\sigma(f)=\frac{1}{1+e^{-f}}$: $$\nabla_{f_i}\log p(y_i\mid f_i) = y_i(1-\pi_i), \qquad W_{ii} = \pi_i(1-\pi_i).$$
Probit $\Phi(f)$: $$\nabla_{f_i}\log p(y_i\mid f_i) = y_i\frac{\mathcal{N}(y_if_i)}{\Phi(y_if_i)}, \qquad W_{ii} = \left(\frac{\mathcal{N}(y_if_i)}{\Phi(y_if_i)}\right)^{2} + y_if_i\frac{\mathcal{N}(y_if_i)}{\Phi(y_if_i)}.$$
Why do we need $W$? $W$ is the curvature (precision) of the log-likelihood. It enters the Newton update and determines the covariance of the Laplace Gaussian: $$\Sigma = (K^{-1}+W)^{-1}.$$
2. Helper Functions: Kernels & Likelihood¶
We implement the RBF kernel and both logistic / probit likelihood interfaces needed later.
# ═══════════════════════════════════════════════
# Kernel
# ═══════════════════════════════════════════════
def rbf_kernel(X1, X2, lengthscale=1.0, variance=1.0):
"""Squared Exponential / RBF kernel for d-dimensional inputs.
Parameters
----------
X1 : (n1, d) or (n1,)
X2 : (n2, d) or (n2,)
Returns
-------
K : (n1, n2)
"""
X1 = np.atleast_2d(X1)
X2 = np.atleast_2d(X2)
sqdist = np.sum(X1**2, axis=1, keepdims=True) - 2*X1 @ X2.T + np.sum(X2**2, axis=1)
return variance * np.exp(-0.5 * sqdist / lengthscale**2)
# ═══════════════════════════════════════════════
# Likelihood helpers (logistic link)
# ═══════════════════════════════════════════════
def loglik_logistic(y, f):
"""Log-likelihood log p(y|f) = log σ(y*f) (logistic link)."""
return -np.logaddexp(0, -y * f) # numerically stable log σ(yf)
def grad_loglik_logistic(y, f):
"""∇_f log p(y|f) = y(1 − σ(yf)) (logistic link)."""
t = y * f
pi = sigmoid(t)
return y * (1.0 - pi)
def W_logistic(y, f):
"""W_ii = π_i(1−π_i) where π_i = σ(y_i f_i) (logistic link).
Returns a 1-D array (diagonal of W).
"""
t = y * f
pi = sigmoid(t)
return pi * (1.0 - pi)
# ═══════════════════════════════════════════════
# Likelihood helpers (probit link)
# ═══════════════════════════════════════════════
def loglik_probit(y, f):
"""Log-likelihood log p(y|f) = log Φ(yf) (probit link)."""
return norm.logcdf(y * f)
def grad_loglik_probit(y, f):
"""∇_f log p(y|f) = y φ(yf)/Φ(yf) (probit link)."""
t = y * f
return y * norm.pdf(t) / np.maximum(norm.cdf(t), 1e-12)
def W_probit(y, f):
"""W_ii for probit link (always non-negative)."""
t = y * f
phi = norm.pdf(t)
Phi = np.maximum(norm.cdf(t), 1e-12)
r = phi / Phi
return np.maximum(r**2 + t * r, 1e-12)
print("✓ Kernels and likelihood helpers loaded.")
✓ Kernels and likelihood helpers loaded.
3. Why the Posterior Is Non-Gaussian¶
In GP regression, posterior = Gaussian × Gaussian = Gaussian (easy!).
In GP classification, the unnormalized log posterior is: $$\Psi(\mathbf{f}) = \log p(\mathbf{y}\mid\mathbf{f}) + \log p(\mathbf{f}\mid X) = \underbrace{\sum_{i=1}^n \log\sigma(y_i f_i)}_{\text{log-likelihood (non-quadratic!)}} - \underbrace{\tfrac{1}{2}\mathbf{f}^\top K^{-1}\mathbf{f} - \tfrac{1}{2}\log\lvert K\rvert - \tfrac{n}{2}\log 2\pi}_{\text{log GP prior (quadratic in }\mathbf{f}\text{)}}.$$
The log-likelihood term $\sum_i\log\sigma(y_i f_i)$ is not quadratic in $\mathbf{f}$, so $p(\mathbf{f}\mid X,\mathbf{y})\propto\exp(\Psi(\mathbf{f}))$ is not Gaussian.
Gradient and Hessian¶
$$\nabla\Psi(\mathbf{f}) = \nabla\log p(\mathbf{y}\mid\mathbf{f}) - K^{-1}\mathbf{f},$$ $$\nabla\nabla\Psi(\mathbf{f}) = \underbrace{\nabla\nabla\log p(\mathbf{y}\mid\mathbf{f})}_{=-W} - K^{-1} = -(W+K^{-1}).$$
Here $W\triangleq -\nabla\nabla\log p(\mathbf{y}\mid\mathbf{f})$ is a diagonal matrix (because each $y_i$ depends only on $f_i$).
Note: If the likelihood $p(\mathbf{y}\mid\mathbf{f})$ is log-concave (true for both logistic and probit), then $\Psi(\mathbf{f})$ is concave and has a unique global maximum $\hat{\mathbf{f}}$.
Example 1: Visualizing the non-Gaussian posterior (1-D toy)¶
To build intuition, consider the simplest case: one training point $(x_0, y_0=+1)$ with a 1-D "kernel matrix" $K=[k_{00}]$, so $f$ is scalar.
We will illustrate two common link functions:
- Logistic: $p(y\mid f) = \sigma(yf)$
- Probit: $p(y\mid f) = \Phi(yf)$
The (unnormalized) posterior density is proportional to: $$p(f\mid y) \;\propto\; p(y\mid f)\;\exp\!\left(-\frac{f^2}{2k_{00}}\right).$$
Below we use the kernel entry $k_{00}$ (prior variance) as the tuning knob:
- Small $k_{00}$ (strong prior) → posterior looks close to Gaussian
- Large $k_{00}$ (weak prior) → posterior becomes more skewed (non-Gaussian)
Approximation on a grid¶
In this 1-D demo we evaluate the (unnormalized) log posterior on a grid $\{f_i\}$, i.e. we compute values $\Psi_i = \log \tilde p(f_i\mid y)$. To plot a density (so that the total area is about $1$), we need the normalizing constant $Z = \int \exp(\Psi(f))\,df$.
Because we only have values on a finite grid, we approximate the integral using a Riemann sum with spacing $\Delta f = df$: $$Z \;\approx\; \sum_i \exp(\Psi_i)\,\Delta f.$$
Therefore the normalized density at grid points is approximated by $p_i \approx \exp(\Psi_i)/Z$, which in discrete form means $\sum_i p_i\,\Delta f \approx 1$.
Numerical stability: computing $\sum_i \exp(\Psi_i)$ directly can overflow/underflow. logsumexp stably computes $\log\sum_i \exp(\Psi_i)$, so we normalize in log-space:
$$p_i = \exp\Big(\Psi_i - \operatorname{logsumexp}(\Psi) - \log\Delta f\Big).$$
Approximation note: the accuracy depends on the grid range and spacing $\Delta f$; a smaller $\Delta f$ (and a sufficiently wide range) makes the discrete approximation closer to the true continuous density.
# Scalar toy: one observation y=+1, varying kernel prior variance k00
y0 = 1.0 # label (+1 / -1)
f_grid = np.linspace(-6, 10, 500)
df = f_grid[1] - f_grid[0]
# Kernel settings (k00 is the 1x1 kernel matrix entry, i.e., prior variance)
k00_list = [0.25, 40.0] # small -> near-Gaussian; large -> more skew (non-Gaussian)
from scipy.special import logsumexp, expit
from scipy.stats import norm
# Two link functions to compare (defined locally to avoid name shadowing bugs)
link_specs = [
dict(
name='logistic',
color='steelblue',
prob=lambda t: expit(t),
prob_label=r'$\sigma(yf)$',
loglik=lambda t: -np.logaddexp(0.0, -t), # log σ(t)
W_hat=lambda t_hat: expit(t_hat) * (1.0 - expit(t_hat)),
),
dict(
name='probit',
color='seagreen',
prob=lambda t: norm.cdf(t),
prob_label=r'$\Phi(yf)$',
loglik=lambda t: norm.logcdf(t), # log Φ(t)
W_hat=lambda t_hat: (
(lambda phi, Phi, r: np.maximum(r**2 + t_hat * r, 1e-12))(
norm.pdf(t_hat),
np.maximum(norm.cdf(t_hat), 1e-12),
norm.pdf(t_hat) / np.maximum(norm.cdf(t_hat), 1e-12),
)
),
),
]
nrows = len(k00_list)
fig, axes = plt.subplots(nrows, 3, figsize=(18, 4 * nrows), sharex=True)
if nrows == 1:
axes = axes.reshape(1, 3)
for row_idx, k00 in enumerate(k00_list):
# Prior density p(f) = N(0, k00)
prior_pdf = norm.pdf(f_grid, loc=0.0, scale=np.sqrt(k00))
log_prior = -0.5 * f_grid**2 / k00
t_grid = y0 * f_grid
results = {}
for spec in link_specs:
# Unnormalized posterior (computed via log terms for numerical stability)
log_lik = spec['loglik'](t_grid)
Psi = log_lik + log_prior
# Mode (brute force for 1-D demo)
idx_mode = np.argmax(Psi)
f_hat = f_grid[idx_mode]
t_hat = y0 * f_hat
# Laplace: W at the mode, then variance = (1/k00 + W)^{-1}
W_hat = float(spec['W_hat'](t_hat))
sigma2_laplace = 1.0 / (1.0 / k00 + W_hat)
Psi_laplace = Psi[idx_mode] - 0.5 * (f_grid - f_hat) ** 2 / sigma2_laplace
# Normalize for plotting as densities
p_true = np.exp(Psi - logsumexp(Psi) - np.log(df))
p_laplace = np.exp(Psi_laplace - logsumexp(Psi_laplace) - np.log(df))
results[spec['name']] = dict(
spec=spec,
f_hat=f_hat,
sigma2_laplace=sigma2_laplace,
prob_yf=spec['prob'](t_grid),
p_true=p_true,
p_laplace=p_laplace,
)
# (Col 1) prior density + both link probabilities on a second axis
ax0 = axes[row_idx, 0]
ax0.plot(f_grid, prior_pdf, lw=2.0, color='gray', label=r'Prior $\mathcal{N}(0,k_{00})$')
ax0.set_ylabel('density')
ax0.set_title(rf'$k_{{00}}={k00}$: prior and link functions')
ax0.set_xlim(-6, 10)
ax0b = ax0.twinx()
ax0b.set_ylabel('probability')
ax0b.set_ylim(-0.02, 1.02)
for name, out in results.items():
spec = out['spec']
ax0b.plot(f_grid, out['prob_yf'], lw=2.4, color=spec['color'], label=f"{name}: {spec['prob_label']}")
ax0.axvline(out['f_hat'], color=spec['color'], lw=1.3, ls=':', alpha=0.9)
# Merge legends from both axes
h0, l0 = ax0.get_legend_handles_labels()
h1, l1 = ax0b.get_legend_handles_labels()
ax0.legend(h0 + h1, l0 + l1, fontsize=9, loc='upper left')
# (Col 2) logistic posterior vs Laplace
ax1 = axes[row_idx, 1]
out = results['logistic']
spec = out['spec']
ax1.fill_between(f_grid, out['p_true'], alpha=0.25, color=spec['color'], label='posterior')
ax1.plot(f_grid, out['p_true'], lw=2.2, color=spec['color'])
ax1.plot(f_grid, out['p_laplace'], lw=2.0, ls='--', color='crimson', label='Laplace')
ax1.axvline(out['f_hat'], color=spec['color'], lw=1.3, ls=':', alpha=0.9)
ax1.set_ylabel('density')
ax1.set_title('Posterior vs Laplace (logistic)')
ax1.legend(fontsize=9)
ax1.set_xlim(-6, 10)
# (Col 3) probit posterior vs Laplace
ax2 = axes[row_idx, 2]
out = results['probit']
spec = out['spec']
ax2.fill_between(f_grid, out['p_true'], alpha=0.25, color=spec['color'], label='posterior')
ax2.plot(f_grid, out['p_true'], lw=2.2, color=spec['color'])
ax2.plot(f_grid, out['p_laplace'], lw=2.0, ls='--', color='crimson', label='Laplace')
ax2.axvline(out['f_hat'], color=spec['color'], lw=1.3, ls=':', alpha=0.9)
ax2.set_ylabel('density')
ax2.set_title('Posterior vs Laplace (probit)')
ax2.legend(fontsize=9)
ax2.set_xlim(-6, 10)
# Optional numeric summary
print(
f"k00={k00:>5}: "
f"logistic f̂={results['logistic']['f_hat']:.3f}, var={results['logistic']['sigma2_laplace']:.3f}; "
f"probit f̂={results['probit']['f_hat']:.3f}, var={results['probit']['sigma2_laplace']:.3f}"
)
for ax in axes[-1, :]:
ax.set_xlabel('$f$')
plt.suptitle(
'1-D toy: one observation $y=+1$, tuning kernel variance $k_{00}$ (logistic vs probit)',
y=1.01, fontsize=12
)
plt.tight_layout()
plt.show()
k00= 0.25: logistic f̂=0.124, var=0.235; probit f̂=0.188, var=0.218 k00= 40.0: logistic f̂=2.657, var=11.595; probit f̂=2.048, var=7.698
4. Laplace Approximation — Mode Finding via Newton's Method¶
Idea: Find the mode $\hat{\mathbf{f}}=\arg\max_{\mathbf{f}}\Psi(\mathbf{f})$, then approximate the posterior by a Gaussian centered at $\hat{\mathbf{f}}$ with covariance equal to the negative inverse Hessian at $\hat{\mathbf{f}}$:
$$q(\mathbf{f}\mid X,\mathbf{y}) = \mathcal{N}\!\left(\hat{\mathbf{f}},\;(K^{-1}+W)^{-1}\right).$$
Newton's Method¶
At the mode, $\nabla\Psi=\mathbf{0}$. Newton's update:
$$\mathbf{f}^{\text{new}} = \mathbf{f} - (\nabla\nabla\Psi)^{-1}\nabla\Psi = (K^{-1}+W)^{-1}\!\left(W\mathbf{f}+\nabla\log p(\mathbf{y}\mid\mathbf{f})\right).$$
Derivation sketch:
- Line 1: standard Newton update
- Line 2: substitute $\nabla\nabla\Psi = -(K^{-1}+W)$ and $\nabla\Psi = \nabla\log p(\mathbf{y}\mid\mathbf{f}) - K^{-1}\mathbf{f}$
- Line 3: simplify $(K^{-1}+W)\mathbf{f} - K^{-1}\mathbf{f} = W\mathbf{f}$
Numerically Stable Implementation via $B$¶
Directly inverting $(K^{-1}+W)$ is unstable. Using the matrix inversion lemma:
$$(K^{-1}+W)^{-1} = K - KW^{1/2}B^{-1}W^{1/2}K, \quad B = I + W^{1/2}KW^{1/2}.$$
$B$ is symmetric positive definite → Cholesky decomposition $LL^\top = B$ is numerically stable. We solve via triangular systems.
Why is this better? Forming $B$ costs $\mathcal{O}(n^2)$ extra work (since $W$ is diagonal), and the Cholesky factor $L$ can be reused everywhere.
# ═══════════════════════════════════════════════
# Laplace Approximation for GP Classification
# (Algorithm 3.1 from Rasmussen & Williams)
# ═══════════════════════════════════════════════
def laplace_mode_finding(K, y, link='logistic', max_iter=50, tol=1e-4):
"""Find the posterior mode f̂ using Newton's method.
Parameters
----------
K : (n, n) kernel matrix
y : (n,) labels in {+1, -1}
link : 'logistic' or 'probit'
Returns
-------
f_hat : (n,) posterior mode
W_diag : (n,) diagonal of W at the mode
L : (n, n) Cholesky factor of B = I + W^{1/2} K W^{1/2}
log_ml : approximate log marginal likelihood
info : dict with convergence history
"""
n = len(y)
jitter = 1e-6 * np.eye(n)
f = np.zeros(n) # initialize at the prior mean
# Select likelihood functions based on link
if link == 'logistic':
_loglik = loglik_logistic
_grad = grad_loglik_logistic
_W = W_logistic
elif link == 'probit':
_loglik = loglik_probit
_grad = grad_loglik_probit
_W = W_probit
else:
raise ValueError(f"Unknown link: {link}")
history = []
K_jit = K + jitter # jittered kernel for stable solves
for it in range(max_iter):
# Step 1: compute W = diag of -∇²log p(y|f)
W_diag = _W(y, f)
W_sqrt = np.sqrt(np.maximum(W_diag, 1e-12))
# Step 2: B = I + W^{1/2} K W^{1/2}
B = np.eye(n) + (W_sqrt[:, None] * K) * W_sqrt[None, :]
L = np.linalg.cholesky(B)
# Step 3: Newton target b = W f + ∇ log p(y|f)
grad = _grad(y, f)
b = W_diag * f + grad
# Step 4: f_new = (K^{-1}+W)^{-1} b via Woodbury (R&W Alg. 3.1)
# a = b − W^{1/2} L^{−T} L^{−1} W^{1/2} K b
# f_new = K a
Kb = K @ b
v = np.linalg.solve(L, W_sqrt * Kb) # L \ (W^{1/2} K b)
a_rw = b - W_sqrt * np.linalg.solve(L.T, v)
f_new = K @ a_rw
# Log unnormalized posterior Ψ(f)
log_post = np.sum(_loglik(y, f_new)) - 0.5 * f_new @ np.linalg.solve(
K_jit, f_new)
history.append(log_post)
# Check convergence
if np.max(np.abs(f_new - f)) < tol:
f = f_new
break
f = f_new
# Recompute W, L at the final mode
W_diag = _W(y, f)
W_sqrt = np.sqrt(np.maximum(W_diag, 1e-12))
B = np.eye(n) + (W_sqrt[:, None] * K) * W_sqrt[None, :]
L = np.linalg.cholesky(B)
# Approximate log marginal likelihood (eq. 3.32 in R&W)
log_ml = (np.sum(_loglik(y, f))
- 0.5 * f @ np.linalg.solve(K_jit, f)
- np.sum(np.log(np.diag(L))))
converged = (it + 1) < max_iter
return f, W_diag, L, log_ml, {'history': history, 'n_iter': it+1, 'converged': converged}
print("✓ laplace_mode_finding() defined.")
✓ laplace_mode_finding() defined.
5. Prediction — Posterior Mean, Variance & Class Probability¶
After obtaining $\hat{\mathbf{f}}$ and $W$, we predict at a new test point $\mathbf{x}_*$.
Posterior Mean (Laplace)¶
$$\mathbb{E}_q[f_*\mid\mathbf{x}_*,\mathcal{D}] = \mathbf{k}(\mathbf{x}_*)^\top K^{-1}\hat{\mathbf{f}}.$$
Posterior Variance (Laplace)¶
Using the law of total variance and the matrix inversion lemma: $$\mathrm{Var}_q[f_*\mid\mathbf{x}_*,\mathcal{D}] = k(\mathbf{x}_*,\mathbf{x}_*) - \mathbf{v}^\top\mathbf{v}, \quad\text{where } \mathbf{v}=L\backslash(W^{1/2}\mathbf{k}(\mathbf{x}_*)).$$
Class Probability¶
Two ways to convert the latent Gaussian $q(f_*)=\mathcal{N}(\mu_*,\sigma_*^2)$ into a class probability:
MAP prediction (fast, ignores uncertainty): $$\hat{\pi}_* = \sigma(\mu_*).$$
Averaged prediction (correct Bayesian answer): $$\bar{\pi}_* = \int\sigma(f_*)\,q(f_*)\,df_*.$$
- Probit link → closed form: $\bar{\pi}_* = \Phi\!\left(\frac{\mu_*}{\sqrt{1+\sigma_*^2}}\right)$.
- Logistic link → approximate: $\bar{\pi}_* \approx \sigma\!\left(\frac{\mu_*}{\sqrt{1+\pi\sigma_*^2/8}}\right)$.
Key take-away: When uncertainty is large, averaged prediction is more calibrated; MAP can be over-confident.
# ═══════════════════════════════════════════════
# Prediction (Algorithm 3.2 from R&W)
# ═══════════════════════════════════════════════
def laplace_predict(X_train, y_train, X_test, f_hat, W_diag, L, K_train,
kernel_fn, link='logistic', **kernel_kwargs):
"""Laplace-approximate GP classification prediction.
Parameters
----------
X_train : (n, d) training inputs
y_train : (n,) training labels {+1, -1}
X_test : (m, d) test inputs
f_hat : (n,) posterior mode
W_diag : (n,) diagonal of W at the mode
L : (n, n) Cholesky of B
K_train : (n, n) kernel matrix K(X,X)
kernel_fn: kernel function
link : 'logistic' or 'probit'
Returns
-------
mu_star : (m,) predictive mean of f_*
var_star : (m,) predictive variance of f_*
pi_map : (m,) MAP class probability σ(μ_*)
pi_avg : (m,) averaged class probability ∫σ(f)q(f)df
"""
W_sqrt = np.sqrt(W_diag)
# k_* = K(X_train, X_test) shape (n, m)
k_star = kernel_fn(X_train, X_test, **kernel_kwargs)
# k_** = diag K(X_test, X_test) shape (m,)
k_ss = np.diag(kernel_fn(X_test, X_test, **kernel_kwargs))
# Predictive mean: μ_* = k_*^T K^{-1} f̂
# Use K^{-1} f̂ indirectly: at the mode, K^{-1} f̂ = ∇ log p(y|f̂)
if link == 'logistic':
alpha = grad_loglik_logistic(y_train, f_hat) # = K^{-1} f̂ at the mode
else:
alpha = grad_loglik_probit(y_train, f_hat)
mu_star = k_star.T @ alpha
# Predictive variance: var_* = k_** - v^T v, v = L \ (W^{1/2} k_*)
v = np.linalg.solve(L, W_sqrt[:, None] * k_star) # (n, m)
var_star = np.maximum(k_ss - np.sum(v**2, axis=0), 1e-10)
# MAP class probability
if link == 'logistic':
pi_map = sigmoid(mu_star)
else:
pi_map = probit(mu_star)
# Averaged class probability
if link == 'logistic':
# Approximate: σ(μ / √(1 + π σ² / 8))
kappa = 1.0 / np.sqrt(1.0 + np.pi * var_star / 8.0)
pi_avg = sigmoid(kappa * mu_star)
else:
# Exact: Φ(μ / √(1 + σ²))
pi_avg = probit(mu_star / np.sqrt(1.0 + var_star))
return mu_star, var_star, pi_map, pi_avg
print("✓ laplace_predict() defined.")
✓ laplace_predict() defined.
6. Example 2 — 1D Binary Classification¶
We generate a simple 1-D classification dataset from a mixture of three Gaussians:
- Class $+1$: centered at $x=-4$ and $x=4$
- Class $-1$: centered at $x=0$
This creates a non-linearly separable problem (class $+1$ wraps around class $-1$), which a linear classifier cannot handle but a GP can.
What to look for:
- How the latent function $f(x)$ swings positive / negative in the regions of each class
- How the predictive probability transitions smoothly between classes
- The uncertainty (variance) grows in regions with no data
# ── Generate 1-D dataset ──
n_per_group = 10
x_pos1 = rng.normal(-3, 1.0, n_per_group) # class +1 (left cluster)
x_pos2 = rng.normal( 3, 1.0, n_per_group) # class +1 (right cluster)
x_neg = rng.normal( 0, 1.0, 2*n_per_group) # class -1 (middle)
X_train_1d = np.concatenate([x_pos1, x_pos2, x_neg]).reshape(-1, 1)
y_train_1d = np.concatenate([np.ones(2*n_per_group), -np.ones(2*n_per_group)])
# Shuffle
perm = rng.permutation(len(y_train_1d))
X_train_1d = X_train_1d[perm]
y_train_1d = y_train_1d[perm]
# Visualize
plt.figure(figsize=(9, 2.5))
mask_p = y_train_1d == 1
mask_n = y_train_1d == -1
plt.scatter(X_train_1d[mask_p, 0], np.ones(mask_p.sum()), marker='o', s=40,
c='steelblue', edgecolors='k', lw=0.4, label='$y=+1$')
plt.scatter(X_train_1d[mask_n, 0], np.zeros(mask_n.sum()), marker='s', s=40,
c='tomato', edgecolors='k', lw=0.4, label='$y=-1$')
plt.xlabel('$x$')
plt.ylabel('$y$ (plotted as 1 / 0)')
plt.yticks([0, 1])
plt.title('1-D classification dataset (3 clusters)')
plt.legend()
plt.tight_layout()
plt.show()
# ── Run Laplace GPC on the 1-D dataset ──
ell_1d, sf2_1d = 2.0, 4.0 # lengthscale and signal variance
K_1d = rbf_kernel(X_train_1d, X_train_1d, lengthscale=ell_1d, variance=sf2_1d)
f_hat_1d, W_1d, L_1d, lml_1d, info_1d = laplace_mode_finding(
K_1d, y_train_1d, link='logistic', max_iter=100)
if info_1d['converged']:
print(f"Newton converged in {info_1d['n_iter']} iterations")
else:
print(f"Newton reached max iterations ({info_1d['n_iter']}), may not have converged")
print(f"Approx log marginal likelihood = {lml_1d:.3f}")
# ── Predict on a dense grid ──
X_test_1d = np.linspace(-8, 8, 500).reshape(-1, 1)
mu_1d, var_1d, pi_map_1d, pi_avg_1d = laplace_predict(
X_train_1d, y_train_1d, X_test_1d,
f_hat_1d, W_1d, L_1d, K_1d,
rbf_kernel, link='logistic',
lengthscale=ell_1d, variance=sf2_1d)
# ── Plot ──
fig, axes = plt.subplots(2, 1, figsize=(10, 7), sharex=True)
# Panel (a): Predictive probability
ax = axes[0]
ax.scatter(X_train_1d[mask_p, 0], np.ones(mask_p.sum()), marker='o', s=40,
c='steelblue', edgecolors='k', lw=0.4, label='$y=+1$ data')
ax.scatter(X_train_1d[mask_n, 0], np.zeros(mask_n.sum()), marker='s', s=40,
c='tomato', edgecolors='k', lw=0.4, label='$y=-1$ data')
ax.plot(X_test_1d[:, 0], pi_avg_1d, lw=2.5, color='purple', label='$\\bar{\\pi}_*$ (averaged)')
ax.plot(X_test_1d[:, 0], pi_map_1d, lw=2.0, ls='--', color='orange', label='$\\hat{\\pi}_*$ (MAP)')
ax.axhline(0.5, color='gray', lw=0.8, ls=':')
ax.set_ylabel('$p(y{=}+1 \\mid x)$')
ax.set_title('(a) Predictive class probability')
ax.legend(fontsize=9, ncols=2)
# Panel (b): Latent function
ax = axes[1]
std_1d = np.sqrt(var_1d)
ax.fill_between(X_test_1d[:, 0], mu_1d - 2*std_1d, mu_1d + 2*std_1d,
color='crimson', alpha=0.18, label='±2 std')
ax.plot(X_test_1d[:, 0], mu_1d, lw=2.5, color='crimson', label='latent mean $\\mu_*$')
ax.axhline(0, color='gray', lw=0.8, ls=':')
ax.scatter(X_train_1d[mask_p, 0], f_hat_1d[mask_p], marker='o', s=30,
c='steelblue', edgecolors='k', lw=0.3, alpha=0.7)
ax.scatter(X_train_1d[mask_n, 0], f_hat_1d[mask_n], marker='s', s=30,
c='tomato', edgecolors='k', lw=0.3, alpha=0.7)
ax.set_xlabel('$x$')
ax.set_ylabel('$f(x)$')
ax.set_title('(b) Latent function $f(x)$ with ±2 std')
ax.legend(fontsize=9)
plt.suptitle(f'1-D Laplace GPC ($\\ell={ell_1d}$, $\\sigma_f^2={sf2_1d:.0f}$, logistic link)',
y=1.02, fontsize=13)
plt.tight_layout()
plt.show()
Newton converged in 5 iterations Approx log marginal likelihood = -12.982
Newton Convergence¶
Let's verify that Newton's method converges rapidly (typical: 5–10 iterations). We plot $\Psi(\mathbf{f})$ at each iteration.
plt.figure(figsize=(6, 3.5))
plt.plot(range(1, len(info_1d['history'])+1), info_1d['history'], 'o-', lw=2, markersize=6)
plt.xlabel('Newton iteration')
plt.ylabel(r'$\Psi(\mathbf{f})$ (log unnorm. posterior)')
plt.title("Newton's method convergence for mode finding")
plt.tight_layout()
plt.show()
Averaged vs MAP Prediction — Intuition¶
Recall:
- MAP: $\hat{\pi}_*=\sigma(\mu_*)$ — plugs in the mean, ignores uncertainty → can be over-confident
- Averaged: $\bar{\pi}_*=\int\sigma(f_*)\,q(f_*)\,df_*$ — the correct Bayesian prediction → more calibrated
Because $\sigma(\cdot)$ is nonlinear, $\bar{\pi}_*\neq\sigma(\mathbb{E}_q[f_*])$ in general. They coincide only when $\mathrm{Var}_q[f_*]\to 0$ (high confidence).
Look at the plot above: in the uncertain regions (e.g., far from data), averaged prediction stays closer to 0.5 while MAP is more extreme.
Example 3: Effect of Lengthscale on GP Classification¶
Just as in GP regression, the lengthscale $\ell$ controls smoothness.
- Small $\ell$: The decision boundary follows the data closely → risk of over-fitting
- Large $\ell$: The boundary is very smooth → risk of under-fitting
- The marginal likelihood (evidence) can guide the choice of $\ell$
# ── Compare three lengthscales ──
ell_list = [0.5, 2.0, 6.0]
sf2_fixed = 4.0
fig, axes = plt.subplots(len(ell_list), 1, figsize=(10, 3.2*len(ell_list)), sharex=True)
for ax, ell_try in zip(axes, ell_list):
K_try = rbf_kernel(X_train_1d, X_train_1d, lengthscale=ell_try, variance=sf2_fixed)
f_try, W_try, L_try, lml_try, _ = laplace_mode_finding(K_try, y_train_1d, link='logistic')
mu_try, var_try, _, pi_avg_try = laplace_predict(
X_train_1d, y_train_1d, X_test_1d,
f_try, W_try, L_try, K_try,
rbf_kernel, link='logistic',
lengthscale=ell_try, variance=sf2_fixed)
ax.scatter(X_train_1d[mask_p, 0], np.ones(mask_p.sum()), marker='o', s=30,
c='steelblue', edgecolors='k', lw=0.3, alpha=0.7)
ax.scatter(X_train_1d[mask_n, 0], np.zeros(mask_n.sum()), marker='s', s=30,
c='tomato', edgecolors='k', lw=0.3, alpha=0.7)
ax.plot(X_test_1d[:, 0], pi_avg_try, lw=2.5, color='purple')
ax.axhline(0.5, color='gray', lw=0.8, ls=':')
ax.set_ylabel('$p(y{=}+1)$')
ax.set_title(rf'$\ell={ell_try}$, log evidence $={lml_try:.1f}$')
axes[-1].set_xlabel('$x$')
plt.suptitle('Effect of lengthscale on GP classification (evidence selects the best)', y=1.02, fontsize=13)
plt.tight_layout()
plt.show()
7. Example 4 — 2D Binary Classification (Half-Moons)¶
We now tackle a 2-D problem using a classic half-moons dataset. This is a non-linearly-separable problem that showcases:
- The decision boundary as a contour of $p(y{=}+1\mid\mathbf{x})=0.5$
- How uncertainty increases far from the data
- The difference between averaged and MAP predictions
We generate the data from scratch (no sklearn needed).
# ── Generate half-moons dataset (no sklearn!) ──
def make_moons(n_samples=100, noise=0.15, seed=42):
"""Generate two interleaving half circles (like sklearn.make_moons)."""
rng_m = np.random.default_rng(seed)
n_each = n_samples // 2
theta1 = np.linspace(0, np.pi, n_each)
theta2 = np.linspace(0, np.pi, n_each)
X1 = np.column_stack([np.cos(theta1), np.sin(theta1)])
X2 = np.column_stack([1 - np.cos(theta2), 1 - np.sin(theta2) - 0.5])
X = np.vstack([X1, X2]) + noise * rng_m.standard_normal((2*n_each, 2))
y = np.concatenate([np.ones(n_each), -np.ones(n_each)])
return X, y
X_moon, y_moon = make_moons(n_samples=80, noise=0.18, seed=42)
plt.figure(figsize=(6, 4.5))
m_p = y_moon == 1
m_n = y_moon == -1
plt.scatter(X_moon[m_p, 0], X_moon[m_p, 1], s=50, c='steelblue', edgecolors='k',
lw=0.4, label='$y=+1$', marker='o')
plt.scatter(X_moon[m_n, 0], X_moon[m_n, 1], s=50, c='tomato', edgecolors='k',
lw=0.4, label='$y=-1$', marker='s')
plt.xlabel('$x_1$')
plt.ylabel('$x_2$')
plt.title('Half-moons dataset (2-D)')
plt.legend()
plt.axis('equal')
plt.tight_layout()
plt.show()
# ── Laplace GPC on the 2-D half-moons ──
ell_2d, sf2_2d = 0.6, 5.0
K_moon = rbf_kernel(X_moon, X_moon, lengthscale=ell_2d, variance=sf2_2d)
f_hat_moon, W_moon, L_moon, lml_moon, info_moon = laplace_mode_finding(
K_moon, y_moon, link='logistic')
print(f"Newton converged in {info_moon['n_iter']} iterations, log ML ≈ {lml_moon:.2f}")
# ── Predict on a 2-D grid ──
grid_res = 100
x1_range = np.linspace(X_moon[:, 0].min()-0.8, X_moon[:, 0].max()+0.8, grid_res)
x2_range = np.linspace(X_moon[:, 1].min()-0.8, X_moon[:, 1].max()+0.8, grid_res)
xx1, xx2 = np.meshgrid(x1_range, x2_range)
X_grid = np.column_stack([xx1.ravel(), xx2.ravel()])
mu_grid, var_grid, pi_map_grid, pi_avg_grid = laplace_predict(
X_moon, y_moon, X_grid,
f_hat_moon, W_moon, L_moon, K_moon,
rbf_kernel, link='logistic',
lengthscale=ell_2d, variance=sf2_2d)
# ── Visualization: 4 panels ──
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
# (a) Averaged predictive probability
ax = axes[0, 0]
c = ax.contourf(xx1, xx2, pi_avg_grid.reshape(grid_res, grid_res),
levels=np.linspace(0, 1, 21), cmap='RdYlBu')
ax.contour(xx1, xx2, pi_avg_grid.reshape(grid_res, grid_res),
levels=[0.5], colors='k', linewidths=2)
ax.scatter(X_moon[m_p, 0], X_moon[m_p, 1], s=30, c='steelblue',
edgecolors='k', lw=0.3, marker='o')
ax.scatter(X_moon[m_n, 0], X_moon[m_n, 1], s=30, c='tomato',
edgecolors='k', lw=0.3, marker='s')
fig.colorbar(c, ax=ax, label='$\\bar{\\pi}_*$')
ax.set_title('(a) Averaged prediction $\\bar{\\pi}_*$')
ax.set_xlabel('$x_1$')
ax.set_ylabel('$x_2$')
# (b) MAP predictive probability
ax = axes[0, 1]
c = ax.contourf(xx1, xx2, pi_map_grid.reshape(grid_res, grid_res),
levels=np.linspace(0, 1, 21), cmap='RdYlBu')
ax.contour(xx1, xx2, pi_map_grid.reshape(grid_res, grid_res),
levels=[0.5], colors='k', linewidths=2)
ax.scatter(X_moon[m_p, 0], X_moon[m_p, 1], s=30, c='steelblue',
edgecolors='k', lw=0.3, marker='o')
ax.scatter(X_moon[m_n, 0], X_moon[m_n, 1], s=30, c='tomato',
edgecolors='k', lw=0.3, marker='s')
fig.colorbar(c, ax=ax, label='$\\hat{\\pi}_*$')
ax.set_title('(b) MAP prediction $\\hat{\\pi}_*$')
ax.set_xlabel('$x_1$')
ax.set_ylabel('$x_2$')
# (c) Latent mean
ax = axes[1, 0]
c = ax.contourf(xx1, xx2, mu_grid.reshape(grid_res, grid_res),
levels=20, cmap='coolwarm')
ax.contour(xx1, xx2, mu_grid.reshape(grid_res, grid_res),
levels=[0], colors='k', linewidths=2)
ax.scatter(X_moon[m_p, 0], X_moon[m_p, 1], s=30, c='steelblue',
edgecolors='k', lw=0.3, marker='o')
ax.scatter(X_moon[m_n, 0], X_moon[m_n, 1], s=30, c='tomato',
edgecolors='k', lw=0.3, marker='s')
fig.colorbar(c, ax=ax, label='$\\mu_*$')
ax.set_title('(c) Latent mean $\\mu_*$')
ax.set_xlabel('$x_1$')
ax.set_ylabel('$x_2$')
# (d) Predictive variance (uncertainty)
ax = axes[1, 1]
c = ax.contourf(xx1, xx2, var_grid.reshape(grid_res, grid_res),
levels=20, cmap='magma_r')
ax.scatter(X_moon[m_p, 0], X_moon[m_p, 1], s=30, c='steelblue',
edgecolors='white', lw=0.3, marker='o')
ax.scatter(X_moon[m_n, 0], X_moon[m_n, 1], s=30, c='tomato',
edgecolors='white', lw=0.3, marker='s')
fig.colorbar(c, ax=ax, label='$\\mathrm{Var}_q[f_*]$')
ax.set_title('(d) Predictive variance (uncertainty)')
ax.set_xlabel('$x_1$')
ax.set_ylabel('$x_2$')
plt.suptitle(f'2-D Laplace GPC on half-moons ($\\ell={ell_2d}$, $\\sigma_f^2={sf2_2d}$)',
y=1.02, fontsize=14)
plt.tight_layout()
plt.show()
Newton converged in 6 iterations, log ML ≈ -22.24
Example 5: 2-D Lengthscale Comparison¶
We repeat the 2-D classification with three different lengthscales to see the effect on the decision boundary. The log marginal likelihood (evidence) is shown in each panel title — the highest evidence picks the best $\ell$.
# ── 2-D: compare lengthscales ──
ell_list_2d = [0.2, 0.6, 2.0]
sf2_moon = 5.0
fig, axes = plt.subplots(1, 3, figsize=(15, 4.5))
for ax, ell_try in zip(axes, ell_list_2d):
K_try = rbf_kernel(X_moon, X_moon, lengthscale=ell_try, variance=sf2_moon)
f_try, W_try, L_try, lml_try, _ = laplace_mode_finding(K_try, y_moon, link='logistic')
_, _, _, pi_try = laplace_predict(
X_moon, y_moon, X_grid,
f_try, W_try, L_try, K_try,
rbf_kernel, link='logistic',
lengthscale=ell_try, variance=sf2_moon)
c = ax.contourf(xx1, xx2, pi_try.reshape(grid_res, grid_res),
levels=np.linspace(0, 1, 21), cmap='RdYlBu')
ax.contour(xx1, xx2, pi_try.reshape(grid_res, grid_res),
levels=[0.5], colors='k', linewidths=2)
ax.scatter(X_moon[m_p, 0], X_moon[m_p, 1], s=25, c='steelblue',
edgecolors='k', lw=0.3, marker='o')
ax.scatter(X_moon[m_n, 0], X_moon[m_n, 1], s=25, c='tomato',
edgecolors='k', lw=0.3, marker='s')
ax.set_title(rf'$\ell={ell_try}$, log ML$={lml_try:.1f}$')
ax.set_xlabel('$x_1$')
if ax == axes[0]:
ax.set_ylabel('$x_2$')
plt.suptitle('2-D GPC: decision boundary for different lengthscales (evidence in title)', y=1.02, fontsize=13)
plt.tight_layout()
plt.show()
8. Marginal Likelihood for Hyperparameter Selection¶
The kernel $k(\mathbf{x},\mathbf{x}')$ has hyperparameters $\boldsymbol{\theta}$ (e.g., lengthscale $\ell$, signal variance $\sigma_f^2$). We select them by maximizing the log marginal likelihood (a.k.a. evidence).
The exact marginal likelihood is: $$p(\mathbf{y}\mid X) = \int p(\mathbf{y}\mid\mathbf{f})\,p(\mathbf{f}\mid X)\,d\mathbf{f} = \int\exp(\Psi(\mathbf{f}))\,d\mathbf{f}.$$
Using a Taylor expansion of $\Psi$ around $\hat{\mathbf{f}}$ and evaluating the Gaussian integral:
$$\log q(\mathbf{y}\mid X) = \underbrace{-\tfrac{1}{2}\hat{\mathbf{f}}^\top K^{-1}\hat{\mathbf{f}}}_{\text{complexity penalty}} + \underbrace{\log p(\mathbf{y}\mid\hat{\mathbf{f}})}_{\text{data fit}} - \underbrace{\tfrac{1}{2}\log|B|}_{\text{Occam factor}}$$
where $|B|=|LL^\top|$ and $\log|B|=2\sum_i\log L_{ii}$ (reusing the Cholesky factor!).
Interpretation:
- Complexity penalty: penalizes modes that deviate from the prior mean
- Data fit: how well the mode explains the labels
- Occam factor: favors broader (simpler) posteriors
Example 6: Evidence Landscape (Grid Search)¶
We search over $(\ell, \sigma_f^2)$ and plot the log marginal likelihood surface. The red dot marks the best combination — the one the evidence selects.
How to read the heatmap:
- Brighter = higher evidence = better hyperparameters
- The evidence naturally balances data fit and complexity
# ── Evidence landscape over (ell, sf2) for the half-moons data ──
ell_grid = np.linspace(0.15, 2.5, 30)
sf2_grid = np.linspace(0.5, 15.0, 30)
lml_grid = np.full((len(sf2_grid), len(ell_grid)), -np.inf)
for i, sf2_v in enumerate(sf2_grid):
for j, ell_v in enumerate(ell_grid):
try:
K_tmp = rbf_kernel(X_moon, X_moon, lengthscale=ell_v, variance=sf2_v)
_, _, _, lml_v, _ = laplace_mode_finding(K_tmp, y_moon, link='logistic', max_iter=40)
lml_grid[i, j] = lml_v
except Exception:
pass # Cholesky may fail for extreme hyperparameters
i_best, j_best = np.unravel_index(np.nanargmax(lml_grid), lml_grid.shape)
ell_star = ell_grid[j_best]
sf2_star = sf2_grid[i_best]
plt.figure(figsize=(8, 5))
im = plt.imshow(lml_grid, origin='lower', aspect='auto', cmap='viridis',
extent=[ell_grid[0], ell_grid[-1], sf2_grid[0], sf2_grid[-1]])
plt.colorbar(im, label='Approx. log marginal likelihood')
plt.scatter([ell_star], [sf2_star], c='red', s=80, edgecolors='white', lw=1.0,
zorder=5, label=f'best: $\\ell$={ell_star:.2f}, $\\sigma_f^2$={sf2_star:.1f}')
plt.xlabel(r'lengthscale $\ell$')
plt.ylabel(r'signal variance $\sigma_f^2$')
plt.title('Evidence landscape for 2-D half-moons GPC')
plt.legend(fontsize=10)
plt.tight_layout()
plt.show()
print(f"Best hyperparameters: ell = {ell_star:.3f}, sigma_f^2 = {sf2_star:.2f}")
Best hyperparameters: ell = 0.555, sigma_f^2 = 15.00
Example 7: Best Evidence Hyperparameters — Final 2D Classification¶
Using the best hyperparameters selected by the marginal likelihood, we visualize the final GPC result. This is the evidence-tuned classifier.
# ── Run GPC with evidence-best hyperparameters ──
K_best = rbf_kernel(X_moon, X_moon, lengthscale=ell_star, variance=sf2_star)
f_hat_best, W_best, L_best, lml_best, _ = laplace_mode_finding(K_best, y_moon, link='logistic')
mu_best, var_best, pi_map_best, pi_avg_best = laplace_predict(
X_moon, y_moon, X_grid,
f_hat_best, W_best, L_best, K_best,
rbf_kernel, link='logistic',
lengthscale=ell_star, variance=sf2_star)
fig, axes = plt.subplots(1, 2, figsize=(13, 5))
# (a) Averaged prediction
ax = axes[0]
c = ax.contourf(xx1, xx2, pi_avg_best.reshape(grid_res, grid_res),
levels=np.linspace(0, 1, 21), cmap='RdYlBu')
ax.contour(xx1, xx2, pi_avg_best.reshape(grid_res, grid_res),
levels=[0.5], colors='k', linewidths=2.5)
ax.scatter(X_moon[m_p, 0], X_moon[m_p, 1], s=35, c='steelblue',
edgecolors='k', lw=0.3, marker='o')
ax.scatter(X_moon[m_n, 0], X_moon[m_n, 1], s=35, c='tomato',
edgecolors='k', lw=0.3, marker='s')
fig.colorbar(c, ax=ax, label='$\\bar{\\pi}_*$')
ax.set_title('(a) Averaged prediction (evidence-tuned)')
ax.set_xlabel('$x_1$')
ax.set_ylabel('$x_2$')
# (b) Uncertainty
ax = axes[1]
c = ax.contourf(xx1, xx2, var_best.reshape(grid_res, grid_res),
levels=20, cmap='magma_r')
ax.contour(xx1, xx2, pi_avg_best.reshape(grid_res, grid_res),
levels=[0.5], colors='white', linewidths=2, linestyles='--')
ax.scatter(X_moon[m_p, 0], X_moon[m_p, 1], s=35, c='steelblue',
edgecolors='white', lw=0.3, marker='o')
ax.scatter(X_moon[m_n, 0], X_moon[m_n, 1], s=35, c='tomato',
edgecolors='white', lw=0.3, marker='s')
fig.colorbar(c, ax=ax, label='$\\mathrm{Var}_q[f_*]$')
ax.set_title('(b) Uncertainty (evidence-tuned)')
ax.set_xlabel('$x_1$')
ax.set_ylabel('$x_2$')
plt.suptitle(f'Evidence-tuned GPC: $\\ell={ell_star:.2f}$, $\\sigma_f^2={sf2_star:.1f}$, log ML={lml_best:.1f}',
y=1.02, fontsize=13)
plt.tight_layout()
plt.show()
10. Example 9 — Real-World Data: Iris (2 classes, 2 features)¶
To show GP classification on a real dataset, we use the classic Iris dataset (built into many textbooks). We pick the two hardest classes (Versicolor vs Virginica) and the two most discriminative features (petal length and petal width).
We download the dataset as a CSV from the UCI Machine Learning Repository.
# ── Load Iris dataset (no sklearn, just CSV download) ──
import urllib.request, csv, io
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
try:
response = urllib.request.urlopen(url, timeout=10)
raw = response.read().decode('utf-8')
except Exception:
# Fallback: generate a simple synthetic Iris-like dataset
print("⚠ Could not download Iris data. Using a synthetic fallback.")
raw = None
if raw is not None:
reader = csv.reader(io.StringIO(raw))
rows = [r for r in reader if len(r) == 5]
# Columns: sepal_length, sepal_width, petal_length, petal_width, class
# We pick Versicolor (class +1) vs Virginica (class -1), all 4 features
iris_X, iris_y = [], []
for r in rows:
if 'versicolor' in r[4]:
iris_X.append([float(r[0]), float(r[1]), float(r[2]), float(r[3])]) # all 4 features
iris_y.append(+1)
elif 'virginica' in r[4]:
iris_X.append([float(r[0]), float(r[1]), float(r[2]), float(r[3])])
iris_y.append(-1)
iris_X = np.array(iris_X)
iris_y = np.array(iris_y)
else:
# Synthetic fallback (4-D clusters)
iris_X = np.vstack([rng.normal([5.0, 3.2, 4.2, 1.3], [0.5, 0.3, 0.5, 0.2], (50, 4)),
rng.normal([6.5, 2.9, 5.5, 2.0], [0.5, 0.3, 0.5, 0.2], (50, 4))])
iris_y = np.concatenate([np.ones(50), -np.ones(50)])
# Standardize features for better kernel behavior
iris_mean = iris_X.mean(axis=0)
iris_std = iris_X.std(axis=0)
iris_Xn = (iris_X - iris_mean) / iris_std
feature_names = ['Sepal length', 'Sepal width', 'Petal length', 'Petal width']
print(f"Dataset: {len(iris_y)} samples, {(iris_y==1).sum()} Versicolor, {(iris_y==-1).sum()} Virginica")
print(f"Features used: {feature_names}")
# Pairwise scatter plots for all four features
mp = iris_y == 1
mn = iris_y == -1
pairs = [
(0, 2, 'Sepal length', 'Petal length'),
(1, 3, 'Sepal width', 'Petal width'),
(2, 3, 'Petal length', 'Petal width'),
]
fig, axes = plt.subplots(1, 3, figsize=(14, 4))
for ax, (ci, cj, xl, yl) in zip(axes, pairs):
ax.scatter(iris_Xn[mp, ci], iris_Xn[mp, cj], s=50, c='steelblue', edgecolors='k',
lw=0.4, label='Versicolor ($y=+1$)', marker='o')
ax.scatter(iris_Xn[mn, ci], iris_Xn[mn, cj], s=50, c='tomato', edgecolors='k',
lw=0.4, label='Virginica ($y=-1$)', marker='s')
ax.set_xlabel(f'{xl} (standardized)')
ax.set_ylabel(f'{yl} (standardized)')
ax.set_title(f'{xl} vs {yl}')
axes[0].legend(fontsize=9)
plt.suptitle('Iris: Versicolor vs Virginica — all 4 features', fontsize=13)
plt.tight_layout()
plt.show()
Dataset: 100 samples, 50 Versicolor, 50 Virginica Features used: ['Sepal length', 'Sepal width', 'Petal length', 'Petal width']
# ── Step 1: Hyperparameter optimisation via evidence grid search ──
ell_grid_iris = np.linspace(0.2, 3.0, 25)
sf2_grid_iris = np.linspace(0.5, 15.0, 25)
lml_grid_iris = np.full((len(sf2_grid_iris), len(ell_grid_iris)), -np.inf)
for i, sf2_v in enumerate(sf2_grid_iris):
for j, ell_v in enumerate(ell_grid_iris):
try:
K_tmp = rbf_kernel(iris_Xn, iris_Xn, lengthscale=ell_v, variance=sf2_v)
_, _, _, lml_v, _ = laplace_mode_finding(K_tmp, iris_y, link='logistic', max_iter=40)
lml_grid_iris[i, j] = lml_v
except Exception:
pass # Cholesky may fail for extreme hyperparameters
i_best_iris, j_best_iris = np.unravel_index(np.nanargmax(lml_grid_iris), lml_grid_iris.shape)
ell_iris_star = ell_grid_iris[j_best_iris]
sf2_iris_star = sf2_grid_iris[i_best_iris]
plt.figure(figsize=(8, 5))
im = plt.imshow(lml_grid_iris, origin='lower', aspect='auto', cmap='viridis',
extent=[ell_grid_iris[0], ell_grid_iris[-1],
sf2_grid_iris[0], sf2_grid_iris[-1]])
plt.colorbar(im, label='Approx. log marginal likelihood')
plt.scatter([ell_iris_star], [sf2_iris_star], c='red', s=80,
edgecolors='white', lw=1.0, zorder=5,
label=f'best: $\\ell$={ell_iris_star:.2f}, $\\sigma_f^2$={sf2_iris_star:.1f}')
plt.xlabel(r'lengthscale $\ell$')
plt.ylabel(r'signal variance $\sigma_f^2$')
plt.title('Evidence landscape for Iris GPC (4 features)')
plt.legend(fontsize=10)
plt.tight_layout()
plt.show()
print(f"Best hyperparameters: ell = {ell_iris_star:.3f}, sigma_f^2 = {sf2_iris_star:.2f}")
# ── Step 2: GP classification with evidence-best hyperparameters ──
K_iris = rbf_kernel(iris_Xn, iris_Xn, lengthscale=ell_iris_star, variance=sf2_iris_star)
f_iris, W_iris, L_iris, lml_iris, info_iris = laplace_mode_finding(
K_iris, iris_y, link='logistic')
print(f"Newton iterations: {info_iris['n_iter']}, log ML = {lml_iris:.2f}")
pred_class = np.sign(f_iris)
acc = np.mean(pred_class == iris_y) * 100
print(f"Training accuracy (4 features, evidence-tuned): {acc:.1f}%")
# ── Step 3: 2-D decision-boundary slices (remaining dims fixed at mean = 0) ──
slice_pairs = [
(2, 3, 'Petal length (std)', 'Petal width (std)'),
(0, 2, 'Sepal length (std)', 'Petal length (std)'),
(1, 3, 'Sepal width (std)', 'Petal width (std)'),
]
fig, axes = plt.subplots(2, 3, figsize=(15, 9))
margin = 0.8
res_g = 60 # grid resolution (lower = faster for 4-D)
for col_idx, (ci, cj, xlabel, ylabel) in enumerate(slice_pairs):
xi_range = np.linspace(iris_Xn[:, ci].min() - margin,
iris_Xn[:, ci].max() + margin, res_g)
xj_range = np.linspace(iris_Xn[:, cj].min() - margin,
iris_Xn[:, cj].max() + margin, res_g)
ggi, ggj = np.meshgrid(xi_range, xj_range)
Xg_slice = np.zeros((res_g * res_g, 4))
Xg_slice[:, ci] = ggi.ravel()
Xg_slice[:, cj] = ggj.ravel()
mu_g, var_g, _, pi_avg_g = laplace_predict(
iris_Xn, iris_y, Xg_slice,
f_iris, W_iris, L_iris, K_iris,
rbf_kernel, link='logistic',
lengthscale=ell_iris_star, variance=sf2_iris_star)
# (top row) averaged class probability
ax = axes[0, col_idx]
c = ax.contourf(ggi, ggj, pi_avg_g.reshape(res_g, res_g),
levels=np.linspace(0, 1, 21), cmap='RdYlBu')
ax.contour(ggi, ggj, pi_avg_g.reshape(res_g, res_g),
levels=[0.5], colors='k', linewidths=2.5)
ax.scatter(iris_Xn[mp, ci], iris_Xn[mp, cj], s=35, c='steelblue',
edgecolors='k', lw=0.3, marker='o')
ax.scatter(iris_Xn[mn, ci], iris_Xn[mn, cj], s=35, c='tomato',
edgecolors='k', lw=0.3, marker='s')
fig.colorbar(c, ax=ax, label='$\\bar{\\pi}_*$')
ax.set_title(f'Prob — {xlabel.split(" (")[0]} vs {ylabel.split(" (")[0]}')
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
# (bottom row) predictive uncertainty
ax = axes[1, col_idx]
c = ax.contourf(ggi, ggj, var_g.reshape(res_g, res_g),
levels=20, cmap='magma_r')
ax.contour(ggi, ggj, pi_avg_g.reshape(res_g, res_g),
levels=[0.5], colors='white', linewidths=2, linestyles='--')
ax.scatter(iris_Xn[mp, ci], iris_Xn[mp, cj], s=35, c='steelblue',
edgecolors='white', lw=0.3, marker='o')
ax.scatter(iris_Xn[mn, ci], iris_Xn[mn, cj], s=35, c='tomato',
edgecolors='white', lw=0.3, marker='s')
fig.colorbar(c, ax=ax, label='$\\mathrm{Var}_q[f_*]$')
ax.set_title(f'Uncertainty — {xlabel.split(" (")[0]} vs {ylabel.split(" (")[0]}')
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
plt.suptitle(
f'Laplace GPC on Iris — 4 features (evidence-tuned: $\\ell={ell_iris_star:.2f}$, '
f'$\\sigma_f^2={sf2_iris_star:.1f}$, log ML={lml_iris:.1f}, train acc={acc:.0f}%)',
fontsize=13, y=1.01)
plt.tight_layout()
plt.show()
Best hyperparameters: ell = 2.300, sigma_f^2 = 15.00 Newton iterations: 7, log ML = -21.10 Training accuracy (4 features, evidence-tuned): 97.0%
11. Summary¶
GP Classification extends GP regression by replacing the Gaussian likelihood with a Bernoulli likelihood + response function $\sigma(\cdot)$ (logistic or probit).
The posterior $p(\mathbf{f}\mid X,\mathbf{y})$ is non-Gaussian → intractable integrals.
Laplace Approximation:
- Find the mode $\hat{\mathbf{f}}$ via Newton's method
- Approximate: $p(\mathbf{f}\mid X,\mathbf{y}) \approx q(\mathbf{f}) = \mathcal{N}\!\left(\hat{\mathbf{f}},\,(K^{-1}+W)^{-1}\right)$
Prediction via the law of total expectation/variance:
- Mean: $\mathbb{E}_q[f_*] = \mathbf{k}(\mathbf{x}_*)^\top K^{-1}\hat{\mathbf{f}}$
- Variance: $\mathrm{Var}_q[f_*] = k(\mathbf{x}_*,\mathbf{x}_*) - \mathbf{k}(\mathbf{x}_*)^\top(K+W^{-1})^{-1}\mathbf{k}(\mathbf{x}_*)$
- Class probability: averaged $\bar{\pi}_*=\int\sigma(f_*)\,q(f_*)\,df_*$ or MAP $\hat{\pi}_*=\sigma(\mathbb{E}_q[f_*])$
Marginal likelihood approximation enables kernel hyperparameter optimization: $$\log q(\mathbf{y}\mid X) = -\tfrac{1}{2}\hat{\mathbf{f}}^\top K^{-1}\hat{\mathbf{f}} + \log p(\mathbf{y}\mid\hat{\mathbf{f}}) - \tfrac{1}{2}\log\lvert B\rvert$$
Stable implementation via Cholesky of $B = I + W^{1/2}KW^{1/2}$:
- Newton updates, predictive variance, and log-determinant all reuse the same $L$
- Cost: $\mathcal{O}(n^3)$ for Cholesky, $\mathcal{O}(n^2)$ for each prediction
Key Differences: GP Regression vs GP Classification¶
- Likelihood — Regression: $\mathcal{N}(y\mid f,\sigma_n^2)$ · Classification: $\text{Bernoulli}(\sigma(yf))$
- Posterior — Regression: Exact Gaussian · Classification: Approximate (Laplace)
- Prediction — Regression: Closed-form · Classification: Requires integration (averaged) or plug-in (MAP)
- Hyperparameters — Regression: Exact log evidence · Classification: Approximate log evidence
- Noise parameter — Regression: $\sigma_n^2$ (explicit) · Classification: None (implicit in the Bernoulli)