|
| 1 | +# --- |
| 2 | +# jupyter: |
| 3 | +# jupytext: |
| 4 | +# cell_metadata_filter: -all |
| 5 | +# custom_cell_magics: kql |
| 6 | +# text_representation: |
| 7 | +# extension: .py |
| 8 | +# format_name: percent |
| 9 | +# format_version: '1.3' |
| 10 | +# jupytext_version: 1.17.3 |
| 11 | +# kernelspec: |
| 12 | +# display_name: python3 |
| 13 | +# language: python |
| 14 | +# name: python3 |
| 15 | +# --- |
| 16 | + |
| 17 | +# %% [markdown] |
| 18 | +# # Joint Inference with Numpyro |
| 19 | +# |
| 20 | +# In this notebook, we demonstrate how to use [Numpyro](https://num.pyro.ai/) to perform fully Bayesian inference over the hyperparameters of a Gaussian process model. |
| 21 | +# We will look at a scenario where we have a structured mean function (a linear model) and a GP capturing the residuals. We will infer the parameters of both the linear model and the GP jointly. |
| 22 | + |
| 23 | +# %% |
| 24 | +from jax import config |
| 25 | +import jax.numpy as jnp |
| 26 | +import jax.random as jr |
| 27 | +import matplotlib.pyplot as plt |
| 28 | +import numpyro |
| 29 | +import numpyro.distributions as dist |
| 30 | +from numpyro.infer import ( |
| 31 | + MCMC, |
| 32 | + NUTS, |
| 33 | +) |
| 34 | + |
| 35 | +import gpjax as gpx |
| 36 | +from gpjax.numpyro_extras import register_parameters |
| 37 | + |
| 38 | +config.update("jax_enable_x64", True) |
| 39 | + |
| 40 | +key = jr.key(42) |
| 41 | + |
| 42 | +# %% [markdown] |
| 43 | +# ## Data Generation |
| 44 | +# |
| 45 | +# We generate a synthetic dataset that consists of a linear trend, a periodic component, and some noise. |
| 46 | + |
| 47 | +# %% |
| 48 | +N = 100 |
| 49 | +x = jnp.sort(jr.uniform(key, shape=(N, 1), minval=0.0, maxval=10.0), axis=0) |
| 50 | + |
| 51 | +# True parameters |
| 52 | +true_slope = 0.5 |
| 53 | +true_intercept = 2.0 |
| 54 | +true_period = 2.0 |
| 55 | +true_lengthscale = 1.0 |
| 56 | +true_noise = 0.1 |
| 57 | + |
| 58 | +# Signal |
| 59 | +linear_trend = true_slope * x + true_intercept |
| 60 | +periodic_signal = jnp.sin(2 * jnp.pi * x / true_period) |
| 61 | +y_clean = linear_trend + periodic_signal |
| 62 | + |
| 63 | +# Observations |
| 64 | +y = y_clean + true_noise * jr.normal(key, shape=x.shape) |
| 65 | + |
| 66 | +plt.figure(figsize=(10, 5)) |
| 67 | +plt.scatter(x, y, label="Data", alpha=0.6) |
| 68 | +plt.plot(x, y_clean, "k--", label="True Signal") |
| 69 | +plt.legend() |
| 70 | +plt.show() |
| 71 | + |
| 72 | +# %% [markdown] |
| 73 | +# ## Model Definition |
| 74 | +# |
| 75 | +# We define a GP model with a generic mean function (zero for now, as we will handle the linear trend explicitly in the Numpyro model) and a kernel that is the product of a periodic kernel and an RBF kernel. This choice reflects our prior knowledge that the signal is locally periodic. |
| 76 | + |
| 77 | +# %% |
| 78 | +kernel = gpx.kernels.RBF() * gpx.kernels.Periodic() |
| 79 | +meanf = gpx.mean_functions.Zero() |
| 80 | +prior = gpx.gps.Prior(mean_function=meanf, kernel=kernel) |
| 81 | + |
| 82 | +# We will use a ConjugatePosterior since we assume Gaussian noise |
| 83 | +likelihood = gpx.likelihoods.Gaussian(num_datapoints=N) |
| 84 | +posterior = prior * likelihood |
| 85 | + |
| 86 | +# We initialise the model parameters. |
| 87 | +# Note: These values will be overwritten by Numpyro samples during inference. |
| 88 | +D = gpx.Dataset(X=x, y=y) |
| 89 | + |
| 90 | +# %% [markdown] |
| 91 | +# ## Joint Inference Loop |
| 92 | +# |
| 93 | +# We define a Numpyro model function that: |
| 94 | +# 1. Samples the parameters for the linear trend. |
| 95 | +# 2. Computes the residuals (Data - Linear Trend). |
| 96 | +# 3. Samples the GP hyperparameters using `register_parameters`. |
| 97 | +# 4. Computes the GP marginal log-likelihood on the residuals. |
| 98 | +# 5. Adds the GP log-likelihood to the joint density. |
| 99 | + |
| 100 | + |
| 101 | +# %% |
| 102 | +def model(X, Y): |
| 103 | + # 1. Sample linear model parameters |
| 104 | + slope = numpyro.sample("slope", dist.Normal(0.0, 2.0)) |
| 105 | + intercept = numpyro.sample("intercept", dist.Normal(0.0, 2.0)) |
| 106 | + |
| 107 | + # Calculate residuals |
| 108 | + trend = slope * X + intercept |
| 109 | + residuals = Y - trend |
| 110 | + |
| 111 | + # 2. Register GP parameters |
| 112 | + # This automatically samples parameters from the GPJax model |
| 113 | + # and returns a model with updated values. |
| 114 | + # We can specify custom priors if needed, but we'll rely on defaults here. |
| 115 | + # register_parameters modifies the model in-place (and returns it). |
| 116 | + # Since Numpyro re-runs this function, we are overwriting the parameters |
| 117 | + # of the same object repeatedly, which is fine as they are completely determined |
| 118 | + # by the sample sites. |
| 119 | + p_posterior = register_parameters(posterior) |
| 120 | + |
| 121 | + # Create dataset for residuals |
| 122 | + D_resid = gpx.Dataset(X=X, y=residuals) |
| 123 | + |
| 124 | + # 3. Compute MLL |
| 125 | + # We use conjugate_mll which computes log p(y | X, theta) analytically for Gaussian likelihoods. |
| 126 | + mll = gpx.objectives.conjugate_mll(p_posterior, D_resid) |
| 127 | + |
| 128 | + # 4. Add to potential |
| 129 | + numpyro.factor("gp_log_lik", mll) |
| 130 | + |
| 131 | + |
| 132 | +# %% [markdown] |
| 133 | +# ## Running MCMC |
| 134 | +# |
| 135 | +# We use the NUTS sampler to draw samples from the posterior. |
| 136 | + |
| 137 | +# %% |
| 138 | +nuts_kernel = NUTS(model) |
| 139 | +mcmc = MCMC(nuts_kernel, num_warmup=500, num_samples=1000, num_chains=1) |
| 140 | +mcmc.run(jr.key(0), x, y) |
| 141 | + |
| 142 | +mcmc.print_summary() |
| 143 | + |
| 144 | +# %% [markdown] |
| 145 | +# ## Analysis and Plotting |
| 146 | +# |
| 147 | +# We extract the samples and plot the predictions. |
| 148 | + |
| 149 | +# %% |
| 150 | +samples = mcmc.get_samples() |
| 151 | + |
| 152 | + |
| 153 | +# Helper to get predictions |
| 154 | +def predict(rng_key, sample_idx): |
| 155 | + # Reconstruct model with sampled values |
| 156 | + |
| 157 | + # Linear part |
| 158 | + slope = samples["slope"][sample_idx] |
| 159 | + intercept = samples["intercept"][sample_idx] |
| 160 | + trend = slope * x + intercept |
| 161 | + |
| 162 | + # GP part |
| 163 | + # We use numpyro.handlers.substitute to inject the sampled values into register_parameters |
| 164 | + # to reconstruct the GP model state for this sample. |
| 165 | + sample_dict = {k: v[sample_idx] for k, v in samples.items()} |
| 166 | + |
| 167 | + with numpyro.handlers.substitute(data=sample_dict): |
| 168 | + # We call register_parameters again to update the posterior object with this sample's values |
| 169 | + p_posterior = register_parameters(posterior) |
| 170 | + |
| 171 | + # Now predict on residuals |
| 172 | + residuals = y - trend |
| 173 | + D_resid = gpx.Dataset(X=x, y=residuals) |
| 174 | + |
| 175 | + latent_dist = p_posterior.predict(x, train_data=D_resid) |
| 176 | + predictive_mean = latent_dist.mean |
| 177 | + predictive_std = latent_dist.stddev() |
| 178 | + |
| 179 | + return trend + predictive_mean, predictive_std |
| 180 | + |
| 181 | + |
| 182 | +# Plot |
| 183 | +plt.figure(figsize=(12, 6)) |
| 184 | +plt.scatter(x, y, alpha=0.5, label="Data", color="gray") |
| 185 | +plt.plot(x, y_clean, "k--", label="True Signal") |
| 186 | + |
| 187 | +# Compute mean prediction (using mean of samples for efficiency) |
| 188 | +mean_slope = jnp.mean(samples["slope"]) |
| 189 | +mean_intercept = jnp.mean(samples["intercept"]) |
| 190 | +mean_trend = mean_slope * x + mean_intercept |
| 191 | + |
| 192 | +mean_samples = {k: jnp.mean(v, axis=0) for k, v in samples.items()} |
| 193 | +with numpyro.handlers.substitute(data=mean_samples): |
| 194 | + p_posterior_mean = register_parameters(posterior) |
| 195 | + |
| 196 | +residuals_mean = y - mean_trend |
| 197 | +D_resid_mean = gpx.Dataset(X=x, y=residuals_mean) |
| 198 | +latent_dist = p_posterior_mean.predict(x, train_data=D_resid_mean) |
| 199 | +pred_mean = latent_dist.mean |
| 200 | +pred_std = latent_dist.stddev() |
| 201 | + |
| 202 | +total_mean = mean_trend.flatten() + pred_mean.flatten() |
| 203 | +std_flat = pred_std.flatten() |
| 204 | + |
| 205 | +plt.plot(x, total_mean, "b-", label="Posterior Mean") |
| 206 | +plt.fill_between( |
| 207 | + x.flatten(), |
| 208 | + total_mean - 2 * std_flat, |
| 209 | + total_mean + 2 * std_flat, |
| 210 | + color="b", |
| 211 | + alpha=0.2, |
| 212 | + label="95% CI (GP Uncertainty)", |
| 213 | +) |
| 214 | + |
| 215 | +plt.legend() |
| 216 | +plt.show() |
0 commit comments