Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Training a Markov GP — maximum likelihood, NUTS, variational inference, and what the data can tell you

Open In Colab

MarkovGPPrior.log_marginal(y, noise_var) is the Kalman-filter marginal likelihood of a GP with a Gaussian likelihood. It is differentiable in every kernel hyperparameter through the SDE construction and the lax.scan-based filter, and it costs O(N d3)\mathcal{O}(N\,d^3) per evaluation. That makes three ways of setting the hyperparameters θ=(σ2,ℓ,σn2)\boldsymbol{\theta} = (\sigma^2, \ell, \sigma_n^2) cheap:

  1. a point estimate: maximise log⁡p(y∣θ)\log p(\mathbf{y} \mid \boldsymbol{\theta}) with L-BFGS (type-II maximum likelihood);

  2. the full posterior p(θ∣y)p(\boldsymbol{\theta} \mid \mathbf{y}) with NUTS, through markov_gp_factor in a NumPyro model;

  3. an approximate posterior with stochastic variational inference, mean-field and full-rank.

The last section asks what any of them can recover: which hyperparameters a record actually constrains, and how record length, sampling density and gaps change that, framed for geoscience time series.

Setup

Detect Colab and install pyrox-gp[colab] (which pulls in matplotlib and watermark) and pyrox-ssm only when running there.

Python implementation: CPython
Python version       : 3.13.12
IPython version      : 9.13.0

jax       : 0.10.2
equinox   : 0.13.8
numpyro   : 0.21.0
pyrox     : 0.2.1
matplotlib: 3.10.9

Compiler    : Clang 21.1.4 
OS          : Linux
Release     : 6.8.0-1044-azure
Machine     : x86_64
Processor   : x86_64
CPU cores   : 16
Architecture: 64bit

1. Synthetic data

A noisy mixture of two sinusoids on an irregular time grid of N=60N = 60 points over t∈[0,8]t \in [0, 8], fitted below with a Matern-3/2 SDE prior. The signal is not a draw from that prior, so no hyperparameter value is “true” here; section 4 uses data drawn from a known Matern-3/2 GP for that.

<Figure size 800x300 with 1 Axes>

2. A point estimate: type-II maximum likelihood with L-BFGS

We optimise in log-space so that σ2,ℓ,σn2>0\sigma^2, \ell, \sigma_n^2 > 0 holds automatically. The model lives in a small equinox.Module so it composes with optax.

initial NLL: 26.632
final NLL: -20.833
learned variance:    0.417
learned lengthscale: 1.461
learned noise_var:   0.0237
<Figure size 1100x340 with 2 Axes>
<Figure size 850x360 with 1 Axes>

The point estimate gives a sensible fit, but it is one value of θ\boldsymbol{\theta}: the band above treats the hyperparameters as known. The next section puts priors on them and asks how uncertain they are.

3. Bayesian hyperparameters in NumPyro

3.1 The model

markov_gp_factor adds the Kalman marginal likelihood log⁡p(y∣θ)\log p(\mathbf{y} \mid \boldsymbol{\theta}) to a NumPyro model as a factor site, with the latent function integrated out. The model therefore has only three sample sites, one per hyperparameter, and every log-density evaluation is one O(N d3)\mathcal{O}(N\,d^3) filter pass.

The priors encode what a record can and cannot inform:

  • σ2∼LogNormal(0,1)\sigma^2 \sim \mathrm{LogNormal}(0, 1): weakly informative around the data’s own scale.

  • ℓ∼InverseGamma(3,3)\ell \sim \mathrm{InverseGamma}(3, 3): mean 1.5, with almost no mass below the sampling interval (about 0.13) or above the record length (8). A lengthscale below the sampling interval is indistinguishable from noise, and one beyond the record shows no decorrelation inside it, so the likelihood is flat in both directions; the prior keeps the posterior away from those regions. The inverse-gamma’s light left tail is what does this.

  • σn2∼LogNormal(log⁡0.05,1)\sigma_n^2 \sim \mathrm{LogNormal}(\log 0.05, 1).

prior P(ell < 0.3) = 0.0028
prior P(ell > 8)   = 0.0067
site 'variance'     type=sample
site 'lengthscale'  type=sample
site 'noise_var'    type=sample
site 'y'            type=sample

3.2 MCMC with NUTS

