Model Selection for Gaussian Processes¶
Course: MCE5919 — Gaussian Process for Machine Learning and Signal Processing
Topic: Model Selection (Lecture 7)
Instructor: Wenqiang PU
Date: April 2026
Learning Objectives¶
- Understand why model selection matters: underfitting vs overfitting
- Use log marginal likelihood to balance data fit and model complexity
- Compare hold-out validation, LOO-CV, and marginal likelihood
- See how the gradient of the log marginal likelihood is used in training
- Understand ARD as a probabilistic feature-selection mechanism
- See a simple GP classification example with evidence-based hyperparameter tuning
Environment / Packages¶
Required: numpy, matplotlib, scipy.
This notebook follows the style of the other course notebooks: short theory blocks, then small runnable examples.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import expit as logistic
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(7)
Notation Cheat Sheet¶
- $X=[\mathbf{x}_1,\ldots,\mathbf{x}_n]^\top$: training inputs
- $\mathbf{y}=[y_1,\ldots,y_n]^\top$: observations
- $k(\mathbf{x},\mathbf{x}';\boldsymbol{\theta})$: kernel with hyperparameters $\boldsymbol{\theta}$
- $K_f = k(X,X)$: Gram matrix
- $K_y = K_f + \sigma_n^2 I$: noisy covariance matrix
- $\mathcal{L}(\boldsymbol{\theta}) = \log p(\mathbf{y}\mid X,\boldsymbol{\theta})$: log marginal likelihood
- $\boldsymbol{\alpha}=K_y^{-1}\mathbf{y}$: dual coefficients
- In this notebook, most examples focus on tuning the kernel length-scale $\ell$ and signal variance $\sigma_f^2$
def _to_2d(X):
X = np.asarray(X, dtype=float)
if X.ndim == 1:
X = X[:, None]
return X
def rbf_kernel(X1, X2, lengthscale=1.0, variance=1.0):
X1 = _to_2d(X1)
X2 = _to_2d(X2)
sqdist = np.sum((X1[:, None, :] - X2[None, :, :]) ** 2, axis=2)
return variance * np.exp(-0.5 * sqdist / (lengthscale ** 2))
def ard_rbf_kernel(X1, X2, lengthscales, variance=1.0):
X1 = _to_2d(X1)
X2 = _to_2d(X2)
lengthscales = np.asarray(lengthscales, dtype=float)
Z1 = X1 / lengthscales
Z2 = X2 / lengthscales
sqdist = np.sum((Z1[:, None, :] - Z2[None, :, :]) ** 2, axis=2)
return variance * np.exp(-0.5 * sqdist)
def gp_posterior(X_train, y_train, X_test, lengthscale=0.5, variance=1.0, noise=0.1, kernel_fn=rbf_kernel, **kernel_kwargs):
X_train = _to_2d(X_train)
X_test = _to_2d(X_test)
y_train = np.asarray(y_train, dtype=float)
K = kernel_fn(X_train, X_train, lengthscale=lengthscale, variance=variance, **kernel_kwargs)
K += (noise ** 2 + 1e-9) * np.eye(len(X_train))
Ks = kernel_fn(X_train, X_test, lengthscale=lengthscale, variance=variance, **kernel_kwargs)
Kss = kernel_fn(X_test, X_test, lengthscale=lengthscale, variance=variance, **kernel_kwargs)
L = np.linalg.cholesky(K)
alpha = np.linalg.solve(L.T, np.linalg.solve(L, y_train))
mu = Ks.T @ alpha
v = np.linalg.solve(L, Ks)
var = np.maximum(np.diag(Kss) - np.sum(v ** 2, axis=0), 1e-12)
return mu, var, K, L, alpha
def gp_log_marginal_likelihood(X, y, lengthscale=0.5, variance=1.0, noise=0.1, kernel_fn=rbf_kernel, **kernel_kwargs):
X = _to_2d(X)
y = np.asarray(y, dtype=float)
K = kernel_fn(X, X, lengthscale=lengthscale, variance=variance, **kernel_kwargs)
Ky = K + (noise ** 2 + 1e-9) * np.eye(len(X))
L = np.linalg.cholesky(Ky)
alpha = np.linalg.solve(L.T, np.linalg.solve(L, y))
fit = -0.5 * y @ alpha
complexity = -np.sum(np.log(np.diag(L)))
constant = -0.5 * len(X) * np.log(2 * np.pi)
return fit + complexity + constant, fit, complexity, constant, Ky, L, alpha
def gp_predictive_mse(X_train, y_train, X_val, y_val, ell, variance=1.0, noise=0.1):
mu, _, _, _, _ = gp_posterior(X_train, y_train, X_val, lengthscale=ell, variance=variance, noise=noise)
return np.mean((y_val - mu) ** 2)
def gp_loo_log_predictive(X, y, ell, variance=1.0, noise=0.1):
_, _, _, _, Ky, _, _ = gp_log_marginal_likelihood(X, y, lengthscale=ell, variance=variance, noise=noise)
Ky_inv = np.linalg.inv(Ky)
alpha = Ky_inv @ y
sigma2 = 1.0 / np.diag(Ky_inv)
mu = y - alpha / np.diag(Ky_inv)
logp = -0.5 * (np.log(2 * np.pi * sigma2) + (y - mu) ** 2 / sigma2)
return np.sum(logp)
def make_regression_data(n=14, noise=0.12, rng=None):
if rng is None:
rng = np.random.default_rng(0)
X = np.linspace(0.0, 1.0, n)
f_true = np.sin(2 * np.pi * X) + 0.25 * np.cos(4 * np.pi * X)
y = f_true + noise * rng.normal(size=n)
return X[:, None], y, f_true
def make_2d_ard_data(n=40, noise=0.10, rng=None):
if rng is None:
rng = np.random.default_rng(0)
X = rng.uniform(-1.0, 1.0, size=(n, 2))
y = np.sin(3 * X[:, 0]) + noise * rng.normal(size=n)
return X, y
def make_toy_binary_data(n_per_class=22, rng=None):
if rng is None:
rng = np.random.default_rng(0)
X_pos = rng.normal(loc=[1.1, 0.9], scale=[0.55, 0.45], size=(n_per_class, 2))
X_neg = rng.normal(loc=[-1.0, -0.8], scale=[0.60, 0.55], size=(n_per_class, 2))
X = np.vstack([X_pos, X_neg])
y = np.hstack([np.ones(n_per_class), -np.ones(n_per_class)])
return X, y
def laplace_mode_finding(K, y, max_iter=40, tol=1e-6):
y01 = ((np.asarray(y) + 1) / 2).astype(float)
n = len(y01)
f = np.zeros(n)
for _ in range(max_iter):
pi = logistic(f)
W = np.clip(pi * (1 - pi), 1e-9, None)
W_sqrt = np.sqrt(W)
B = np.eye(n) + (W_sqrt[:, None] * K) * W_sqrt[None, :]
L = np.linalg.cholesky(B + 1e-9 * np.eye(n))
b = W * f + (y01 - pi)
Kb = K @ b
c = np.linalg.solve(L, W_sqrt * Kb)
a = b - W_sqrt * np.linalg.solve(L.T, c)
f_new = K @ a
if np.max(np.abs(f_new - f)) < tol:
f = f_new
break
f = f_new
pi = logistic(f)
W = np.clip(pi * (1 - pi), 1e-9, None)
W_sqrt = np.sqrt(W)
B = np.eye(n) + (W_sqrt[:, None] * K) * W_sqrt[None, :]
L = np.linalg.cholesky(B + 1e-9 * np.eye(n))
log_lik = np.sum(y01 * np.log(pi + 1e-12) + (1 - y01) * np.log(1 - pi + 1e-12))
lml = -0.5 * f @ np.linalg.solve(K + 1e-9 * np.eye(n), f) + log_lik - np.sum(np.log(np.diag(L)))
return f, W, L, lml
def laplace_predict_proba(X_train, X_test, f_hat, W, L, lengthscale, variance):
X_train = _to_2d(X_train)
X_test = _to_2d(X_test)
K = rbf_kernel(X_train, X_train, lengthscale=lengthscale, variance=variance) + 1e-9 * np.eye(len(X_train))
Ks = rbf_kernel(X_train, X_test, lengthscale=lengthscale, variance=variance)
alpha = np.linalg.solve(K, f_hat)
mu = Ks.T @ alpha
V = np.linalg.solve(L, np.sqrt(W)[:, None] * Ks)
var = np.maximum(variance - np.sum(V ** 2, axis=0), 1e-9)
kappa = 1.0 / np.sqrt(1.0 + np.pi * var / 8.0)
return logistic(mu * kappa), mu, var
1. What is Model Selection?¶
In GP models, model selection means choosing:
- a kernel structure (RBF, periodic, linear, sums/products, ...), and
- the hyperparameters inside the kernel (for example $\ell$, $\sigma_f^2$, $\sigma_n^2$).
A bad choice leads to either:
- underfitting: the model is too rigid,
- overfitting: the model is too flexible.
We start with a 1D regression example because it is easy to visualize.
# ── Simple 1D regression data ──
X_train, y_train, f_true_train = make_regression_data(n=14, noise=0.12, rng=rng)
X_plot = np.linspace(-0.05, 1.05, 400)[:, None]
f_true_plot = np.sin(2 * np.pi * X_plot[:, 0]) + 0.25 * np.cos(4 * np.pi * X_plot[:, 0])
plt.figure(figsize=(8, 4.5))
plt.plot(X_plot[:, 0], f_true_plot, color='black', lw=2, label='latent truth')
plt.scatter(X_train[:, 0], y_train, s=50, c='tomato', edgecolors='k', lw=0.4, label='observations')
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.title('Toy 1D regression data for model selection')
plt.legend()
plt.tight_layout()
plt.show()
Example 1: Underfitting vs Overfitting Through the Length-Scale¶
For the RBF kernel, $$ k(x,x') = \sigma_f^2\exp\!\left(-\frac{(x-x')^2}{2\ell^2}\right), $$ the length-scale $\ell$ controls how rapidly the function can vary.
- Small $\ell$: very flexible, may overfit noise
- Large $\ell$: very smooth, may underfit
- Intermediate $\ell$: often gives the best generalization
# ── Posterior fits for three different length-scales ──
ell_list = [0.08, 0.25, 1.20]
labels = ['small $\\ell$ (overfit)', 'medium $\\ell$', 'large $\\ell$ (underfit)']
fig, axes = plt.subplots(1, 3, figsize=(15, 4.2), sharey=True)
for ax, ell, label in zip(axes, ell_list, labels):
mu, var, _, _, _ = gp_posterior(X_train, y_train, X_plot, lengthscale=ell, variance=1.0, noise=0.12)
std = np.sqrt(var)
ax.plot(X_plot[:, 0], f_true_plot, color='black', lw=1.8, label='truth')
ax.plot(X_plot[:, 0], mu, color='royalblue', lw=2.2, label='posterior mean')
ax.fill_between(X_plot[:, 0], mu - 2 * std, mu + 2 * std, color='royalblue', alpha=0.18)
ax.scatter(X_train[:, 0], y_train, s=40, c='tomato', edgecolors='k', lw=0.3)
ax.set_title(label)
ax.set_xlabel('$x$')
axes[0].set_ylabel('$y$')
axes[0].legend(fontsize=9)
plt.suptitle('The same data, different hyperparameters', fontsize=13)
plt.tight_layout()
plt.show()
2. Cross-Validation for Model Selection¶
Marginal likelihood is not the only strategy. A more direct predictive criterion is cross-validation.
Here we compare three curves as functions of $\ell$:
- hold-out MSE on a validation set,
- LOO log predictive probability,
- log marginal likelihood.
They measure different things, so their optima need not be identical.
# ── Hold-out CV, LOO-CV, and evidence on the same dataset ──
ell_grid = np.linspace(0.05, 1.5, 120)
train_idx = np.arange(len(X_train)) % 2 == 0
X_tr, y_tr = X_train[train_idx], y_train[train_idx]
X_val, y_val = X_train[~train_idx], y_train[~train_idx]
mse_holdout = []
loo_logp = []
lml_full = []
for ell in ell_grid:
mse_holdout.append(gp_predictive_mse(X_tr, y_tr, X_val, y_val, ell, variance=1.0, noise=0.12))
loo_logp.append(gp_loo_log_predictive(X_train, y_train, ell, variance=1.0, noise=0.12))
lml_full.append(gp_log_marginal_likelihood(X_train, y_train, ell, variance=1.0, noise=0.12)[0])
mse_holdout = np.array(mse_holdout)
loo_logp = np.array(loo_logp)
lml_full = np.array(lml_full)
ell_holdout = ell_grid[np.argmin(mse_holdout)]
ell_loo = ell_grid[np.argmax(loo_logp)]
ell_evidence = ell_grid[np.argmax(lml_full)]
fig, axes = plt.subplots(1, 3, figsize=(15, 4.2))
axes[0].plot(ell_grid, mse_holdout, lw=2, color='darkorange')
axes[0].axvline(ell_holdout, color='red', ls='--', label=f'best={ell_holdout:.2f}')
axes[0].set_title('Hold-out validation')
axes[0].set_xlabel('length-scale $\\ell$')
axes[0].set_ylabel('validation MSE')
axes[0].legend(fontsize=9)
axes[1].plot(ell_grid, loo_logp, lw=2, color='teal')
axes[1].axvline(ell_loo, color='red', ls='--', label=f'best={ell_loo:.2f}')
axes[1].set_title('LOO-CV log predictive probability')
axes[1].set_xlabel('length-scale $\\ell$')
axes[1].set_ylabel('LOO log predictive prob.')
axes[1].legend(fontsize=9)
axes[2].plot(ell_grid, lml_full, lw=2, color='purple')
axes[2].axvline(ell_evidence, color='red', ls='--', label=f'best={ell_evidence:.2f}')
axes[2].set_title('Log marginal likelihood')
axes[2].set_xlabel('length-scale $\\ell$')
axes[2].set_ylabel('log evidence')
axes[2].legend(fontsize=9)
plt.tight_layout()
plt.show()
print(f'Best ell by hold-out MSE : {ell_holdout:.3f}')
print(f'Best ell by LOO-CV : {ell_loo:.3f}')
print(f'Best ell by evidence : {ell_evidence:.3f}')
Best ell by hold-out MSE : 0.172 Best ell by LOO-CV : 0.196 Best ell by evidence : 0.196
3. Log Marginal Likelihood: Data Fit vs Complexity¶
For GP regression, $$ \mathcal{L}(\boldsymbol{\theta}) = \log p(\mathbf{y}\mid X,\boldsymbol{\theta}) = -\tfrac{1}{2}\mathbf{y}^\top K_y^{-1}\mathbf{y} -\tfrac{1}{2}\log |K_y| -\tfrac{n}{2}\log(2\pi). $$
This decomposition has a clear interpretation:
- data fit: explains the observations well
- complexity penalty: discourages overly flexible models
- constant term: independent of the hyperparameters
A useful intuition is that the evidence automatically implements Occam's razor.
# ── Evidence landscape as a function of length-scale ──
lml_list, fit_list, comp_list = [], [], []
for ell in ell_grid:
lml, fit, comp, const, _, _, _ = gp_log_marginal_likelihood(
X_train, y_train, lengthscale=ell, variance=1.0, noise=0.12)
lml_list.append(lml)
fit_list.append(fit)
comp_list.append(comp)
lml_list = np.array(lml_list)
fit_list = np.array(fit_list)
comp_list = np.array(comp_list)
ell_star = ell_grid[np.argmax(lml_list)]
fig, axes = plt.subplots(1, 2, figsize=(13, 4.5))
ax = axes[0]
ax.plot(ell_grid, fit_list, lw=2, label='data fit term')
ax.plot(ell_grid, comp_list, lw=2, label='complexity penalty term')
ax.set_xlabel('length-scale $\\ell$')
ax.set_ylabel('value')
ax.set_title('Two competing terms in the evidence')
ax.legend(fontsize=9)
ax = axes[1]
ax.plot(ell_grid, lml_list, color='purple', lw=2.5)
ax.axvline(ell_star, color='red', ls='--', lw=1.8, label=f'best $\\ell$={ell_star:.2f}')
ax.set_xlabel('length-scale $\\ell$')
ax.set_ylabel('log marginal likelihood')
ax.set_title('Evidence chooses a compromise')
ax.legend(fontsize=9)
plt.tight_layout()
plt.show()
print(f'Best length-scale from evidence: ell = {ell_star:.3f}')
Best length-scale from evidence: ell = 0.196
4. Gradient of the Log Marginal Likelihood¶
To train hyperparameters efficiently, we often optimize $\mathcal{L}(\boldsymbol{\theta})$ by gradients rather than by brute-force grid search.
For a kernel hyperparameter $\theta_j$, $$ \frac{\partial \mathcal{L}}{\partial \theta_j} = \frac{1}{2}\operatorname{tr}\left((\boldsymbol{\alpha}\boldsymbol{\alpha}^\top - K_y^{-1})\frac{\partial K_y}{\partial \theta_j}\right). $$
Below we check this formula numerically for the RBF length-scale $\ell$.
# ── Check the gradient formula numerically for the RBF length-scale ──
ell0 = 0.35
variance0 = 1.0
noise0 = 0.12
lml0, _, _, _, Ky, _, alpha = gp_log_marginal_likelihood(
X_train, y_train, lengthscale=ell0, variance=variance0, noise=noise0)
sqdist = np.sum((X_train[:, None, :] - X_train[None, :, :]) ** 2, axis=2)
Kf = rbf_kernel(X_train, X_train, lengthscale=ell0, variance=variance0)
dK_dell = Kf * sqdist / (ell0 ** 3)
Ky_inv = np.linalg.inv(Ky)
grad_trace = 0.5 * np.trace((np.outer(alpha, alpha) - Ky_inv) @ dK_dell)
eps = 1e-4
lml_plus = gp_log_marginal_likelihood(X_train, y_train, lengthscale=ell0 + eps, variance=variance0, noise=noise0)[0]
lml_minus = gp_log_marginal_likelihood(X_train, y_train, lengthscale=ell0 - eps, variance=variance0, noise=noise0)[0]
grad_fd = (lml_plus - lml_minus) / (2 * eps)
print(f'Analytic gradient : {grad_trace:.6f}')
print(f'Finite-diff gradient: {grad_fd:.6f}')
print(f'Absolute difference : {abs(grad_trace - grad_fd):.3e}')
Analytic gradient : -93.245366 Finite-diff gradient: -93.245368 Absolute difference : 2.590e-06
6. Automatic Relevance Determination (ARD)¶
The isotropic RBF kernel uses one shared length-scale $\ell$ for all input dimensions. ARD replaces it by one length-scale per feature: $$ k_{\text{ARD}}(\mathbf{x},\mathbf{x}') = \sigma_f^2\exp\!\left(-\frac{1}{2}\sum_{d=1}^{D}\frac{(x_d-x_d')^2}{\ell_d^2}\right). $$
Interpretation:
- small $\ell_d$: the function changes quickly along dimension $d$ → feature $d$ is relevant
- large $\ell_d$: the function hardly changes along dimension $d$ → feature $d$ is less relevant
The next toy example is designed so that only the first input dimension matters.
# ── ARD example: only x1 matters, x2 is mostly irrelevant ──
X_ard, y_ard = make_2d_ard_data(n=100, noise=0.10, rng=rng)
ell1_grid = np.linspace(0.15, 1.5, 28)
ell2_grid = np.linspace(0.15, 10.0, 28)
score_ard = np.full((len(ell2_grid), len(ell1_grid)), -np.inf)
for i, ell2 in enumerate(ell2_grid):
for j, ell1 in enumerate(ell1_grid):
try:
lml, _, _, _, _, _, _ = gp_log_marginal_likelihood(
X_ard, y_ard, variance=1.0, noise=0.10,
kernel_fn=lambda A, B, lengthscale=None, variance=1.0: ard_rbf_kernel(A, B, [ell1, ell2], variance=variance))
score_ard[i, j] = lml
except np.linalg.LinAlgError:
pass
i_best, j_best = np.unravel_index(np.argmax(score_ard), score_ard.shape)
ell1_star = ell1_grid[j_best]
ell2_star = ell2_grid[i_best]
fig, axes = plt.subplots(1, 2, figsize=(13, 4.6))
axes[0].scatter(X_ard[:, 0], X_ard[:, 1], c=y_ard, cmap='coolwarm', s=45, edgecolors='k', lw=0.3)
axes[0].set_xlabel('$x_1$')
axes[0].set_ylabel('$x_2$')
axes[0].set_title('Toy 2D data for ARD')
im = axes[1].imshow(score_ard, origin='lower', aspect='auto', cmap='viridis',
extent=[ell1_grid[0], ell1_grid[-1], ell2_grid[0], ell2_grid[-1]])
axes[1].scatter([ell1_star], [ell2_star], c='red', s=70, edgecolors='white', lw=1.0)
axes[1].set_xlabel('length-scale $\\ell_1$')
axes[1].set_ylabel('length-scale $\\ell_2$')
axes[1].set_title('Evidence surface for ARD kernel')
fig.colorbar(im, ax=axes[1], label='log marginal likelihood')
plt.tight_layout()
plt.show()
print(f'Best ARD length-scales: ell1 = {ell1_star:.3f}, ell2 = {ell2_star:.3f}')
print('Interpretation: a much larger ell2 means the second feature is less relevant.')
Best ARD length-scales: ell1 = 0.650, ell2 = 10.000 Interpretation: a much larger ell2 means the second feature is less relevant.
7. Model Selection for GP Classification¶
For GP classification, the posterior is no longer Gaussian, so the marginal likelihood is not available in exact closed form.
With the Laplace approximation, we replace the true posterior by a Gaussian around the mode and optimize the approximate log marginal likelihood.
The idea is the same as in regression:
- try candidate hyperparameters,
- compute the approximate evidence,
- pick the hyperparameters with the highest score.
To make the evidence landscape more informative, the example below uses a slightly overlapping toy dataset with a few flipped labels. This avoids an almost perfectly separable problem, where the approximate evidence can keep increasing toward the boundary of the search grid.
# ── GP classification: evidence tuning on a strongly nonlinear 2D toy dataset ──
# We use a compact positive class inside a noisy outer ring of negative samples.
# This encourages a noticeably curved, closed decision boundary while still keeping a few flipped labels.
n_pos = 24
n_neg = 24
X_pos = rng.normal(loc=[0.10, -0.05], scale=[0.42, 0.34], size=(n_pos, 2))
theta = np.linspace(0.0, 2.0 * np.pi, n_neg, endpoint=False)
theta += rng.normal(scale=0.16, size=n_neg)
radius = 1.75 + 0.22 * np.sin(2.0 * theta) + 0.16 * rng.normal(size=n_neg)
X_neg = np.column_stack([
radius * np.cos(theta),
0.82 * radius * np.sin(theta)
])
X_neg += rng.normal(scale=0.08, size=(n_neg, 2))
X_cls = np.vstack([X_pos, X_neg])
y_cls = np.hstack([np.ones(n_pos), -np.ones(n_neg)])
flip_idx = np.array([4, 11, 28, 39])
y_cls[flip_idx] *= -1
# Standardize inputs so the length-scale grid has a clearer interpretation.
X_cls = (X_cls - X_cls.mean(axis=0)) / X_cls.std(axis=0)
ell_grid_cls = np.linspace(0.20, 2.00, 25)
sf2_grid_cls = np.linspace(0.30, 10, 22)
lml_cls = np.full((len(sf2_grid_cls), len(ell_grid_cls)), -np.inf)
for i, sf2 in enumerate(sf2_grid_cls):
for j, ell in enumerate(ell_grid_cls):
try:
K = rbf_kernel(X_cls, X_cls, lengthscale=ell, variance=sf2) + 1e-9 * np.eye(len(X_cls))
_, _, _, score = laplace_mode_finding(K, y_cls)
lml_cls[i, j] = score
except np.linalg.LinAlgError:
pass
i_best_cls, j_best_cls = np.unravel_index(np.argmax(lml_cls), lml_cls.shape)
ell_cls_star = ell_grid_cls[j_best_cls]
sf2_cls_star = sf2_grid_cls[i_best_cls]
K_star = rbf_kernel(X_cls, X_cls, lengthscale=ell_cls_star, variance=sf2_cls_star) + 1e-9 * np.eye(len(X_cls))
f_hat_cls, W_cls, L_cls, lml_star_cls = laplace_mode_finding(K_star, y_cls)
x1 = np.linspace(X_cls[:, 0].min() - 0.8, X_cls[:, 0].max() + 0.8, 120)
x2 = np.linspace(X_cls[:, 1].min() - 0.8, X_cls[:, 1].max() + 0.8, 120)
xx1, xx2 = np.meshgrid(x1, x2)
Xg = np.column_stack([xx1.ravel(), xx2.ravel()])
pi_cls, mu_cls, var_cls = laplace_predict_proba(
X_cls, Xg, f_hat_cls, W_cls, L_cls,
lengthscale=ell_cls_star, variance=sf2_cls_star)
fig, axes = plt.subplots(1, 2, figsize=(13, 4.8))
im = axes[0].imshow(lml_cls, origin='lower', aspect='auto', cmap='viridis',
extent=[ell_grid_cls[0], ell_grid_cls[-1], sf2_grid_cls[0], sf2_grid_cls[-1]])
axes[0].scatter([ell_cls_star], [sf2_cls_star], c='red', s=75, edgecolors='white', lw=1.0)
axes[0].set_xlabel('length-scale $\\ell$')
axes[0].set_ylabel('signal variance $\\sigma_f^2$')
axes[0].set_title('Approx. evidence for GP classification')
fig.colorbar(im, ax=axes[0], label='approx. log marginal likelihood')
c = axes[1].contourf(xx1, xx2, pi_cls.reshape(xx1.shape), levels=np.linspace(0, 1, 21), cmap='RdYlBu')
axes[1].contour(xx1, xx2, pi_cls.reshape(xx1.shape), levels=[0.5], colors='k', linewidths=2)
axes[1].scatter(X_cls[y_cls == 1, 0], X_cls[y_cls == 1, 1], s=40, c='steelblue', edgecolors='k', lw=0.3, marker='o')
axes[1].scatter(X_cls[y_cls == -1, 0], X_cls[y_cls == -1, 1], s=40, c='tomato', edgecolors='k', lw=0.3, marker='s')
axes[1].set_xlabel('$x_1$')
axes[1].set_ylabel('$x_2$')
axes[1].set_title('Decision boundary with evidence-tuned hyperparameters')
fig.colorbar(c, ax=axes[1], label='$p(y=+1\\mid \\mathbf{x})$')
plt.tight_layout()
plt.show()
print(f'Best classification hyperparameters: ell = {ell_cls_star:.3f}, sigma_f^2 = {sf2_cls_star:.3f}')
print(f'Approximate log marginal likelihood at optimum: {lml_star_cls:.3f}')
print(f'Optimum on boundary? ell: {j_best_cls in (0, len(ell_grid_cls)-1)}, sf2: {i_best_cls in (0, len(sf2_grid_cls)-1)}')
Best classification hyperparameters: ell = 0.800, sigma_f^2 = 10.000 Approximate log marginal likelihood at optimum: -21.403 Optimum on boundary? ell: False, sf2: True
8. Kernel Structure Comparison¶
Besides tuning hyperparameters inside one kernel family, we may also compare different kernel structures.
A simple intuition:
- RBF kernel prefers smooth functions
- Linear kernel prefers approximately straight-line trends
- Periodic kernel prefers repeating patterns
Model selection is therefore not only about finding the best $\ell$, but also about choosing a kernel whose inductive bias matches the data.
# ── Compare kernel structures on three simple patterns ──
def linear_kernel(X1, X2, variance=1.0, offset=0.0):
X1 = _to_2d(X1)
X2 = _to_2d(X2)
return variance * ((X1 @ X2.T) + offset)
def periodic_kernel(X1, X2, lengthscale=0.25, variance=1.0, period=1.0):
X1 = _to_2d(X1)
X2 = _to_2d(X2)
dist = np.sqrt(np.sum((X1[:, None, :] - X2[None, :, :]) ** 2, axis=2))
return variance * np.exp(-2.0 * np.sin(np.pi * dist / period) ** 2 / (lengthscale ** 2))
x_demo = np.linspace(0, 4, 160)[:, None]
y_linear = 0.7 * x_demo[:, 0] - 1.0
y_smooth = np.sin(1.3 * x_demo[:, 0])
y_periodic = np.sin(2 * np.pi * x_demo[:, 0])
patterns = [
('linear-like data', y_linear),
('smooth nonlinear data', y_smooth),
('periodic data', y_periodic),
]
kernel_scores = {'RBF': [], 'Linear': [], 'Periodic': []}
for _, y_pat in patterns:
kernel_scores['RBF'].append(gp_log_marginal_likelihood(x_demo[::8], y_pat[::8], lengthscale=0.5, variance=1.0, noise=0.08)[0])
kernel_scores['Linear'].append(gp_log_marginal_likelihood(
x_demo[::8], y_pat[::8], variance=1.0, noise=0.08,
kernel_fn=lambda A, B, lengthscale=None, variance=1.0: linear_kernel(A, B, variance=variance, offset=1.0))[0])
kernel_scores['Periodic'].append(gp_log_marginal_likelihood(
x_demo[::8], y_pat[::8], variance=1.0, noise=0.08,
kernel_fn=lambda A, B, lengthscale=0.35, variance=1.0: periodic_kernel(A, B, lengthscale=0.35, variance=variance, period=1.0))[0])
fig, axes = plt.subplots(1, 2, figsize=(13, 4.5))
for idx, (title, y_pat) in enumerate(patterns):
axes[0].plot(x_demo[:, 0], y_pat + 3.0 * idx, lw=2, label=title)
axes[0].set_xlabel('$x$')
axes[0].set_ylabel('shifted output')
axes[0].set_title('Three data patterns')
axes[0].legend(fontsize=9)
bar_x = np.arange(len(patterns))
width = 0.24
axes[1].bar(bar_x - width, kernel_scores['RBF'], width=width, label='RBF')
axes[1].bar(bar_x, kernel_scores['Linear'], width=width, label='Linear')
axes[1].bar(bar_x + width, kernel_scores['Periodic'], width=width, label='Periodic')
axes[1].set_xticks(bar_x)
axes[1].set_xticklabels([name for name, _ in patterns], rotation=10)
axes[1].set_ylabel('log marginal likelihood')
axes[1].set_title('Which kernel family fits which pattern?')
axes[1].legend(fontsize=9)
plt.tight_layout()
plt.show()
9. Composite Kernels: Trend + Periodicity¶
One key message from the slides is that real datasets often contain multiple structures at once.
For example, atmospheric CO$_2$ data show:
- a long-term upward trend,
- seasonal periodicity,
- small irregular local deviations.
A natural GP strategy is to build a sum kernel: $$ k(x,x') = k_{\text{trend}}(x,x') + k_{\text{periodic}}(x,x'). $$
Below we use a very small synthetic example to show why a composite kernel can outperform a single-kernel model.
# ── Composite-kernel example: linear trend + periodic component ──
def composite_kernel(X1, X2, variance=1.0, lengthscale=0.35):
return (0.25 * linear_kernel(X1, X2, variance=1.0, offset=1.0)
+ periodic_kernel(X1, X2, lengthscale=lengthscale, variance=0.9, period=1.0))
X_mix = np.linspace(0, 4, 22)[:, None]
y_mix_true = 0.35 * X_mix[:, 0] + 0.9 * np.sin(2 * np.pi * X_mix[:, 0])
y_mix = y_mix_true + 0.12 * rng.normal(size=len(X_mix))
X_mix_plot = np.linspace(-0.2, 4.2, 400)[:, None]
y_mix_truth_plot = 0.35 * X_mix_plot[:, 0] + 0.9 * np.sin(2 * np.pi * X_mix_plot[:, 0])
mu_rbf, var_rbf, _, _, _ = gp_posterior(X_mix, y_mix, X_mix_plot, lengthscale=0.45, variance=1.0, noise=0.12)
mu_cmp, var_cmp, _, _, _ = gp_posterior(
X_mix, y_mix, X_mix_plot, variance=1.0, noise=0.12,
kernel_fn=lambda A, B, lengthscale=0.35, variance=1.0: composite_kernel(A, B, variance=variance, lengthscale=0.35))
lml_rbf = gp_log_marginal_likelihood(X_mix, y_mix, lengthscale=0.45, variance=1.0, noise=0.12)[0]
lml_cmp = gp_log_marginal_likelihood(
X_mix, y_mix, variance=1.0, noise=0.12,
kernel_fn=lambda A, B, lengthscale=0.35, variance=1.0: composite_kernel(A, B, variance=variance, lengthscale=0.35))[0]
fig, axes = plt.subplots(1, 2, figsize=(13, 4.8), sharey=True)
std_rbf = np.sqrt(var_rbf)
axes[0].plot(X_mix_plot[:, 0], y_mix_truth_plot, color='black', lw=1.8, label='truth')
axes[0].plot(X_mix_plot[:, 0], mu_rbf, color='royalblue', lw=2.2, label='RBF mean')
axes[0].fill_between(X_mix_plot[:, 0], mu_rbf - 2 * std_rbf, mu_rbf + 2 * std_rbf, color='royalblue', alpha=0.18)
axes[0].scatter(X_mix[:, 0], y_mix, c='tomato', s=38, edgecolors='k', lw=0.3)
axes[0].set_title(f'Single RBF kernel\nlog ML = {lml_rbf:.1f}')
axes[0].set_xlabel('$x$')
axes[0].set_ylabel('$y$')
axes[0].legend(fontsize=9)
std_cmp = np.sqrt(var_cmp)
axes[1].plot(X_mix_plot[:, 0], y_mix_truth_plot, color='black', lw=1.8, label='truth')
axes[1].plot(X_mix_plot[:, 0], mu_cmp, color='seagreen', lw=2.2, label='composite mean')
axes[1].fill_between(X_mix_plot[:, 0], mu_cmp - 2 * std_cmp, mu_cmp + 2 * std_cmp, color='seagreen', alpha=0.18)
axes[1].scatter(X_mix[:, 0], y_mix, c='tomato', s=38, edgecolors='k', lw=0.3)
axes[1].set_title(f'Linear + periodic kernel\nlog ML = {lml_cmp:.1f}')
axes[1].set_xlabel('$x$')
axes[1].legend(fontsize=9)
plt.tight_layout()
plt.show()
print(f'RBF log marginal likelihood : {lml_rbf:.3f}')
print(f'Composite-kernel log likelihood : {lml_cmp:.3f}')
RBF log marginal likelihood : -39.023 Composite-kernel log likelihood : -13.477