From 50cd502210b8a4fc995528656e144b9367bb0cf6 Mon Sep 17 00:00:00 2001 From: Neil Lawrence Date: Sat, 28 Nov 2026 07:59:33 +0000 Subject: [PATCH 1/2] Add GPy notebook comparing INLA hyperparameter integration with HMC (CIP-0015 on GPy) --- GPy/inla_vs_hmc_poisson.ipynb | 264 ++++++++++++++++++++++++++++++++++ 1 file changed, 264 insertions(+) create mode 100644 GPy/inla_vs_hmc_poisson.ipynb diff --git a/GPy/inla_vs_hmc_poisson.ipynb b/GPy/inla_vs_hmc_poisson.ipynb new file mode 100644 index 0000000..5406a0e --- /dev/null +++ b/GPy/inla_vs_hmc_poisson.ipynb @@ -0,0 +1,264 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "0", + "metadata": {}, + "source": [ + "\"Open" + ] + }, + { + "cell_type": "markdown", + "id": "1", + "metadata": {}, + "source": [ + "# INLA versus HMC on a Rue-style latent Gaussian model\n", + "\n", + "Håvard Rue and colleagues introduced INLA for *latent Gaussian models*: a Gaussian process (or Markov random field) $f$ enters a non-Gaussian likelihood, and a small number of hyperparameters $\\theta$ control the process. Their canonical examples — Tokyo rainfall, Scottish lip cancer, and the coal mining disasters series — all share this structure. INLA treats $f$ with a Laplace approximation and integrates over $\\theta$ numerically on a small design. We follow the same recipe here with `INLAHyperparameters` from CIP-0015.\n", + "\n", + "The question is whether the design-based integration over $\\theta$ agrees with a sampler that targets the *same* hyperparameter posterior. We use a series in the style of the coal mining disasters data: yearly counts $y_t \\sim \\text{Poisson}(\\exp f(t))$ over 112 years, with a rate that drops abruptly. We simulate it rather than load the historical series, so that we know the truth. The latent function has a Matérn-3/2 prior, a rough process that suits a sharp change, with log-Gaussian priors on its variance and lengthscale.\n", + "\n", + "Two things differ from the earlier `inla_vs_hmc.ipynb` (in `cip/cip0015` of the GPy repository), which used Bernoulli data with an RBF kernel. Here the likelihood is Poisson and the truth is known, so we can also ask how the latent-rate posterior compares with the generating rate. We also report cost.\n", + "\n", + "As before, both methods share the Laplace marginal likelihood. HMC samples $\\theta$ under it, so any disagreement comes from the integration over $\\theta$, not from the Laplace approximation of $f$." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2", + "metadata": {}, + "outputs": [], + "source": [ + "try:\n", + " from GPy.inference.hyperparameters import INLAHyperparameters\n", + "except ImportError:\n", + " # INLAHyperparameters is on GPy main (CIP-0015) and may not be in the latest PyPI release.\n", + " import subprocess\n", + " import sys\n", + " subprocess.check_call(\n", + " [sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"GPy[plotting] @ git+https://github.com/SheffieldML/GPy.git@main\"]\n", + " )\n", + " from GPy.inference.hyperparameters import INLAHyperparameters" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3", + "metadata": {}, + "outputs": [], + "source": [ + "import time\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import GPy\n", + "from GPy.inference.hyperparameters import INLAHyperparameters\n", + "\n", + "rng = np.random.default_rng(3)\n", + "years = np.arange(1851, 1963)\n", + "true_rate = 0.9 + 2.2 / (1 + np.exp((years - 1890) / 4.0)) # abrupt drop around 1890\n", + "Y = rng.poisson(true_rate)[:, None].astype(float)\n", + "X = ((years - 1906.5) / 32.0)[:, None] # standardised time\n", + "\n", + "kern = GPy.kern.Matern32(1)\n", + "kern.variance.set_prior(GPy.priors.LogGaussian(0.0, 1.0), warning=False)\n", + "kern.lengthscale.set_prior(GPy.priors.LogGaussian(0.0, 1.0), warning=False)\n", + "m = GPy.core.GP(X, Y, kernel=kern, likelihood=GPy.likelihoods.Poisson(),\n", + " inference_method=GPy.inference.latent_function_inference.Laplace())\n", + "\n", + "Xs = np.linspace(X.min(), X.max(), 150)[:, None]\n", + "years_s = Xs[:, 0] * 32.0 + 1906.5\n", + "true_s = 0.9 + 2.2 / (1 + np.exp((years_s - 1890) / 4.0))\n", + "\n", + "plt.figure(figsize=(8, 3))\n", + "plt.bar(years, Y[:, 0], color=\"0.75\", label=\"counts\")\n", + "plt.plot(years_s, true_s, \"k\", label=\"true rate\")\n", + "plt.legend(); plt.xlabel(\"year\"); plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "4", + "metadata": {}, + "source": [ + "## INLA-style fit\n", + "\n", + "With two hyperparameters `auto` chooses a grid design." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5", + "metadata": {}, + "outputs": [], + "source": [ + "t0 = time.time()\n", + "inla = INLAHyperparameters(m).fit()\n", + "t_inla = time.time() - t0\n", + "names = list(inla.hyperparameter_summary())\n", + "print(f\"design={inla.design_used}, points={len(inla.weights)}, time={t_inla:.1f}s\")\n", + "print(\"MAP:\", dict(zip(m.parameter_names_flat(), np.round(m.unfixed_param_array, 3))))\n", + "mu_map, var_map = m.predict_noiseless(Xs)\n", + "mu_i, var_i = inla.predict_noiseless(Xs)" + ] + }, + { + "cell_type": "markdown", + "id": "6", + "metadata": {}, + "source": [ + "## HMC over the hyperparameters\n", + "\n", + "The sampler starts at the mode with the Hessian as mass matrix. We discard the first 100 draws." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7", + "metadata": {}, + "outputs": [], + "source": [ + "np.random.seed(0)\n", + "u_star = inla.u_star.copy()\n", + "hmc = GPy.inference.mcmc.HMC(m, M=inla.hessian, stepsize=0.4)\n", + "t0 = time.time()\n", + "S = hmc.sample(num_samples=1500, hmc_iters=8)[100:]\n", + "t_hmc = time.time() - t0\n", + "accept = np.mean(np.any(np.diff(S, axis=0) != 0, axis=1))\n", + "print(f\"HMC: {len(S)} draws kept, acceptance={accept:.2f}, time={t_hmc:.0f}s\")\n", + "m.optimizer_array = u_star" + ] + }, + { + "cell_type": "markdown", + "id": "8", + "metadata": {}, + "source": [ + "## Hyperparameter marginals\n", + "\n", + "We compare the HMC histogram with the weighted INLA design points, and report posterior means and standard deviations." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9", + "metadata": {}, + "outputs": [], + "source": [ + "vals = []\n", + "for u in inla.U:\n", + " m.optimizer_array = u\n", + " vals.append(np.array(m.unfixed_param_array, dtype=float))\n", + "m.optimizer_array = u_star\n", + "vals = np.array(vals)\n", + "w = inla.weights\n", + "\n", + "fig, axes = plt.subplots(1, 3, figsize=(14, 3.2))\n", + "for j in range(2):\n", + " ax = axes[j]\n", + " bins = np.geomspace(min(S[:, j].min(), vals[:, j].min()), max(S[:, j].max(), vals[:, j].max()), 30)\n", + " ax.hist(S[:, j], bins=bins, density=True, alpha=0.5, label=\"HMC\")\n", + " ax.hist(vals[:, j], bins=bins, weights=w, density=True, histtype=\"step\", lw=2, label=\"INLA design\")\n", + " ax.axvline(m.unfixed_param_array[j], color=\"k\", ls=\":\", label=\"MAP\")\n", + " ax.set_xscale(\"log\"); ax.set_title(names[j])\n", + "axes[0].legend()\n", + "axes[2].plot(np.log(S[:, 0]), np.log(S[:, 1]), \".\", alpha=0.2, label=\"HMC\")\n", + "axes[2].scatter(np.log(vals[:, 0]), np.log(vals[:, 1]), s=300 * w / w.max(), c=\"C1\", alpha=0.7, label=\"INLA design (size = weight)\")\n", + "axes[2].set_xlabel(\"log variance\"); axes[2].set_ylabel(\"log lengthscale\"); axes[2].legend()\n", + "plt.tight_layout(); plt.show()\n", + "\n", + "for j, n in enumerate(names):\n", + " mi = np.sum(w * vals[:, j]); si = np.sqrt(np.sum(w * (vals[:, j] - mi) ** 2))\n", + " print(f\"{n:24s} INLA mean {mi:.3f} sd {si:.3f} HMC mean {S[:, j].mean():.3f} sd {S[:, j].std():.3f}\")" + ] + }, + { + "cell_type": "markdown", + "id": "10", + "metadata": {}, + "source": [ + "## Posterior for the log-rate\n", + "\n", + "For HMC we average Laplace predictions over 250 thinned draws and combine variances with the law of total variance, as the INLA design does. The MAP plug-in ignores hyperparameter uncertainty." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "11", + "metadata": {}, + "outputs": [], + "source": [ + "idx = np.linspace(0, len(S) - 1, 250).astype(int)\n", + "mus, vs = [], []\n", + "for k in idx:\n", + " m.kern.variance = S[k, 0]; m.kern.lengthscale = S[k, 1]\n", + " a, b = m.predict_noiseless(Xs)\n", + " mus.append(a); vs.append(b)\n", + "m.optimizer_array = u_star\n", + "mus, vs = np.array(mus), np.array(vs)\n", + "mu_h = mus.mean(0)\n", + "var_h = (vs + mus**2).mean(0) - mu_h**2\n", + "\n", + "fig, axes = plt.subplots(1, 2, figsize=(13, 3.6))\n", + "ax = axes[0]\n", + "for mu, v, lab, col in [(mu_map, var_map, \"MAP\", \"k\"), (mu_i, var_i, \"INLA design\", \"C1\"), (mu_h, var_h, \"HMC\", \"C0\")]:\n", + " mu, v = mu.ravel(), v.ravel()\n", + " ax.plot(years_s, np.exp(mu), color=col, label=lab, ls=\":\" if lab == \"MAP\" else \"-\")\n", + " ax.fill_between(years_s, np.exp(mu - 2 * np.sqrt(v)), np.exp(mu + 2 * np.sqrt(v)), color=col, alpha=0.12)\n", + "ax.plot(years_s, true_s, \"r--\", label=\"truth\"); ax.plot(years, Y, \"k.\", alpha=0.3)\n", + "ax.set_title(\"rate exp(f) with 2 sd bands on f\"); ax.legend()\n", + "axes[1].plot(years_s, np.sqrt(var_map).ravel(), \"k:\", label=\"MAP\"); axes[1].plot(years_s, np.sqrt(var_i).ravel(), \"C1\", label=\"INLA design\"); axes[1].plot(years_s, np.sqrt(var_h).ravel(), \"C0--\", label=\"HMC\")\n", + "axes[1].set_title(\"posterior sd of f\"); axes[1].legend()\n", + "plt.tight_layout(); plt.show()\n", + "\n", + "worst = lambda a, b: float(np.abs(a - b).max())\n", + "print(f\"max |INLA - HMC|: mean of f {worst(mu_i, mu_h):.3f}, sd of f {worst(np.sqrt(var_i), np.sqrt(var_h)):.3f}\")\n", + "print(f\"max |MAP - HMC|: mean of f {worst(mu_map, mu_h):.3f}, sd of f {worst(np.sqrt(var_map), np.sqrt(var_h)):.3f}\")\n", + "print(f\"cost: INLA {t_inla:.1f}s ({len(w)} Laplace fits plus Hessian), HMC {t_hmc:.0f}s\")" + ] + }, + { + "cell_type": "markdown", + "id": "12", + "metadata": {}, + "source": [ + "## Reading the result\n", + "\n", + "On this problem the INLA design and HMC agree on the latent posterior to about 0.003 in the mean and standard deviation of $f$, against about 0.025 for the MAP plug-in. So the design recovers most of what the plug-in misses, at under a second against roughly a minute for HMC. The difference from the plug-in is small in absolute terms because 112 counts pin the rate down well; hyperparameter uncertainty matters more with less data.\n", + "\n", + "The hyperparameter marginals agree less closely than the predictions. The lengthscale matches well, but the variance standard deviation is about 0.81 under the design and 0.95 under HMC. The variance posterior has a heavy right tail, and the grid cutoff truncates it. The same effect is documented in CIP-0015, where a wider `grid_cutoff` or the importance design recovers the tail. The predictions are insensitive to it here because the tail has little posterior mass.\n", + "\n", + "This is where INLA is strongest: two or three hyperparameters and a moderately sized latent field. See `cip/cip0015/check_high_dim.py` and CIP-0015 in the [GPy repository](https://github.com/SheffieldML/GPy) for higher dimensions, where the grid becomes expensive and the importance design takes over.\n", + "\n", + "Limits of this comparison. Both methods share the Laplace approximation to $p(y\\mid\\theta)$, so neither tells us whether Laplace is accurate for these counts. Rue et al. address that with a simplified Laplace correction to the marginals of $f$, which `INLAHyperparameters` does not implement. A full test would compare against MCMC over $(f,\\theta)$ jointly, for example elliptical slice sampling for $f$ within a hyperparameter sampler." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.7" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} From 933d367138cac4ff0f195de9a0f42b8207c1cb7c Mon Sep 17 00:00:00 2001 From: Neil Lawrence Date: Sat, 28 Nov 2026 19:35:46 +0000 Subject: [PATCH 2/2] Shorten HMC run so the INLA notebook executes within the CI timeout; soften quoted numbers --- GPy/inla_vs_hmc_poisson.ipynb | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/GPy/inla_vs_hmc_poisson.ipynb b/GPy/inla_vs_hmc_poisson.ipynb index 5406a0e..5389a8c 100644 --- a/GPy/inla_vs_hmc_poisson.ipynb +++ b/GPy/inla_vs_hmc_poisson.ipynb @@ -15,9 +15,9 @@ "source": [ "# INLA versus HMC on a Rue-style latent Gaussian model\n", "\n", - "Håvard Rue and colleagues introduced INLA for *latent Gaussian models*: a Gaussian process (or Markov random field) $f$ enters a non-Gaussian likelihood, and a small number of hyperparameters $\\theta$ control the process. Their canonical examples — Tokyo rainfall, Scottish lip cancer, and the coal mining disasters series — all share this structure. INLA treats $f$ with a Laplace approximation and integrates over $\\theta$ numerically on a small design. We follow the same recipe here with `INLAHyperparameters` from CIP-0015.\n", + "H\u00e5vard Rue and colleagues introduced INLA for *latent Gaussian models*: a Gaussian process (or Markov random field) $f$ enters a non-Gaussian likelihood, and a small number of hyperparameters $\\theta$ control the process. Their canonical examples \u2014 Tokyo rainfall, Scottish lip cancer, and the coal mining disasters series \u2014 all share this structure. INLA treats $f$ with a Laplace approximation and integrates over $\\theta$ numerically on a small design. We follow the same recipe here with `INLAHyperparameters` from CIP-0015.\n", "\n", - "The question is whether the design-based integration over $\\theta$ agrees with a sampler that targets the *same* hyperparameter posterior. We use a series in the style of the coal mining disasters data: yearly counts $y_t \\sim \\text{Poisson}(\\exp f(t))$ over 112 years, with a rate that drops abruptly. We simulate it rather than load the historical series, so that we know the truth. The latent function has a Matérn-3/2 prior, a rough process that suits a sharp change, with log-Gaussian priors on its variance and lengthscale.\n", + "The question is whether the design-based integration over $\\theta$ agrees with a sampler that targets the *same* hyperparameter posterior. We use a series in the style of the coal mining disasters data: yearly counts $y_t \\sim \\text{Poisson}(\\exp f(t))$ over 112 years, with a rate that drops abruptly. We simulate it rather than load the historical series, so that we know the truth. The latent function has a Mat\u00e9rn-3/2 prior, a rough process that suits a sharp change, with log-Gaussian priors on its variance and lengthscale.\n", "\n", "Two things differ from the earlier `inla_vs_hmc.ipynb` (in `cip/cip0015` of the GPy repository), which used Bernoulli data with an RBF kernel. Here the likelihood is Poisson and the truth is known, so we can also ask how the latent-rate posterior compares with the generating rate. We also report cost.\n", "\n", @@ -112,7 +112,7 @@ "source": [ "## HMC over the hyperparameters\n", "\n", - "The sampler starts at the mode with the Hessian as mass matrix. We discard the first 100 draws." + "The sampler starts at the mode with the Hessian as mass matrix. We discard the first 50 draws. The run is short so that the notebook executes quickly in CI; lengthen it for tighter HMC estimates." ] }, { @@ -126,7 +126,7 @@ "u_star = inla.u_star.copy()\n", "hmc = GPy.inference.mcmc.HMC(m, M=inla.hessian, stepsize=0.4)\n", "t0 = time.time()\n", - "S = hmc.sample(num_samples=1500, hmc_iters=8)[100:]\n", + "S = hmc.sample(num_samples=450, hmc_iters=6)[50:]\n", "t_hmc = time.time() - t0\n", "accept = np.mean(np.any(np.diff(S, axis=0) != 0, axis=1))\n", "print(f\"HMC: {len(S)} draws kept, acceptance={accept:.2f}, time={t_hmc:.0f}s\")\n", @@ -184,7 +184,7 @@ "source": [ "## Posterior for the log-rate\n", "\n", - "For HMC we average Laplace predictions over 250 thinned draws and combine variances with the law of total variance, as the INLA design does. The MAP plug-in ignores hyperparameter uncertainty." + "For HMC we average Laplace predictions over 100 thinned draws and combine variances with the law of total variance, as the INLA design does. The MAP plug-in ignores hyperparameter uncertainty." ] }, { @@ -194,7 +194,7 @@ "metadata": {}, "outputs": [], "source": [ - "idx = np.linspace(0, len(S) - 1, 250).astype(int)\n", + "idx = np.linspace(0, len(S) - 1, 100).astype(int)\n", "mus, vs = [], []\n", "for k in idx:\n", " m.kern.variance = S[k, 0]; m.kern.lengthscale = S[k, 1]\n", @@ -230,9 +230,9 @@ "source": [ "## Reading the result\n", "\n", - "On this problem the INLA design and HMC agree on the latent posterior to about 0.003 in the mean and standard deviation of $f$, against about 0.025 for the MAP plug-in. So the design recovers most of what the plug-in misses, at under a second against roughly a minute for HMC. The difference from the plug-in is small in absolute terms because 112 counts pin the rate down well; hyperparameter uncertainty matters more with less data.\n", + "Compare the two `max |...|` lines in the last block. The INLA design should sit close to HMC, and closer than the MAP plug-in, at a small fraction of the cost. In our runs the INLA-to-HMC difference in the mean and standard deviation of $f$ was under 0.01, against about 0.02 for the MAP plug-in, with INLA taking about a second and HMC tens of seconds. The difference from the plug-in is small in absolute terms because 112 counts pin the rate down well; hyperparameter uncertainty matters more with less data.\n", "\n", - "The hyperparameter marginals agree less closely than the predictions. The lengthscale matches well, but the variance standard deviation is about 0.81 under the design and 0.95 under HMC. The variance posterior has a heavy right tail, and the grid cutoff truncates it. The same effect is documented in CIP-0015, where a wider `grid_cutoff` or the importance design recovers the tail. The predictions are insensitive to it here because the tail has little posterior mass.\n", + "The hyperparameter marginals agree less closely than the predictions, and the HMC chain here is deliberately short, so its own Monte Carlo error is of the same order as the gap. The lengthscale marginals match well. The variance posterior has a heavy right tail, which a finite grid truncates; CIP-0015 documents this, and a wider `grid_cutoff` or the importance design recovers the tail. The predictions are insensitive to it because the tail carries little posterior mass. To tighten the HMC reference, raise `num_samples` in the sampling cell.\n", "\n", "This is where INLA is strongest: two or three hyperparameters and a moderately sized latent field. See `cip/cip0015/check_high_dim.py` and CIP-0015 in the [GPy repository](https://github.com/SheffieldML/GPy) for higher dimensions, where the grid becomes expensive and the importance design takes over.\n", "\n", @@ -261,4 +261,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file