NUTS (Hoffman & Gelman, 2014) is the right sampler here: three continuous parameters, a smooth log-density with exact gradients, and no latent function in the state because the factor has integrated it out, so there is no funnel between f\mathbf{f} and its hyperparameters to trap the sampler. Two chains of 1000 draws after 500 warm-up steps are plenty for three parameters.


                   mean       std    median      5.0%     95.0%     n_eff     r_hat
  lengthscale      1.46      0.40      1.39      0.84      2.06    851.06      1.00
    noise_var      0.04      0.01      0.03      0.02      0.05   1088.75      1.00
     variance      1.00      0.71      0.83      0.23      1.69    714.88      1.00

Number of divergences: 0

Both chains agree (R^=1.00\hat R = 1.00), the effective sample sizes are in the hundreds, and there are no divergences.

3.3 Stochastic variational inference: mean-field and full-rank

SVI fits a Gaussian q(θ;ν)q(\boldsymbol{\theta}; \boldsymbol{\nu}) in the unconstrained (log) space by maximising the ELBO. With three parameters the choice of guide is easy: AutoMultivariateNormal learns a full 3×33 \times 3 covariance at negligible cost, which matters because the posterior is correlated; AutoNormal (mean-field) is shown for contrast, because it is the default people reach for on larger models.

<Figure size 800x300 with 1 Axes>

3.4 Comparing the posteriors

The scatter plots show (log⁡σ2,log⁡ℓ)(\log \sigma^2, \log \ell) samples from each method, with the L-BFGS estimate marked; the table gives each method’s posterior standard deviation of the three log-hyperparameters.

<Figure size 1400x400 with 3 Axes>
method              sd log var  sd log ell  sd log noise
NUTS                     0.529       0.266         0.219
SVI, full-rank           0.522       0.253         0.229
SVI, mean-field          0.359       0.184         0.229

The NUTS posterior is a tilted ridge: larger variances go with longer lengthscales. Full-rank SVI reproduces both the tilt and the spread. Mean-field SVI cannot represent the correlation, so it fits an axis-aligned ellipse and understates the spread of log⁡σ2\log \sigma^2 and log⁡ℓ\log \ell, the known behaviour of mean-field variational inference (Blei, Kucukelbir & McAuliffe, 2017). The noise variance is nearly uncorrelated with the other two, so all three methods agree on it. The L-BFGS estimate sits below the low-variance edge of the posterior cloud: it maximises the likelihood alone, while the posterior adds the priors and averages along the ridge, where larger variances paired with longer lengthscales fit almost as well.

Hyperparameter uncertainty propagates into predictions. Below, the NUTS posterior predictive averages the Kalman posterior over 200 posterior draws of θ\boldsymbol{\theta} (one jax.vmap over condition and predict), and is compared with the plug-in band from the L-BFGS estimate.

<Figure size 1000x380 with 1 Axes>

Inside the record the two bands nearly coincide: the data pin the function down wherever they are dense. Past the last observation the forecast band depends on σ2\sigma^2 and ℓ\ell directly, so averaging over their uncertainty widens it; that is where a plug-in estimate is most overconfident.

4. What a record can tell you about its hyperparameters

4.1 The variance–lengthscale ridge

The tilted ridge in §3.4 is not an accident of this data set. For a Matérn-ν\nu process observed more and more densely on a fixed interval (infill sampling), σ2\sigma^2 and ℓ\ell cannot both be estimated consistently: only the combination σ2/ℓ2ν\sigma^2 / \ell^{2\nu} can (Zhang, 2004), which for Matern-3/2 is σ2/ℓ3\sigma^2 / \ell^3. Sampling the same stretch more often sharpens that combination and nothing else. Only a longer record, more decorrelation lengths, separates σ2\sigma^2 from ℓ\ell.

For a geoscience series the lengthscale is a decorrelation time: the memory of a sea-surface temperature anomaly, the persistence of a soil-moisture anomaly, the duration of a drought spell. Estimating it needs a record that spans many such times, which is often what a geophysical record does not have.

4.2 Record length, sampling density and gaps

To make this concrete we draw data from a known Matern-3/2 GP (σ2=1\sigma^2 = 1, ℓ=1\ell = 1, noise variance 0.01) and map the log marginal likelihood over (ℓ,σ2)(\ell, \sigma^2) with the noise variance held at its true value, for four records:

  1. a short record: T=10T = 10 (ten decorrelation times), N=100N = 100, every tenth point of record 2;

  2. the same stretch of the same realisation sampled ten times more densely: T=10T = 10, N=1000N = 1000 (infill, like moving from daily to hourly sampling), so records 1 and 2 differ only in sampling density;

  3. a ten-times longer record at the original density: T=100T = 100, N=1000N = 1000;

  4. the long record with every other block of 10 time units missing, passed to the filter through mask= (like a sensor that is down every other season): T=100T = 100, 501 observed.

