Gaussian Process Regression (Function-Space View)¶
Course: MCE5919 — Gaussian Process for Machine Learning and Signal Processing
Topic: GP Regression (Lecture 4)
Instructor: Wenqiang PU
Date: Feb. 2026
Learning Objectives¶
- Understand a Gaussian process (GP) as a distribution over functions
- Read a kernel $k(x,x')$ as a modeling assumption (smoothness, periodicity, etc.)
- Derive GP regression posterior by conditioning a joint Gaussian
- Interpret predictive mean (best guess) and variance (uncertainty)
Environment / Packages¶
Required: numpy, matplotlib.
This notebook intentionally avoids heavy dependencies so students can run it anywhere.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
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(0)
Notation Cheat Sheet¶
We use the same notation as the slides.
- $X=[x_1,\ldots,x_n]$: training inputs (here we focus on 1D for intuition)
- $\mathbf{y}=[y_1,\ldots,y_n]$: noisy observations
- $f(\cdot)$: latent (noise-free) function
- $k(x,x')$: kernel / covariance function
- $K(X,X)$: Gram matrix with $K_{ij}=k(x_i,x_j)$
- $\sigma_n^2$: observation noise variance
- $X_*$: test inputs; $\mathbf{f}_*$ / $\mathbf{y}_*$: predicted latent/noisy outputs
1. Definition of Gaussian Process¶
A Gaussian process is a collection of random variables, any finite number of which have a joint Gaussian distribution.
We write: $$f(x)\sim {GP}(m(x),k(x,x')).$$ Meaning:
- Pick any finite set $x_1,\ldots,x_n$
- Then $\mathbf{f}=[f(x_1),\ldots,f(x_n)]$ is multivariate Gaussian: $$\mathbf{f}\in\mathcal{N}(\mathbf{m},K),\quad K_{ij}=k(x_i,x_j).$$
In demos we often use $m(x)=0$ to keep the focus on kernels.
Kernels¶
Choosing a kernel is choosing what kinds of functions are likely.
Typical kernels we will use:
- RBF / Squared Exponential (SE): very smooth functions
- Linear: straight lines
- Periodic: repeating patterns
Rule of thumb: start with SE/RBF, then add structure (sum/product kernels) if residuals suggest it.
def _as_col(x: np.ndarray) -> np.ndarray:
x = np.asarray(x).reshape(-1, 1)
return x
def rbf_kernel(x1: np.ndarray, x2: np.ndarray, lengthscale: float = 0.3, variance: float = 1.0) -> np.ndarray:
"""Squared Exponential / RBF kernel for 1D inputs."""
x1 = _as_col(x1)
x2 = _as_col(x2)
sqdist = (x1 - x2.T) ** 2
return variance * np.exp(-0.5 * sqdist / (lengthscale**2))
def linear_kernel(x1: np.ndarray, x2: np.ndarray, bias: float = 0.0, variance: float = 1.0) -> np.ndarray:
"""Linear kernel: k(x,x') = variance * (x x' + bias)."""
x1 = _as_col(x1)
x2 = _as_col(x2)
return variance * (x1 @ x2.T + bias)
def polynomial_kernel(
x1: np.ndarray,
x2: np.ndarray,
degree: int = 2,
bias: float = 1.0,
variance: float = 1.0,
) -> np.ndarray:
"""Polynomial kernel: k(x,x') = variance * (x x' + bias)^degree (1D)."""
x1 = _as_col(x1)
x2 = _as_col(x2)
return variance * (x1 @ x2.T + bias) ** degree
def periodic_kernel(x1: np.ndarray, x2: np.ndarray, period: float = 1.0, lengthscale: float = 0.3, variance: float = 1.0) -> np.ndarray:
"""Standard periodic kernel (1D).
k(x,x') = variance * exp( -2 sin^2(pi|x-x'|/period) / lengthscale^2 )
"""
x1 = _as_col(x1)
x2 = _as_col(x2)
dist = np.abs(x1 - x2.T)
sin_term = np.sin(np.pi * dist / period)
return variance * np.exp(-2.0 * (sin_term**2) / (lengthscale**2))
def kernel_sum(k1, k2):
return lambda x, y, **kw: k1(x, y, **kw) + k2(x, y, **kw)
def plot_gp_1d(x_train, y_train, x_test, mean, var, title: str, show_legend: bool = True):
std = np.sqrt(np.maximum(var, 0.0))
plt.figure(figsize=(7.6, 4.6))
if x_train is not None and y_train is not None:
plt.scatter(x_train, y_train, s=55, alpha=0.9, edgecolors='k', linewidths=0.4, label='train')
plt.plot(x_test, mean, color='crimson', lw=2.2, label='predictive mean')
plt.fill_between(x_test, mean - 2*std, mean + 2*std, color='crimson', alpha=0.18, label='±2 std')
plt.xlabel('x')
plt.ylabel('y')
plt.title(title)
if show_legend:
plt.legend()
plt.tight_layout()
plt.show()
def sample_gp_prior(x: np.ndarray, kernel_fn, n_samples: int = 3, jitter: float = 1e-8, **kernel_kwargs):
"""Sample functions f(x) from GP(0, k) at finite points x."""
x = np.asarray(x).reshape(-1)
K = kernel_fn(x, x, **kernel_kwargs) + jitter * np.eye(len(x))
L = np.linalg.cholesky(K)
z = rng.standard_normal(size=(len(x), n_samples))
f = L @ z
return f
Example 1: Draw samples from a GP prior¶
We draw random functions before seeing any data (a GP prior). In practice we sample $\mathbf{f}\sim\mathcal{N}(\mathbf{0},K)$ on a grid of $x$ values and plot the resulting curves.
What to look for:
- Lengthscale $\ell$ controls horizontal correlation: small $\ell$ → nearby points weakly correlated → wiggly samples; large $\ell$ → strong correlation → smooth samples.
- Signal variance $\sigma_f^2$ controls vertical scale: larger $\sigma_f^2$ → larger amplitude.
- The green band is the pointwise prior uncertainty: at each $x$, $\pm 2\sqrt{k(x,x)}$ (not a confidence interval over entire functions).
Key message: the kernel $k(x,x')$ is a modeling assumption about what functions are likely.
x = np.linspace(-2.0, 2.0, 250)
ells = [0.05, 0.6, 2.0]
variance = 6.0
plt.figure(figsize=(10.8, 3.2))
for i, ell in enumerate(ells, 1):
f_samp = sample_gp_prior(x, rbf_kernel, n_samples=4, lengthscale=ell, variance=variance)
Kxx = rbf_kernel(x, x, lengthscale=ell, variance=variance)
std = np.sqrt(np.maximum(np.diag(Kxx), 0.0))
ax = plt.subplot(1, 3, i)
# Prior mean is 0; uncertainty band is ±2 std(x)
ax.fill_between(x, -2 * std, 2 * std, color='green', alpha=0.18, label='±2 std (prior)')
ax.plot(x, np.zeros_like(x), color='black', lw=1.2, alpha=0.7, label='prior mean')
for j in range(f_samp.shape[1]):
ax.plot(x, f_samp[:, j], lw=1.6)
ax.set_title(rf'GP prior samples (RBF, $\ell={ell}$)')
ax.set_xlabel('x')
if i == 1:
ax.set_ylabel('f(x)')
ax.grid(True, ls='--', alpha=0.35)
plt.tight_layout()
plt.show()
Example 1 (more): other kernels¶
The same sampling procedure works for other kernels; only $K$ changes.
What to look for (1D intuition):
- Linear kernel prefers straight lines because it corresponds to a finite-dimensional linear model $f(x)=ax+b$ (function space is very limited).
- Polynomial kernel produces stronger global trends / curvature; higher degree usually means more global bending/variation.
Numerical note: the linear kernel Gram matrix is often low-rank or nearly singular on a grid, so we use a slightly larger jitter when sampling to make Cholesky stable.
x = np.linspace(-2.0, 2.0, 250)
plt.figure(figsize=(10.8, 3.2))
# Linear kernel (often low-rank) → use slightly larger jitter for stable sampling
bias = 2.0
variance = 1.0
K_lin = linear_kernel(x, x, bias=bias, variance=variance)
std_lin = np.sqrt(np.maximum(np.diag(K_lin), 0.0))
f_lin = sample_gp_prior(x, linear_kernel, n_samples=4, jitter=1e-6, bias=bias, variance=variance)
ax = plt.subplot(1, 2, 1)
ax.fill_between(x, -2 * std_lin, 2 * std_lin, color='green', alpha=0.18, label='±2 std (prior)')
ax.plot(x, np.zeros_like(x), color='black', lw=1.2, alpha=0.7, label='prior mean')
for j in range(f_lin.shape[1]):
ax.plot(x, f_lin[:, j], lw=1.6)
ax.set_title('GP prior samples (Linear kernel)')
ax.set_xlabel('x')
ax.set_ylabel('f(x)')
ax.grid(True, ls='--', alpha=0.35)
# Polynomial kernel: (x x' + bias)^degree
degree = 3
bias = 0.0
variance = 1.0
K_poly = polynomial_kernel(x, x, degree=degree, bias=bias, variance=variance)
std_poly = np.sqrt(np.maximum(np.diag(K_poly), 0.0))
f_poly = sample_gp_prior(x, polynomial_kernel, n_samples=4, jitter=1e-6, degree=degree, bias=bias, variance=variance)
ax = plt.subplot(1, 2, 2)
ax.fill_between(x, -2 * std_poly, 2 * std_poly, color='green', alpha=0.18, label='±2 std (prior)')
ax.plot(x, np.zeros_like(x), color='black', lw=1.2, alpha=0.7, label='prior mean')
for j in range(f_poly.shape[1]):
ax.plot(x, f_poly[:, j], lw=1.6)
ax.set_title(f'GP prior samples (Polynomial kernel, degree={degree})')
ax.set_xlabel('x')
ax.grid(True, ls='--', alpha=0.35)
plt.tight_layout()
plt.show()
2. GP Regression: Generative Model¶
We model a latent function and noisy observations: $$f(\cdot)\sim\mathcal{GP}(0, k(\cdot,\cdot)),\quad y_i = f(x_i) + \epsilon_i,\ \epsilon_i \sim \mathcal{N}(0,\sigma_n^2).$$ Stack values at training points $X=[x_1,\ldots,x_n]$:
- Latent vector $\mathbf{f}=[f(x_1),\ldots,f(x_n)]^\top \sim \mathcal{N}(\mathbf{0}, K)$
- Likelihood $\mathbf{y}\mid \mathbf{f} \sim \mathcal{N}(\mathbf{f},\sigma_n^2 I)$ So marginally (integrating out $\mathbf{f}$): $$\mathbf{y}\sim \mathcal{N}(\mathbf{0},\ K+\sigma_n^2 I).$$
Key Step: Conditioning a Joint Gaussian¶
A GP guarantees that any finite set of function values is jointly Gaussian. With Gaussian observation noise, the observed outputs are also jointly Gaussian. For training inputs $X$ and test inputs $X_*$, we build the joint Gaussian: $$\begin{bmatrix}\mathbf{y}\\ \mathbf{y}_*\end{bmatrix}\sim\mathcal{N}\!\left(\mathbf{0},\ \begin{bmatrix}K(X,X)+\sigma_n^2I & K(X,X_*) \\ K(X_*,X) & K(X_*,X_*)+\sigma_n^2I\end{bmatrix}\right).$$ Conditioning gives the posterior predictive mean/variance in closed form.
In implementation we do not invert matrices explicitly; we use Cholesky solves.
def gp_posterior_predict(
X_train: np.ndarray,
y_train: np.ndarray,
X_test: np.ndarray,
kernel_fn,
noise_std: float,
jitter: float = 1e-8,
return_cov: bool = False,
**kernel_kwargs,
):
"""Compute GP regression posterior for f_* and y_* at X_test.
Returns:
mean_f: predictive mean of latent f_*
var_f: predictive variance (diagonal) of latent f_*
var_y: predictive variance (diagonal) of noisy y_* (adds noise_std^2)
(optional) cov_f: full covariance of f_* if return_cov=True
"""
X_train = np.asarray(X_train).reshape(-1)
y_train = np.asarray(y_train).reshape(-1)
X_test = np.asarray(X_test).reshape(-1)
K = kernel_fn(X_train, X_train, **kernel_kwargs)
Ks = kernel_fn(X_train, X_test, **kernel_kwargs)
Kss = kernel_fn(X_test, X_test, **kernel_kwargs)
sigma2 = float(noise_std) ** 2
Ky = K + (sigma2 + jitter) * np.eye(len(X_train))
L = np.linalg.cholesky(Ky)
alpha = np.linalg.solve(L.T, np.linalg.solve(L, y_train))
mean_f = Ks.T @ alpha
v = np.linalg.solve(L, Ks)
cov_f = Kss - v.T @ v
var_f = np.clip(np.diag(cov_f), 0.0, None)
var_y = var_f + sigma2
if return_cov:
return mean_f, var_f, var_y, cov_f
return mean_f, var_f, var_y
def gp_log_marginal_likelihood(X_train: np.ndarray, y_train: np.ndarray, kernel_fn, noise_std: float, jitter: float = 1e-8, **kernel_kwargs) -> float:
"""Compute log p(y|X,theta) for GP regression with Gaussian noise."""
X_train = np.asarray(X_train).reshape(-1)
y_train = np.asarray(y_train).reshape(-1)
K = kernel_fn(X_train, X_train, **kernel_kwargs)
sigma2 = float(noise_std) ** 2
Ky = K + (sigma2 + jitter) * np.eye(len(X_train))
L = np.linalg.cholesky(Ky)
alpha = np.linalg.solve(L.T, np.linalg.solve(L, y_train))
data_fit = -0.5 * (y_train @ alpha)
log_det = np.sum(np.log(np.diag(L)))
complexity = -log_det
const = -0.5 * len(X_train) * np.log(2.0 * np.pi)
return float(data_fit + complexity + const)
GP Regression in Practice (4-step recipe)¶
Given training data $\mathcal{D}=\{X,\mathbf{y}\}$:
- Choose a kernel $k(\cdot,\cdot;\theta_h)$ and noise level $\sigma_n^2$.
- Build $K=K(X,X)$ and add noise: $K_y=K+\sigma_n^2 I$.
- Solve $\boldsymbol{\alpha}=K_y^{-1}\mathbf{y}$ via Cholesky, not by forming $K_y^{-1}$.
- For test inputs $X_*$:
- mean: $\bar{\mathbf{m}} = K(X_*,X)\,\boldsymbol{\alpha}$
- covariance: $\bar{V} = K(X_*,X_*) - K(X_*,X)\,K_y^{-1}\,K(X,X_*)$
- (noisy) predictive variance: add $\sigma_n^2$ on the diagonal if predicting $\mathbf{y}_*$ Complexity: Cholesky is $\mathcal{O}(n^3)$; after that, each solve is $\mathcal{O}(n^2)$.
Example 2: Basic GP regression (noisy sine)¶
We fit a smooth function from noisy samples and visualize uncertainty.
What happens in this example:
- We generate noisy observations $y_i=f(x_i)+\epsilon_i$ from a true sine curve.
- We choose an RBF kernel and compute the posterior predictive mean/variance by conditioning a joint Gaussian (implemented via Cholesky solves).
- We plot: training points, posterior mean, and a $\pm2$ standard deviation band.
Teaching points / how to read the plot:
- Near many training points: uncertainty shrinks (the band becomes narrow).
- Far away (extrapolation): uncertainty grows back toward the prior.
- The posterior mean is a linear combination of observations (kernelized linear predictor).
- Changing $\ell$ or $\sigma_n$ changes both the mean and uncertainty.
def f_true(x):
return np.sin(2.5 * x)
n = 12
X_train = np.linspace(-1.2, 1.2, n)
noise_std = 1.15
y_train = f_true(X_train) + noise_std * rng.standard_normal(n)
X_test = np.linspace(-2.0, 2.0, 400)
ell = 0.1
sigma_f2 = 3
mean_f, var_f, var_y = gp_posterior_predict(
X_train, y_train, X_test,
kernel_fn=rbf_kernel,
noise_std=noise_std,
lengthscale=ell,
variance=sigma_f2,
)
# plot_gp_1d(X_train, y_train, X_test, mean_f, var_y,
# title=rf'GP regression (RBF kernel) — $\ell={ell}$, $\sigma_n={noise_std}$')
plt.figure(figsize=(7.6, 4.6))
plt.plot(X_test, f_true(X_test), color='black', lw=2.0, alpha=0.8, label='true f(x)')
plt.scatter(X_train, y_train, s=55, alpha=0.9, edgecolors='k', linewidths=0.4, label='train')
plt.plot(X_test, mean_f, color='crimson', lw=2.2, label='posterior mean')
std_y = np.sqrt(np.maximum(var_y, 0.0))
plt.fill_between(X_test, mean_f - 2*std_y, mean_f + 2*std_y, color='crimson', alpha=0.18, label='±2 std (y)')
plt.title('Same plot + true function (for teaching)')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.tight_layout()
plt.xlim(-2.0, 2.0)
plt.ylim(-2.0, 2.0)
plt.show()
# --- Extra figure: posterior function realizations (samples) ---
# We sample latent f(x) ~ N(mean_f, cov_f) on the test grid.
# (This is different from sampling noisy y, which would add extra iid noise.)
mean_f_samp, var_f_samp, var_y_samp, cov_f_samp = gp_posterior_predict(
X_train, y_train, X_test,
kernel_fn=rbf_kernel,
noise_std=noise_std,
lengthscale=ell,
variance=sigma_f2,
return_cov=True,
)
cov_f_samp = 0.5 * (cov_f_samp + cov_f_samp.T) # numerical symmetrization
n_realizations = 6
z = rng.standard_normal(size=(len(X_test), n_realizations))
for jitter_try in (1e-10, 1e-8, 1e-6):
try:
L = np.linalg.cholesky(cov_f_samp + jitter_try * np.eye(len(X_test)))
break
except np.linalg.LinAlgError:
L = None
if L is None:
raise np.linalg.LinAlgError('Cholesky failed for posterior covariance even with jitter.')
f_samps = mean_f_samp.reshape(-1, 1) + L @ z
plt.figure(figsize=(7.6, 4.6))
plt.plot(X_test, f_true(X_test), color='black', lw=2.0, alpha=0.75, label='true f(x)')
plt.scatter(X_train, y_train, s=55, alpha=0.9, edgecolors='k', linewidths=0.4, label='train')
std_y = np.sqrt(np.maximum(var_y, 0.0))
plt.fill_between(X_test, mean_f - 2*std_y, mean_f + 2*std_y, color='crimson', alpha=0.18, label='±2 std (y)')
plt.plot(X_test, mean_f_samp, color='crimson', lw=2.2, label='posterior mean')
for j in range(n_realizations):
plt.plot(X_test, f_samps[:, j], lw=1.3, alpha=0.65, color='steelblue')
plt.title('Posterior GP function realizations (samples of f)')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.tight_layout()
plt.xlim(-2.0, 2.0)
plt.ylim(-2.0, 2.0)
plt.show()
Example 3: What does noise $\sigma_n$ do?¶
Keep the same kernel, vary the assumed observation noise.
Intuition:
- Larger $\sigma_n$ means the model believes observations are less reliable. The posterior mean becomes smoother and the uncertainty band widens.
- Smaller $\sigma_n$ makes the model try to pass closer to the data, with narrower uncertainty near points.
How it appears in the equations:
- Noise enters through $K_y = K + \sigma_n^2 I$. Increasing $\sigma_n^2$ increases the diagonal, reducing the influence of each data point in the linear solve.
noise_list = [0.03, 0.15, 0.45]
ell = 0.45
sigma_f2 = 1.0
plt.figure(figsize=(10.8, 3.4))
for i, ns in enumerate(noise_list, 1):
mean_f, var_f, var_y = gp_posterior_predict(
X_train, y_train, X_test,
kernel_fn=rbf_kernel,
noise_std=ns,
lengthscale=ell,
variance=sigma_f2,
)
std_y = np.sqrt(np.maximum(var_y, 0.0))
ax = plt.subplot(1, 3, i)
ax.scatter(X_train, y_train, s=38, alpha=0.9, edgecolors='k', linewidths=0.35)
ax.plot(X_test, mean_f, color='crimson', lw=2.0)
ax.fill_between(X_test, mean_f - 2*std_y, mean_f + 2*std_y, color='crimson', alpha=0.18)
ax.plot(X_test, f_true(X_test), color='black', lw=1.8, alpha=0.75)
ax.set_title(rf'$\sigma_n={ns}$')
ax.set_xlabel('x')
if i == 1:
ax.set_ylabel('y')
ax.grid(True, ls='--', alpha=0.35)
plt.suptitle('Effect of observation noise on GP regression', y=1.02, fontsize=12)
plt.tight_layout()
plt.show()
Example 4: What does lengthscale $\ell$ do?¶
Same data, same noise, different lengthscale.
Intuition:
- Small $\ell$ → correlation decays quickly with distance → the function can change rapidly (risk: overfitting).
- Large $\ell$ → long-range correlation → very smooth function (risk: underfitting).
- Uncertainty also changes: with very small $\ell$, the model becomes confident only very locally around training points; with large $\ell$, information propagates farther.
Rule of thumb: treat $\ell$ as a smoothness knob; choose it by evidence (marginal likelihood) or validation.
ell_list = [0.12, 0.45, 1.6]
noise_std_fixed = 0.15
sigma_f2 = 1.0
plt.figure(figsize=(10.8, 3.4))
for i, ell in enumerate(ell_list, 1):
mean_f, var_f, var_y = gp_posterior_predict(
X_train, y_train, X_test,
kernel_fn=rbf_kernel,
noise_std=noise_std_fixed,
lengthscale=ell,
variance=sigma_f2,
)
std_y = np.sqrt(np.maximum(var_y, 0.0))
ax = plt.subplot(1, 3, i)
ax.scatter(X_train, y_train, s=38, alpha=0.9, edgecolors='k', linewidths=0.35)
ax.plot(X_test, mean_f, color='crimson', lw=2.0)
ax.fill_between(X_test, mean_f - 2*std_y, mean_f + 2*std_y, color='crimson', alpha=0.18)
ax.plot(X_test, f_true(X_test), color='black', lw=1.8, alpha=0.75)
ax.set_title(rf'lengthscale $\ell={ell}$')
ax.set_xlabel('x')
if i == 1:
ax.set_ylabel('y')
ax.grid(True, ls='--', alpha=0.35)
plt.suptitle('Effect of RBF lengthscale on smoothness and uncertainty', y=1.02, fontsize=12)
plt.tight_layout()
plt.show()
Example 5: Kernel choice as a modeling assumption¶
We generate periodic-ish data and compare kernels:
- Linear kernel (cannot capture periodicity)
- RBF kernel (can fit locally but is not explicitly periodic)
- Periodic kernel (matches the structure)
How to read the three panels:
- If the kernel family cannot represent the structure (e.g., linear for periodic data), the posterior mean will systematically miss patterns.
- RBF often looks good within the observed range but may not extrapolate with repeating structure.
- A periodic kernel encodes the right inductive bias, so it can generalize periodicity more naturally.
Main lesson: kernel = assumption. Pick kernels using domain knowledge, then tune hyperparameters using evidence/CV.
def f_periodic(x):
return np.sin(2*np.pi * x) + 0.25*np.cos(4*np.pi*x)
n2 = 16
X_train2 = np.linspace(0.0, 1.0, n2)
noise_std2 = 0.12
y_train2 = f_periodic(X_train2) + noise_std2 * rng.standard_normal(n2)
X_test2 = np.linspace(-0.3, 1.3, 450)
configs = [
('Linear', linear_kernel, dict(bias=1.0, variance=1.0)),
('RBF', rbf_kernel, dict(lengthscale=0.18, variance=1.0)),
('Periodic', periodic_kernel, dict(period=1.0, lengthscale=0.22, variance=1.0)),
]
plt.figure(figsize=(10.8, 3.4))
for i, (name, kfn, kw) in enumerate(configs, 1):
mean_f, var_f, var_y = gp_posterior_predict(
X_train2, y_train2, X_test2,
kernel_fn=kfn,
noise_std=noise_std2,
**kw,
)
std_y = np.sqrt(np.maximum(var_y, 0.0))
ax = plt.subplot(1, 3, i)
ax.scatter(X_train2, y_train2, s=38, alpha=0.9, edgecolors='k', linewidths=0.35)
ax.plot(X_test2, f_periodic(X_test2), color='black', lw=1.8, alpha=0.75)
ax.plot(X_test2, mean_f, color='crimson', lw=2.0)
ax.fill_between(X_test2, mean_f - 2*std_y, mean_f + 2*std_y, color='crimson', alpha=0.18)
ax.set_title(name)
ax.set_xlabel('x')
if i == 1:
ax.set_ylabel('y')
ax.grid(True, ls='--', alpha=0.35)
plt.suptitle('Kernel choice changes the function family you assume', y=1.02, fontsize=12)
plt.tight_layout()
plt.show()
3. Marginal Likelihood (Evidence) for Hyperparameter Tuning¶
The marginal likelihood (a.k.a. evidence) integrates out latent function values $\mathbf{f}$: $$p(\mathbf{y}\mid X,\theta)=\int p(\mathbf{y}\mid \mathbf{f},X,\theta)\,p(\mathbf{f}\mid X,\theta)\,d\mathbf{f}.$$ For GP regression (zero-mean prior):
- $\mathbf{f}\mid X\sim\mathcal{N}(\mathbf{0},K)$, where $K\equiv K(X,X)$
- $\mathbf{y}\mid \mathbf{f},X\sim\mathcal{N}(\mathbf{f},\sigma_n^2 I)$ Define $K_y\triangleq K+\sigma_n^2 I$. Since $\mathbf{y}=\mathbf{f}+\varepsilon$ is a sum of independent Gaussians, $$\mathbf{y}\mid X,\theta\sim\mathcal{N}(\mathbf{0},K_y).$$ So the log marginal likelihood is $$\log p(\mathbf{y}\mid X,\theta)=-\tfrac12\mathbf{y}^\top K_y^{-1}\mathbf{y}\; -\;\tfrac12\log|K_y|\; -\;\tfrac{n}{2}\log(2\pi).$$
Interpretation (very important):
- $-\tfrac12\mathbf{y}^\top K_y^{-1}\mathbf{y}$: data-fit term
- $-\tfrac12\log|K_y|$: complexity penalty (prefers simpler functions unless data demands otherwise)
In code, we compute $K_y^{-1}\mathbf{y}$ and $\log|K_y|$ via a single Cholesky factorization $K_y=LL^\top$ (stable, avoids explicit inverses).
Example 6: Hyperparameters can change the posterior a lot (comparison)¶
The next cell compares two GP posteriors on the same dataset:
- Hand-chosen hyperparameters (a reasonable default)
- Evidence-tuned hyperparameters (picked by maximizing the log marginal likelihood on a coarse grid)
What to look for:
- The posterior mean can shift noticeably even when both fits look “reasonable”.
- The uncertainty band can widen/narrow depending on $\sigma_n$ and $\ell$.
- This is why hyperparameter tuning matters in practice (and why GP results can look very different across settings).
Example 7: Evidence landscape (grid search demo)¶
We maximize the log marginal likelihood $\log p(\mathbf{y}\mid X,\theta)$ to tune hyperparameters. In this teaching demo we do a simple grid search over $(\ell,\sigma_n)$ for the RBF kernel (keeping $\sigma_f^2=1$).
How to read the heatmap:
- x-axis: lengthscale $\ell$ (smoothness)
- y-axis: noise standard deviation $\sigma_n$ (how much we trust data)
- color: log marginal likelihood (higher is better)
- the red dot marks the best grid point
Note: for real problems you usually optimize evidence with gradients (rather than a dense grid), but the grid is great for intuition.
# Use the noisy-sine dataset from Example 2 if available; otherwise create it.
if 'X_train' not in globals() or 'y_train' not in globals():
def f_true(x):
return np.sin(2.5 * x)
n = 12
X_train = np.linspace(-1.2, 1.2, n)
noise_std = 0.15
y_train = f_true(X_train) + noise_std * rng.standard_normal(n)
X_test = np.linspace(-2.0, 2.0, 400)
ell_grid = np.linspace(0.1, 3.2, 45)
noise_grid = np.linspace(0.03, 1, 45)
sigma_f2_fixed = 1.0
lml = np.empty((len(noise_grid), len(ell_grid)))
for i, ns in enumerate(noise_grid):
for j, ell in enumerate(ell_grid):
lml[i, j] = gp_log_marginal_likelihood(
X_train, y_train,
kernel_fn=rbf_kernel,
noise_std=ns,
lengthscale=ell,
variance=sigma_f2_fixed,
)
i_best, j_best = np.unravel_index(np.argmax(lml), lml.shape)
noise_best = float(noise_grid[i_best])
ell_best = float(ell_grid[j_best])
plt.figure(figsize=(8.6, 4.0))
im = plt.imshow(lml, origin='lower', aspect='auto', cmap='viridis',
extent=[ell_grid[0], ell_grid[-1], noise_grid[0], noise_grid[-1]])
plt.colorbar(im, label='log marginal likelihood')
plt.scatter([ell_best], [noise_best], c='red', s=55, edgecolors='k', linewidths=0.5, label='best')
plt.xlabel(r'lengthscale $\ell$')
plt.ylabel(r'noise std $\sigma_n$')
plt.title('Evidence landscape for RBF hyperparameters')
plt.legend()
plt.tight_layout()
plt.show()
print(f'Best (grid): ell={ell_best:.3f}, noise_std={noise_best:.3f}')
Best (grid): ell=0.100, noise_std=0.603
# --- Posterior curves: best hyperparameters vs other choices ---
# Ensure we have a dataset + true function (for visualization)
if 'f_true' not in globals():
def f_true(x):
return np.sin(2.5 * x)
if 'X_train' not in globals() or 'y_train' not in globals():
n = 12
X_train = np.linspace(-1.2, 1.2, n)
noise_std = 0.15
y_train = f_true(X_train) + noise_std * rng.standard_normal(n)
if 'X_test' not in globals():
X_test = np.linspace(-2.0, 2.0, 400)
if 'sigma_f2_fixed' not in globals():
sigma_f2_fixed = 1.0
# If best hyperparameters were not computed (cell above not run), compute them quickly.
if 'ell_best' not in globals() or 'noise_best' not in globals():
ell_grid = np.linspace(0.08, 1.2, 45)
noise_grid = np.linspace(0.03, 0.4, 45)
lml = np.empty((len(noise_grid), len(ell_grid)))
for i, ns in enumerate(noise_grid):
for j, ell in enumerate(ell_grid):
lml[i, j] = gp_log_marginal_likelihood(
X_train, y_train,
kernel_fn=rbf_kernel,
noise_std=ns,
lengthscale=ell,
variance=sigma_f2_fixed,
)
i_best, j_best = np.unravel_index(np.argmax(lml), lml.shape)
noise_best = float(noise_grid[i_best])
ell_best = float(ell_grid[j_best])
# Pick a few contrasting hyperparameter settings for teaching comparison
candidates = [
("Best (evidence)", float(ell_best), float(noise_best)),
("Small ℓ, small σn (more wiggly)", 0.12, 0.03),
("Large ℓ, larger σn (more smooth)", 1.10, 0.10),
("Mid ℓ, mid σn (baseline)", 0.45, 0.07),
]
# Compute posteriors
results = []
for name, ell, ns in candidates:
mean_f, var_f, var_y = gp_posterior_predict(
X_train, y_train, X_test,
kernel_fn=rbf_kernel,
noise_std=ns,
lengthscale=ell,
variance=sigma_f2_fixed,
)
results.append((name, ell, ns, mean_f, var_y))
# 1) Panel plot: each setting with its own uncertainty band
n_panels = len(results)
plt.figure(figsize=(4.6 * n_panels, 3.6))
y_true = f_true(X_test)
ymin = min(np.min(y_train), np.min(y_true)) - 0.8
ymax = max(np.max(y_train), np.max(y_true)) + 0.8
for i, (name, ell, ns, mean_f, var_y) in enumerate(results, 1):
std_y = np.sqrt(np.maximum(var_y, 0.0))
ax = plt.subplot(1, n_panels, i)
ax.plot(X_test, y_true, color='black', lw=1.8, alpha=0.75, label='true f(x)')
ax.scatter(X_train, y_train, s=38, alpha=0.9, edgecolors='k', linewidths=0.35, label='train')
ax.plot(X_test, mean_f, color='crimson', lw=2.0, label='posterior mean')
ax.fill_between(X_test, mean_f - 2*std_y, mean_f + 2*std_y, color='crimson', alpha=0.18, label='±2 std (y)')
ax.set_title(f"{name}\nℓ={ell:.3f}, σn={ns:.3f}")
ax.set_xlabel('x')
if i == 1:
ax.set_ylabel('y')
ax.set_xlim(X_test[0], X_test[-1])
ax.set_ylim(ymin, ymax)
ax.grid(True, ls='--', alpha=0.35)
if i == 1:
ax.legend(fontsize=9)
plt.suptitle('GP posterior under different RBF hyperparameters', y=1.05, fontsize=12)
plt.tight_layout()
plt.show()
# 2) Overlay plot: compare posterior means only (easy to see bias/smoothness)
plt.figure(figsize=(8.0, 4.2))
plt.plot(X_test, y_true, color='black', lw=2.0, alpha=0.75, label='true f(x)')
plt.scatter(X_train, y_train, s=45, alpha=0.9, edgecolors='k', linewidths=0.35, label='train')
for name, ell, ns, mean_f, var_y in results:
plt.plot(X_test, mean_f, lw=2.0, label=f"{name}: ℓ={ell:.3f}, σn={ns:.3f}")
plt.title('Posterior means: best vs other hyperparameters')
plt.xlabel('x')
plt.ylabel('y')
plt.xlim(X_test[0], X_test[-1])
plt.ylim(ymin, ymax)
plt.legend(fontsize=9, ncols=1)
plt.tight_layout()
plt.show()
print(f"Evidence-best (grid): ell={float(ell_best):.4f}, noise_std={float(noise_best):.4f}, sigma_f2={float(sigma_f2_fixed):.3f}")
Evidence-best (grid): ell=0.1000, noise_std=0.6032, sigma_f2=1.000
Example 8: Conditioning intuition with one training point¶
This is the smallest possible GP regression problem: one observation $(x_0,y_0)$. With an RBF kernel, the posterior mean becomes a scaled copy of the kernel centered at $x_0$: $$\mathbb{E}[f(x)\mid y_0] = \frac{k(x,x_0)}{k(x_0,x_0)+\sigma_n^2}\,y_0.$$ So the shape of $k(\cdot,x_0)$ directly shapes how information propagates away from $x_0$.
What to look for in the plot below:
- The mean is a bump around $x_0$ whose width is controlled by $\ell$.
- Uncertainty is smallest near $x_0$ and returns to the prior far away.
- The dashed “closed-form” curve should overlap the GP computed mean (a sanity check).
x0 = 0.3
y0 = 1.0
noise_std_demo = 0.15
ell_demo = 0.45
sigma_f2_demo = 1.0
X_train_demo = np.array([x0])
y_train_demo = np.array([y0])
X_test_demo = np.linspace(-2.0, 2.0, 400)
mean_f_demo, var_f_demo, var_y_demo = gp_posterior_predict(
X_train_demo, y_train_demo, X_test_demo,
kernel_fn=rbf_kernel,
noise_std=noise_std_demo,
lengthscale=ell_demo,
variance=sigma_f2_demo,
)
# Closed-form mean with one point (for intuition check)
k_x_x0 = rbf_kernel(X_test_demo, X_train_demo, lengthscale=ell_demo, variance=sigma_f2_demo).reshape(-1)
k_x0_x0 = rbf_kernel(X_train_demo, X_train_demo, lengthscale=ell_demo, variance=sigma_f2_demo).reshape(-1)[0]
mean_closed = (k_x_x0 / (k_x0_x0 + noise_std_demo**2)) * y0
plt.figure(figsize=(7.6, 4.2))
plt.plot(X_test_demo, mean_f_demo, color='crimson', lw=2.2, label='posterior mean (GP)')
plt.plot(X_test_demo, mean_closed, color='black', lw=1.6, alpha=0.75, ls='--', label='one-point closed form')
std_demo = np.sqrt(np.maximum(var_y_demo, 0.0))
plt.fill_between(X_test_demo, mean_f_demo - 2*std_demo, mean_f_demo + 2*std_demo, color='crimson', alpha=0.18, label='±2 std (y)')
plt.scatter([x0], [y0], s=70, c='gold', edgecolors='k', linewidths=0.6, zorder=5, label='(x0,y0)')
plt.title('One-point conditioning: kernel shape = influence shape')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.tight_layout()
plt.show()
Example 9: Kernel matrix is a “similarity / correlation pattern”¶
A kernel becomes concrete when you visualize the Gram matrix $K(X,X)$.
- Entry $(i,j)$ equals $k(x_i,x_j)$: how strongly the prior correlates $f(x_i)$ and $f(x_j)$.
- Bright values mean “strongly coupled”; dark means “weakly coupled”.
How to read the three heatmaps:
- RBF: a bright diagonal band → nearby points are strongly correlated (smoothness).
- Periodic: repeating diagonal stripes → points one period apart are strongly correlated (repeating structure).
- Linear: large-scale/global structure (often effectively low-rank in 1D), leading to straight-line-like functions.
Important note: these are covariances, not normalized correlations; scaling (e.g., variance) changes brightness.
x_vis = np.linspace(-2.0, 2.0, 120)
K_rbf = rbf_kernel(x_vis, x_vis, lengthscale=0.45, variance=1.0)
K_per = periodic_kernel(x_vis, x_vis, period=1.0, lengthscale=0.25, variance=1.0)
K_lin = linear_kernel(x_vis, x_vis, bias=1.0, variance=1.0)
plt.figure(figsize=(10.8, 3.2))
for i, (name, K) in enumerate([('RBF', K_rbf), ('Periodic', K_per), ('Linear', K_lin)], 1):
ax = plt.subplot(1, 3, i)
im = ax.imshow(K, origin='lower', aspect='auto', cmap='viridis')
ax.set_title(f'K(X,X) — {name}')
ax.set_xlabel('index')
if i == 1:
ax.set_ylabel('index')
plt.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
plt.suptitle('Kernel as a prior correlation pattern', y=1.02, fontsize=12)
plt.tight_layout()
plt.show()