Bayesian Regression and Kernels¶
Course: MCE5919 — Gaussian Process for Machine Learning and Signal Processing
Topic: Bayesian Linear Regression & Kernel Trick (Lecture 3)
Instructor: Wenqiang PU
Date: Jan. 2026
Learning Objectives¶
- Start from Bayesian linear regression (weight space) and derive the posterior and predictive distribution
- Connect feature maps $\phi(x)$ with kernels $k(x,x')$ (the kernel trick)
- Build intuition with simple 1D examples: fewer data points $\Rightarrow$ larger uncertainty; hyperparameters control smoothness/fit
- Implement kernelized Bayesian regression (dual form) and compare different kernels
Environment / Packages¶
Required: numpy, matplotlib (optional: scipy, but this notebook does not depend on it).
If you want interactive plots: install ipympl and enable %matplotlib widget.
# In Jupyter you can switch between inline and widget backends:
%matplotlib inline
# %matplotlib widget
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'
})
np.random.seed(0)
1. Bayesian Linear Regression (Weight Space)¶
Model (Lecture 3 notation)¶
We model scalar outputs with a linear model plus Gaussian noise: $$y_i = \mathbf{x}_i^\top \theta + \varepsilon_i,\qquad \varepsilon_i\sim\mathcal{N}(0,\sigma^2).$$
Stacking $N$ samples gives: $$\mathbf{y} = \mathbf{X}\theta + \varepsilon,\qquad \varepsilon\sim\mathcal{N}(0,\sigma^2\mathbf{I}).$$
We place a Gaussian prior on parameters: $$p(\theta)=\mathcal{N}(\theta\mid \mathbf{0},\mathbf{C}).$$
In many demos (including our code) we use the simple isotropic prior $\mathbf{C}=\alpha^{-1}\mathbf{I}$, where $\alpha$ is the prior precision.
Mapping to code: the design matrix $\mathbf{X}$ is called Phi in code, because it is often built from a feature map $\phi(x)$ (e.g., polynomial features).
Posterior¶
With a Gaussian prior and Gaussian noise, the posterior is still Gaussian: $$p(\theta\mid \mathbf{y},\mathbf{X})=\mathcal{N}(\theta\mid \mathbf{m}_N,\mathbf{S}_N).$$
A convenient closed form is $$\begin{aligned} \mathbf{S}_N^{-1} &= \mathbf{C}^{-1}+\frac{1}{\sigma^2}\mathbf{X}^\top\mathbf{X},\\ \mathbf{m}_N &= \frac{1}{\sigma^2}\mathbf{S}_N\mathbf{X}^\top\mathbf{y}. \end{aligned}$$
Predictive¶
For a new input feature vector $\mathbf{x}_*$, the predictive distribution is $$p(y_*\mid \mathbf{x}_*,\mathcal{D})=\mathcal{N}(\mu_*,\sigma_{y,*}^2),$$ with $$\begin{aligned} \mu_* &= \mathbf{x}_*^\top\mathbf{m}_N,\\ \sigma_{y,*}^2 &= \sigma^2 + \mathbf{x}_*^\top\mathbf{S}_N\mathbf{x}_*. \end{aligned}$$
Next we visualize these formulas using a very simple 1D example.
def make_polynomial_features(x: np.ndarray, degree: int) -> np.ndarray:
"""Return Phi with columns [1, x, x^2, ..., x^degree].
x: shape (n,) or (n,1)
"""
x = np.asarray(x).reshape(-1)
return np.vstack([x**k for k in range(degree + 1)]).T
def bayes_linear_regression_posterior(Phi: np.ndarray, y: np.ndarray, alpha: float, sigma: float):
"""Posterior over weights w in Bayesian linear regression.
Prior: w ~ N(0, alpha^{-1} I)
Likelihood: y | w ~ N(Phi w, sigma^2 I)
Returns: (m_N, S_N)
m_N: posterior mean (d,)
S_N: posterior covariance (d,d)
"""
y = np.asarray(y).reshape(-1)
n, d = Phi.shape
A = alpha * np.eye(d) + (Phi.T @ Phi) / (sigma**2)
S_N = np.linalg.inv(A)
m_N = (S_N @ Phi.T @ y) / (sigma**2)
return m_N, S_N
def bayes_linear_regression_predict(Phi_star: np.ndarray, m_N: np.ndarray, S_N: np.ndarray, sigma: float):
"""Predictive mean/variance for y* at test features Phi_star."""
mu = Phi_star @ m_N
var = sigma**2 + np.sum(Phi_star @ S_N * Phi_star, axis=1)
return mu, var
Example 1: Line fitting + uncertainty (minimal working example)¶
We use linear features $\phi(x)=[1,x]$ and plot:
- training points
- predictive mean $\mu(x)$
- the band $\mu(x)\pm 2\sqrt{\sigma_y^2(x)}$ (roughly a 95% interval under a Gaussian)
def plot_predictive_1d(x_train, y_train, x_test, mu, var, title: str):
std = np.sqrt(np.maximum(var, 0.0))
plt.figure(figsize=(7.2, 4.6))
plt.scatter(x_train, y_train, s=55, alpha=0.9, edgecolors='k', linewidths=0.4, label='train')
plt.plot(x_test, mu, color='crimson', lw=2.2, label='predictive mean')
plt.fill_between(x_test, mu - 2*std, mu + 2*std, color='crimson', alpha=0.18, label='±2 std')
plt.xlabel('x')
plt.ylabel('y')
plt.title(title)
plt.legend()
plt.tight_layout()
plt.show()
# Generate a tiny dataset from a line
n = 8
x_train = np.linspace(-1.0, 1.0, n)
beta_true = np.array([0.5, 1.5])
sigma = 0.05
y_train = beta_true[0] + beta_true[1] * x_train + sigma * np.random.randn(n)
# Bayesian linear regression with degree=1 polynomial features (i.e., [1, x])
degree = 1
Phi = make_polynomial_features(x_train, degree)
alpha = 100 # prior precision (larger -> stronger shrinkage)
mN, SN = bayes_linear_regression_posterior(Phi, y_train, alpha=alpha, sigma=sigma)
x_test = np.linspace(-1.2, 1.2, 300)
Phi_star = make_polynomial_features(x_test, degree)
mu, var = bayes_linear_regression_predict(Phi_star, mN, SN, sigma=sigma)
plot_predictive_1d(x_train, y_train, x_test, mu, var, title='Bayesian Linear Regression (degree=1)')
Example 2: Hyperparameter effects ($\alpha$ and $\sigma$)¶
Intuition:
- Larger $\alpha$ (stronger prior precision) shrinks weights more strongly toward $0$ $\Rightarrow$ more conservative / smoother fit
- Larger $\sigma$ (higher noise) increases predictive uncertainty and makes the model trust each data point less
We keep the same dataset and vary hyperparameters to see how the mean curve and uncertainty band change.
x_test = np.linspace(-1.2, 1.2, 300)
Phi_star = make_polynomial_features(x_test, degree=1)
settings = [
{'alpha': 0.2, 'sigma': 0.25, 'name': 'weak prior (alpha=0.2), low noise (sigma=0.25)'},
{'alpha': 10.0, 'sigma': 0.25, 'name': 'strong prior (alpha=10), low noise (sigma=0.25)'},
{'alpha': 2.0, 'sigma': 0.6, 'name': 'medium prior (alpha=2), high noise (sigma=0.6)'},
{'alpha': 10.0, 'sigma': 0.6, 'name': 'strong prior (alpha=10), high noise (sigma=0.6)'},
]
plt.figure(figsize=(10.5, 7.5))
for i, cfg in enumerate(settings, 1):
alpha_i, sigma_i = cfg['alpha'], cfg['sigma']
Phi = make_polynomial_features(x_train, degree=1)
mN, SN = bayes_linear_regression_posterior(Phi, y_train, alpha=alpha_i, sigma=sigma_i)
mu, var = bayes_linear_regression_predict(Phi_star, mN, SN, sigma=sigma_i)
std = np.sqrt(np.maximum(var, 0.0))
ax = plt.subplot(2, 2, i)
ax.scatter(x_train, y_train, s=40, alpha=0.9, edgecolors='k', linewidths=0.4)
ax.plot(x_test, mu, color='crimson', lw=2)
ax.fill_between(x_test, mu - 2*std, mu + 2*std, color='crimson', alpha=0.18)
ax.set_title(cfg['name'], fontsize=10)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.grid(True, ls='--', alpha=0.35)
plt.tight_layout()
plt.show()
Example 3: Polynomial degree (underfitting vs overfitting)¶
We extend features from $[1,x]$ to $[1,x,x^2,\dots,x^M]$.
- If $M$ is too small: underfitting (insufficient expressiveness)
- If $M$ is too large: the mean can become very flexible, but Bayesian inference will reflect uncertainty explicitly (especially outside dense data regions)
We keep the same dataset and compare different polynomial degrees using the predictive mean and uncertainty band.
# Synthetic non-linear data (a smooth curve)
n = 50
x_train2 = np.linspace(-1.0, 1.0, n)
f_true = lambda x: np.sin(3 * x)
sigma2 = 0.05
y_train2 = f_true(x_train2) + sigma2 * np.random.randn(n)
x_test2 = np.linspace(-1.2, 1.2, 400)
degrees = [1, 3, 9]
alpha = 10
plt.figure(figsize=(10.5, 7.5))
for i, deg in enumerate(degrees, 1):
Phi = make_polynomial_features(x_train2, deg)
mN, SN = bayes_linear_regression_posterior(Phi, y_train2, alpha=alpha, sigma=sigma2)
Phi_star = make_polynomial_features(x_test2, deg)
mu, var = bayes_linear_regression_predict(Phi_star, mN, SN, sigma=sigma2)
std = np.sqrt(np.maximum(var, 0.0))
ax = plt.subplot(2, 2, i)
ax.scatter(x_train2, y_train2, s=40, alpha=0.9, edgecolors='k', linewidths=0.4, label='train')
ax.plot(x_test2, f_true(x_test2), color='black', lw=2, alpha=0.8, label='true f(x)')
ax.plot(x_test2, mu, color='crimson', lw=2.0, label='mean')
ax.fill_between(x_test2, mu - 2*std, mu + 2*std, color='crimson', alpha=0.18, label='±2 std')
ax.set_title(f'Polynomial degree={deg}', fontsize=11)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.grid(True, ls='--', alpha=0.35)
if i == 1:
ax.legend(fontsize=9)
plt.subplot(2, 2, 4)
plt.axis('off')
plt.text(0.0, 0.85, 'Discussion:', fontsize=12, weight='bold')
plt.text(0.0, 0.60, '- degree=1: often underfits a curved function', fontsize=11)
plt.text(0.0, 0.40, '- degree=9: flexible mean but uncertainty shows data scarcity', fontsize=11)
plt.text(0.0, 0.20, '- prior (alpha) controls how wild the fit can be', fontsize=11)
plt.tight_layout()
plt.show()
2. From Features to Kernels (Kernel Trick)¶
Key idea¶
In Bayesian linear regression we often introduce a feature map $\phi(x)$ and build a design matrix $\Phi$ (each row is $\phi(x_i)^\top$). If the feature dimension is very large (or infinite), explicitly forming $\Phi$ can be expensive.
Kernel trick: if computations depend on inner products only, we can use a kernel $$k(x,x') = \phi(x)^\top\phi(x')$$ and avoid constructing $\phi(x)$ explicitly.
A useful identity (finite-dimensional features): $$\mathbf{K}=\Phi\Phi^\top,\qquad K_{ij}=\phi(x_i)^\top\phi(x_j).$$
We use $\phi(x)$ as a concrete way to build nonlinear models while keeping linear-in-parameters inference.
For example, polynomial features (used in Examples 1 and 3) are
$$\phi(x)=[1,\,x,\,x^2,\,\dots,\,x^M]^\top.$$
In code, make_polynomial_features(x, degree=M) constructs the matrix $\Phi$ with columns $[1, x, \dots, x^M]$.
RBF kernel (squared exponential)¶
The RBF kernel corresponds to an (infinite-dimensional) feature map and yields smooth functions. For inputs $x\in\mathbb{R}^d$: $$k_{\text{RBF}}(x,x') = s^2\exp\Bigl(-\frac{\lVert x-x'\rVert_2^2}{2\ell^2}\Bigr),$$ where
- $\ell$ is the lengthscale (how quickly similarity decays with distance)
- $s^2$ is the variance (overall scale)
In code, rbf_kernel(x1, x2, lengthscale=..., variance=...) implements the 1D case using squared distances.
How this connects to the code examples¶
- Example 4 (kernel matrix heatmap): builds $\mathbf{K}$ via
K = rbf_kernel(x_grid, x_grid, lengthscale=ell, ...)and visualizes how changing $\ell$ changes similarity structure. - Example 10 (lengthscale sweep, dual form): uses
kernelized_bayes_predict(..., rbf_kernel, lengthscale=ell, ...)to show how $\ell$ changes smoothness and uncertainty in predictions. - Primal vs dual viewpoint: in weight space we compute with $\Phi$ (explicit features), while in the kernelized form we compute with $\mathbf{K}$ and $k(X,x_*)$ without ever building $\phi(x)$.
One-sentence summary¶
- Primal / weight space: do Bayesian inference on parameters $\theta$ (or $w$) using $\Phi$
- Dual / sample space: do prediction using only the Gram matrix $\mathbf{K}$ with $K_{ij}=k(x_i,x_j)$
- Prediction depends on similarities $k(x_i,x_*)$, not on explicit high-dimensional features
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 = np.asarray(x1).reshape(-1, 1)
x2 = np.asarray(x2).reshape(-1, 1)
sqdist = (x1 - x2.T) ** 2
return variance * np.exp(-0.5 * sqdist / (lengthscale**2))
def polynomial_kernel(x1: np.ndarray, x2: np.ndarray, degree: int = 3, c: float = 1.0) -> np.ndarray:
"""Polynomial kernel k(x,x') = (x x' + c)^degree for 1D inputs."""
x1 = np.asarray(x1).reshape(-1, 1)
x2 = np.asarray(x2).reshape(-1, 1)
return (x1 @ x2.T + c) ** degree
Example 4: Visualize the kernel matrix (similarity matrix)¶
We do one thing here: plot $K_{ij}=k(x_i,x_j)$ as a heatmap. This often helps students understand the role of the RBF lengthscale $\ell$ quickly.
x_grid = np.linspace(-1.0, 1.0, 30)
ells = [0.05, 0.4, 2.0]
plt.figure(figsize=(10.5, 3.2))
for i, ell in enumerate(ells, 1):
K = rbf_kernel(x_grid, x_grid, lengthscale=ell, variance=1.0)
ax = plt.subplot(1, 3, i)
im = ax.imshow(K, origin='lower', cmap='viridis', extent=[x_grid.min(), x_grid.max(), x_grid.min(), x_grid.max()])
ax.set_title(rf'RBF kernel matrix ($\ell={ell}$)', fontsize=10)
ax.set_xlabel('x')
if i == 1:
ax.set_ylabel("x'")
plt.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
plt.tight_layout()
plt.show()
3. Kernelized Bayesian Regression (Dual Form)¶
This section rewrites Bayesian linear regression so that prediction depends only on the Gram matrix (kernel evaluations). Conceptually:
- We are still doing Bayesian linear regression
- But we express everything using $k(x,x')$ (similarity) instead of explicit features $\phi(x)$
Dual predictive formula (core result)¶
Given training inputs $X=[x_1,\dots,x_N]$ and targets $\mathbf{y}\in\mathbb{R}^N$, define the Gram matrix $$K_0(X,X)_{ij}=k(x_i,x_j).$$
Under the isotropic weight prior $\theta\sim\mathcal{N}(\mathbf{0},\alpha^{-1}\mathbf{I})$, the induced covariance in function space scales as $$\mathbf{K} = \frac{1}{\alpha}\mathbf{K}_0.$$
Assume observation noise variance $\sigma^2$. For a test input $x_*$, define $$\mathbf{k}_* = \frac{1}{\alpha}k(X,x_*)\in\mathbb{R}^N,\qquad k_{**}=\frac{1}{\alpha}k(x_*,x_*).$$ and $$\mathbf{\Sigma} = \mathbf{K} + \sigma^2\mathbf{I}.$$
Then the predictive mean and variance for the latent value $f_*$ are $$\mu_* = \mathbf{k}_*^\top\mathbf{\Sigma}^{-1}\mathbf{y},$$ $$\sigma_{f,*}^2 = k_{**} - \mathbf{k}_*^\top\mathbf{\Sigma}^{-1}\mathbf{k}_*.$$
For the noisy observation $y_*=f_*+\varepsilon$, add noise: $\sigma_{y,*}^2=\sigma_{f,*}^2+\sigma^2$.
In code we use a small jitter for numerical stability when factorizing $\mathbf{\Sigma}$.
def linear_kernel(x1: np.ndarray, x2: np.ndarray) -> np.ndarray:
x1 = np.asarray(x1).reshape(-1, 1)
x2 = np.asarray(x2).reshape(-1, 1)
return x1 @ x2.T
def monomial_kernel(x1: np.ndarray, x2: np.ndarray, degree: int) -> np.ndarray:
"""Kernel matching the explicit monomial features [1, x, x^2, ..., x^degree].
k(x,x') = sum_{m=0}^degree x^m (x')^m
"""
x1 = np.asarray(x1).reshape(-1, 1)
x2 = np.asarray(x2).reshape(-1, 1)
prod = x1 @ x2.T
K = np.zeros_like(prod, dtype=float)
for m in range(degree + 1):
K += prod ** m
return K
def kernelized_bayes_predict(X_train: np.ndarray, y_train: np.ndarray, X_test: np.ndarray, kernel_fn, alpha: float, sigma: float, jitter: float = 1e-8, **kernel_kwargs):
"""Kernelized Bayesian regression (dual form) with Gaussian noise.
This is the dual computation of Bayesian linear regression where predictions depend on the Gram matrix only.
Returns: (mu, var_f, var_y) over test points.
"""
X_train = np.asarray(X_train).reshape(-1)
y_train = np.asarray(y_train).reshape(-1)
X_test = np.asarray(X_test).reshape(-1)
K0 = kernel_fn(X_train, X_train, **kernel_kwargs)
Ks0 = kernel_fn(X_train, X_test, **kernel_kwargs)
Kss0 = kernel_fn(X_test, X_test, **kernel_kwargs)
# Effective scaling from theta~N(0, alpha^{-1}I): K = (1/alpha) * K0
K = (1.0 / alpha) * K0
Ks = (1.0 / alpha) * Ks0
Kss = (1.0 / alpha) * Kss0
Sigma = K + (sigma**2 + jitter) * np.eye(len(X_train))
L = np.linalg.cholesky(Sigma)
a = np.linalg.solve(L.T, np.linalg.solve(L, y_train))
mu = Ks.T @ a
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 + sigma**2
return mu, var_f, var_y
def plot_mean_and_band(x_train, y_train, x_test, mu, var, title: str, true_fn=None):
std = np.sqrt(np.maximum(var, 0.0))
plt.figure(figsize=(7.4, 4.8))
plt.scatter(x_train, y_train, s=55, alpha=0.9, edgecolors='k', linewidths=0.4, label='train')
if true_fn is not None:
plt.plot(x_test, true_fn(x_test), color='black', lw=2, alpha=0.75, label='true f(x)')
plt.plot(x_test, mu, color='crimson', lw=2.2, label='predictive mean')
plt.fill_between(x_test, mu - 2*std, mu + 2*std, color='crimson', alpha=0.18, label='±2 std')
plt.xlabel('x')
plt.ylabel('y')
plt.title(title)
plt.legend(fontsize=9)
plt.tight_layout()
plt.show()
Example 5: Primal vs Dual (same model, two computations)¶
We solve the same problem in two ways:
- Primal: explicit polynomial features
- Dual: a matching monomial kernel
With the same $\alpha$ and $\sigma$, the predictive mean (and uncertainty) should match up to numerical precision.
# Reuse the non-linear dataset from Example 3
X_train = x_train2
y_train = y_train2
X_test = x_test2
true_fn = f_true
deg = 5
alpha = 2
sigma = sigma2
# Primal (explicit features)
Phi = make_polynomial_features(X_train, deg)
mN, SN = bayes_linear_regression_posterior(Phi, y_train, alpha=alpha, sigma=sigma)
Phi_star = make_polynomial_features(X_test, deg)
mu_primal, var_primal = bayes_linear_regression_predict(Phi_star, mN, SN, sigma=sigma)
# Dual (kernelized)
mu_dual, varf_dual, vary_dual = kernelized_bayes_predict(
X_train, y_train, X_test, monomial_kernel, alpha=alpha, sigma=sigma, degree=deg
)
# Compare
max_abs_diff = float(np.max(np.abs(mu_primal - mu_dual)))
print(f"max |mu_primal - mu_dual| = {max_abs_diff:.3e}")
plot_mean_and_band(X_train, y_train, X_test, mu_primal, var_primal, title=f'Primal (explicit features), degree={deg}', true_fn=true_fn)
plot_mean_and_band(X_train, y_train, X_test, mu_dual, vary_dual, title=f'Dual (kernel), degree={deg}', true_fn=true_fn)
max |mu_primal - mu_dual| = 9.431e-07
Example 6: Compare kernels (Linear vs Monomial vs RBF)¶
On the same dataset, changing the kernel (the similarity definition) can dramatically change smoothness and extrapolation behavior. We keep the same $\alpha$ and $\sigma$ and vary only the kernel.
alpha = 2.0
sigma = sigma2
X_train = x_train2
y_train = y_train2
X_test = x_test2
kernels = [
('Linear', linear_kernel, {}),
('Monomial degree=9', monomial_kernel, {'degree': 9}),
(r'RBF ($\ell=0.35$)', rbf_kernel, {'lengthscale': 0.35, 'variance': 1.0}),
]
plt.figure(figsize=(10.5, 7.5))
for i, (name, kfn, kw) in enumerate(kernels, 1):
mu, var_f, var_y = kernelized_bayes_predict(X_train, y_train, X_test, kfn, alpha=alpha, sigma=sigma, **kw)
std = np.sqrt(np.maximum(var_y, 0.0))
ax = plt.subplot(2, 2, i)
ax.scatter(X_train, y_train, s=40, alpha=0.9, edgecolors='k', linewidths=0.4, label='train')
ax.plot(X_test, f_true(X_test), color='black', lw=2, alpha=0.75, label='true f(x)')
ax.plot(X_test, mu, color='crimson', lw=2.0, label='mean')
ax.fill_between(X_test, mu - 2*std, mu + 2*std, color='crimson', alpha=0.18, label='±2 std')
ax.set_title(name, fontsize=11)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.grid(True, ls='--', alpha=0.35)
if i == 1:
ax.legend(fontsize=9)
plt.subplot(2, 2, 4)
plt.axis('off')
plt.text(0.0, 0.85, 'Discussion:', fontsize=12, weight='bold')
plt.text(0.0, 0.62, '- Linear kernel: limited flexibility', fontsize=11)
plt.text(0.0, 0.42, '- Monomial: flexible but can be unstable outside data range', fontsize=11)
plt.text(0.0, 0.22, r'- RBF: smooth, local generalization controlled by $\ell$', fontsize=11)
plt.tight_layout()
plt.show()
Example 7: How data size affects uncertainty (fewer points → larger uncertainty)¶
We fix the same kernel and hyperparameters, and only change the number of training points to see how the uncertainty band changes.
alpha = 2.0
sigma = sigma2
ell = 0.35
kernel_kwargs = {'lengthscale': ell, 'variance': 1.0}
X_all = x_train2
y_all = y_train2
X_test = x_test2
idx_small = np.array([0, 3, 6, 9]) # 4 points spread out
X_small = X_all[idx_small]
y_small = y_all[idx_small]
cases = [
('4 training points', X_small, y_small),
('12 training points', X_all, y_all),
]
plt.figure(figsize=(10.5, 4.8))
for i, (name, Xtr, ytr) in enumerate(cases, 1):
mu, _, var_y = kernelized_bayes_predict(Xtr, ytr, X_test, rbf_kernel, alpha=alpha, sigma=sigma, **kernel_kwargs)
std = np.sqrt(np.maximum(var_y, 0.0))
ax = plt.subplot(1, 2, i)
ax.scatter(Xtr, ytr, s=55, alpha=0.9, edgecolors='k', linewidths=0.4, label='train')
ax.plot(X_test, f_true(X_test), color='black', lw=2, alpha=0.75, label='true f(x)')
ax.plot(X_test, mu, color='crimson', lw=2.0, label='mean')
ax.fill_between(X_test, mu - 2*std, mu + 2*std, color='crimson', alpha=0.18, label='±2 std')
ax.set_title(name, fontsize=11)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.grid(True, ls='--', alpha=0.35)
ax.legend(fontsize=9)
plt.suptitle(rf'Same kernel (RBF, $\ell={ell}$) but different #points', y=1.02, fontsize=12)
plt.tight_layout()
plt.show()
Example 8: Using a non-isotropic prior covariance $\mathbf{C}$¶
Slides use a general prior covariance $\mathbf{C}$: $p(\theta)=\mathcal{N}(\mathbf{0},\mathbf{C})$. A practical interpretation: you can encode which directions of $\theta$ you believe should be small/large before seeing data.
Here we compare:
- Isotropic prior $\mathbf{C}=\alpha^{-1}\mathbf{I}$
- Decaying variances (stronger shrinkage on higher-order polynomial coefficients)
This is still Bayesian linear regression in weight space, but it helps students see what $\mathbf{C}$ does.
def bayes_linear_regression_posterior_with_cov(Phi: np.ndarray, y: np.ndarray, C: np.ndarray, sigma: float):
"""Posterior for theta with prior theta~N(0,C), y|theta~N(Phi theta, sigma^2 I)."""
y = np.asarray(y).reshape(-1)
C = np.asarray(C)
A = np.linalg.inv(C) + (Phi.T @ Phi) / (sigma**2)
S = np.linalg.inv(A)
m = (S @ Phi.T @ y) / (sigma**2)
return m, S
# Compare isotropic vs decaying prior covariance
deg = 9
sigma = sigma2
Phi = make_polynomial_features(x_train2, deg)
Phi_star = make_polynomial_features(x_test2, deg)
alpha = 2.0
C_iso = (1.0 / alpha) * np.eye(Phi.shape[1])
# Prior variances decay with degree: var_k = s0^2 * r^{2k}
s0 = 5.0
r = 0.55
prior_vars = np.array([(s0 * (r**k))**2 for k in range(deg + 1)])
C_decay = np.diag(prior_vars)
m_iso, S_iso = bayes_linear_regression_posterior_with_cov(Phi, y_train2, C_iso, sigma=sigma)
m_dec, S_dec = bayes_linear_regression_posterior_with_cov(Phi, y_train2, C_decay, sigma=sigma)
mu_iso, var_iso = bayes_linear_regression_predict(Phi_star, m_iso, S_iso, sigma=sigma)
mu_dec, var_dec = bayes_linear_regression_predict(Phi_star, m_dec, S_dec, sigma=sigma)
plt.figure(figsize=(10.5, 4.8))
for i, (name, mu, var) in enumerate([('Isotropic prior', mu_iso, var_iso), ('Decaying-variance prior', mu_dec, var_dec)], 1):
std = np.sqrt(np.maximum(var, 0.0))
ax = plt.subplot(1, 2, i)
ax.scatter(x_train2, y_train2, s=45, alpha=0.9, edgecolors='k', linewidths=0.4, label='train')
ax.plot(x_test2, f_true(x_test2), color='black', lw=2, alpha=0.75, label='true f(x)')
ax.plot(x_test2, mu, color='crimson', lw=2.0, label='mean')
ax.fill_between(x_test2, mu - 2*std, mu + 2*std, color='crimson', alpha=0.18, label='±2 std')
ax.set_title(name, fontsize=11)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.grid(True, ls='--', alpha=0.35)
ax.legend(fontsize=9)
plt.suptitle('Effect of prior covariance $C$ (same degree, same data)', y=1.02, fontsize=12)
plt.tight_layout()
plt.show()
Example 9: RBF lengthscale sweep in the dual form¶
The RBF kernel lengthscale $\ell$ controls how quickly similarity decays with distance. We fix $\alpha$ and $\sigma$ and only vary $\ell$ to see how it changes smoothness and uncertainty.
alpha = 2.0
sigma = sigma2
ells = [0.15, 0.35, 0.9]
plt.figure(figsize=(10.5, 7.2))
for i, ell in enumerate(ells, 1):
mu, _, var_y = kernelized_bayes_predict(
x_train2, y_train2, x_test2, rbf_kernel, alpha=alpha, sigma=sigma, lengthscale=ell, variance=1.0
)
std = np.sqrt(np.maximum(var_y, 0.0))
ax = plt.subplot(2, 2, i)
ax.scatter(x_train2, y_train2, s=40, alpha=0.9, edgecolors='k', linewidths=0.4, label='train')
ax.plot(x_test2, f_true(x_test2), color='black', lw=2, alpha=0.75, label='true f(x)')
ax.plot(x_test2, mu, color='crimson', lw=2.0, label='mean')
ax.fill_between(x_test2, mu - 2*std, mu + 2*std, color='crimson', alpha=0.18, label='±2 std')
ax.set_title(rf'RBF kernel, $\ell={ell}$', fontsize=11)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.grid(True, ls='--', alpha=0.35)
if i == 1:
ax.legend(fontsize=9)
plt.subplot(2, 2, 4)
plt.axis('off')
plt.text(0.0, 0.85, 'Discussion:', fontsize=12, weight='bold')
plt.text(0.0, 0.62, r'- small $\ell$: very local influence (wiggly mean, narrow influence regions)', fontsize=11)
plt.text(0.0, 0.42, r'- large $\ell$: very global influence (smooth mean)', fontsize=11)
plt.text(0.0, 0.22, r'- uncertainty grows where similarity to training points is low', fontsize=11)
plt.tight_layout()
plt.show()