The surfaces use jax.vmap over a grid and one jax.jit, so each costs a second or two.

record                             observed   ell where within 2 of max
T = 10, N = 100                         100             1.00 – 2.76
T = 10, N = 1000 (infill)              1000             0.91 – 2.00
T = 100, N = 1000                      1000             0.91 – 1.20
T = 100, half in gaps (501 obs)         501             0.91 – 1.32
<Figure size 1600x420 with 4 Axes>

Three things stand out.

  • Every surface is a ridge along σ2/ℓ3=const\sigma^2 / \ell^3 = \text{const}, the red line through the truth, as Zhang’s result predicts. Along the ridge the likelihood barely changes, so σ2\sigma^2 and ℓ\ell separately are poorly determined even when their combination is sharp.

  • Infill helps, but far less than record length. On the same stretch of the same realisation, ten times more observations thin the ridge and trim it: the range of ℓ\ell within two log-units of the maximum goes from 1.00–2.76 to 0.91–2.00. It stays a long ridge spanning a factor of two, because denser samples of the same ten decorrelation times mostly add information about short-lag behaviour, which pins down σ2/ℓ3\sigma^2 / \ell^3 rather than ℓ\ell itself.

  • Record length does. The ten-times longer record shrinks the ridge to a small ellipse around the truth. Even with half of it missing, its 501 observations constrain ℓ\ell far better than the 1000 observations packed into the short record, because what informs ℓ\ell is the number of decorrelation times observed, not the number of points. Masking the gaps keeps every observed step and adds no imputed ones.

4.3 Practical guidance for geoscience records

  1. Count decorrelation times, not points. Compare the record length with the plausible range of ℓ\ell before trusting a fitted lengthscale. In the experiment above, ten decorrelation times left every ℓ\ell from 1.0 to 2.8 within two log-units of the maximum with 100 points, and from 0.9 to 2.0 with 1000.

  2. Report what is identified. For a Matérn-ν\nu fit, σ2/ℓ2ν\sigma^2 / \ell^{2\nu} is well determined and σ2\sigma^2 and ℓ\ell separately may not be; interpret them together, and prefer predictions and their uncertainty over individual hyperparameter values.

  3. Use priors that encode the record. Keep ℓ\ell between the sampling interval and the record length, as the inverse-gamma prior in §3.1 does. Penalised-complexity priors for the Matérn range and variance (Fuglstad et al., 2019) are a principled default; pyrox-lgm implements them for its latent Gaussian models.

  4. Propagate hyperparameter uncertainty where it matters. Plug-in estimates are fine for interpolation inside a dense record and overconfident for forecasts and long gaps. Use NUTS when the posterior is small, as here; use full-rank rather than mean-field VI when it is not.

  5. Handle gaps with mask=. Missing seasons or outages need no imputation, and as §4.2 shows, a long record with gaps can be worth more than a short complete one.

Summary

  • MarkovGPPrior.log_marginal is differentiable and linear in NN, so type-II maximum likelihood (L-BFGS), NUTS and SVI over the kernel hyperparameters are all cheap; markov_gp_factor puts it in a NumPyro model with the latent function integrated out.

  • The hyperparameter posterior is a correlated ridge in (log⁡σ2,log⁡ℓ)(\log \sigma^2, \log \ell). NUTS and full-rank SVI capture it; mean-field SVI understates its spread.

  • Only σ2/ℓ2ν\sigma^2 / \ell^{2\nu} is fixed by dense sampling of a fixed record; separating σ2\sigma^2 from ℓ\ell takes a record many decorrelation times long, and a long record with gaps beats a short dense one.

For non-Gaussian likelihoods, plug a MarkovGPPrior into one of the strategies in the companion non-Gaussian Markov GP notebook; LaplaceMarkovInference’s log_marginal_approx approximates the evidence and can play the role of the loss.

References.

  1. Blei, D. M., Kucukelbir, A. & McAuliffe, J. D. (2017). Variational inference: a review for statisticians. JASA 112(518), 859–877.

  2. Fuglstad, G.-A., Simpson, D., Lindgren, F. & Rue, H. (2019). Constructing priors that penalize the complexity of Gaussian random fields. JASA 114(525), 445–452.

  3. Hoffman, M. D. & Gelman, A. (2014). The No-U-Turn sampler: adaptively setting path lengths in Hamiltonian Monte Carlo. JMLR 15, 1593–1623.

  4. Zhang, H. (2004). Inconsistent estimation and asymptotically equal interpolations in model-based geostatistics. JASA 99(465), 250–261.