Skip to content

Commit e6196fa

Browse files
seabbs-botseabbs
andauthored
docs: streamline the Gaussian-process case study (#235) (#237)
Co-authored-by: Sam Abbott <contact@samabbott.co.uk>
1 parent 740a66c commit e6196fa

1 file changed

Lines changed: 69 additions & 115 deletions

File tree

‎docs/src/case-studies/gaussian-process.md‎

Lines changed: 69 additions & 115 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,25 @@
11
# [A Gaussian-process latent process](@id case-study-gp)
22

3-
Any latent process that implements `as_turing_model(model, n)` and returns a
4-
length-`n` path can drive an infection model. This case study uses a **Gaussian
5-
process** (GP) — a prior over functions, and so a flexible choice for a smoothly
6-
varying quantity such as ``\log R_t``: rather than assume a parametric form we
7-
let the data choose the shape, subject only to a smoothness assumption from the
8-
kernel.
9-
10-
An exact GP over ``n`` points needs an ``n \times n`` covariance factorisation
11-
that costs ``O(n^3)`` *at every leapfrog step* of the sampler. The package ships
12-
two GP latent models built on the same ecosystem kernels:
13-
14-
- [`ExactGP`](@ref) — the exact GP. Accurate, but ``O(n^3)`` per evaluation, so
15-
best for short series. It is the accuracy reference.
16-
- [`HilbertSpaceGP`](@ref) — the Hilbert-space basis-function approximation of
3+
Any latent process that implements `as_turing_model(model, n)` and returns a length-`n` path can drive an infection model.
4+
A Gaussian process (GP) is a prior over functions, so it lets the data pick the shape of a smoothly varying quantity such as ``\log R_t`` subject only to the smoothness the kernel implies.
5+
Reach for one when the roughness of the path should be learned rather than fixed in advance.
6+
[`AR`](@ref) and [`RandomWalk`](@ref) are cheaper and usually enough for local smoothing.
7+
8+
The package ships two GP latent models built on the same
9+
[KernelFunctions.jl](https://juliagaussianprocesses.github.io/KernelFunctions.jl/)
10+
kernels.
11+
12+
- [`ExactGP`](@ref) forms the full ``n \times n`` covariance and factorises it.
13+
Accurate, but ``O(n^3)`` per log-density evaluation, so use it on short
14+
series and as the accuracy reference.
15+
- [`HilbertSpaceGP`](@ref) is the basis-function approximation of
1716
[riutortmayol2023practical](@citet), building on [solin2020hilbert](@citep).
1817
A fixed basis makes each evaluation an ``n \times m`` matrix–vector product,
19-
which is fast and stable under gradient-based sampling.
20-
21-
We build both, check them against the GP ecosystem, then fit both to the same
22-
simulated data and compare accuracy and speed.
18+
so use it for anything longer.
2319

2420
## Two GP latent models
2521

26-
Both are latent models in their own right: give one a series length and it
27-
returns a length-`n` draw, like any other component.
22+
Both are latent models in their own right, so giving one a series length returns a length-`n` draw like any other component.
2823

2924
```@example gp
3025
using ComposableTuringIDModels, Distributions, Random
@@ -36,42 +31,20 @@ exact = ExactGP()
3631
exact = length(as_turing_model(exact, 60)()))
3732
```
3833

39-
Both sample a length scale ``\ell`` and marginal standard deviation ``\sigma``.
40-
[`HilbertSpaceGP`](@ref) then draws ``m`` basis weights ``\beta`` and forms the
41-
path from the fixed basis; [`ExactGP`](@ref) draws ``n`` non-centred weights
42-
``z`` and pushes them through the Cholesky factor of the full covariance. Both
43-
parameterisations are non-centred, which NUTS handles well.
44-
45-
They differ in how much of their work depends on the sampled parameters. The
46-
Hilbert-space basis is set by the series length, the number of basis functions
47-
and the boundary factor alone, so [`as_turing_model`](@ref) builds it before
48-
returning the model and captures it: the `@model` body never sees it, and one
49-
``n \times m`` matrix–vector product is all that is differentiated. The exact
50-
GP's covariance and its Cholesky factor depend on ``\ell`` and ``\sigma``, so
51-
both are rebuilt *and* differentiated on every evaluation. That is where the
52-
timing gap below comes from.
53-
54-
Composed into a [`Renewal`](@ref), the enclosing `@model` reconstructs its
55-
submodels on every evaluation, so the basis is rebuilt inside the traced call.
56-
It still depends on no sampled parameter, but it is executed and taped along
57-
with everything else, so it is not free. That cost is measured below.
58-
59-
## The kernel and the GP ecosystem
60-
61-
The kernels are
62-
[KernelFunctions.jl](https://juliagaussianprocesses.github.io/KernelFunctions.jl/)
63-
types — the ones
64-
[AbstractGPs.jl](https://juliagaussianprocesses.github.io/AbstractGPs.jl/) builds
65-
exact GPs from. A kernel enters [`ExactGP`](@ref) through its Gram matrix and
66-
[`HilbertSpaceGP`](@ref) only through its spectral density, so either model takes
67-
`SqExponentialKernel` (the default), `Matern32Kernel` or `Matern52Kernel`.
68-
[`ExactGP`](@ref) forms that Gram matrix itself rather than wrapping an
69-
AbstractGPs `GP`, because it needs the factor inside a Turing model where the
70-
hyperparameters are sampled; the kernels are shared either way.
71-
72-
Both models are linear in a vector of standard-normal weights, so unit vectors at
73-
fixed hyperparameters trace out that map and the Gram matrix of the result is the
74-
model's implied prior covariance. Against AbstractGPs' own:
34+
Both sample a length scale ``\ell`` and a marginal standard deviation ``\sigma``.
35+
[`HilbertSpaceGP`](@ref) then draws ``m`` standard-normal basis weights ``\beta``, and [`ExactGP`](@ref) draws ``n`` weights ``z`` that it pushes through the Cholesky factor of the full covariance.
36+
Both are non-centred parameterisations, which NUTS handles well.
37+
38+
The basis depends only on `n`, `m` and `c`, so [`as_turing_model`](@ref) builds it before returning the model and only the matrix–vector product is differentiated.
39+
The exact GP rebuilds and differentiates its covariance and Cholesky factor on every evaluation, which is where the timing gap below comes from.
40+
41+
## Kernels and a check against AbstractGPs
42+
43+
A kernel enters [`ExactGP`](@ref) through its Gram matrix and [`HilbertSpaceGP`](@ref) only through its spectral density, so either model takes `SqExponentialKernel` (the default), `Matern32Kernel` or `Matern52Kernel`, in order from smoothest paths to roughest.
44+
45+
Both models are linear in a vector of standard-normal weights, so unit vectors at fixed hyperparameters trace out that map and the Gram matrix of the result is the model's implied prior covariance.
46+
The check below compares it against the same kernel in
47+
[AbstractGPs.jl](https://juliagaussianprocesses.github.io/AbstractGPs.jl/).
7548

7649
```@example gp
7750
using LinearAlgebra
@@ -96,31 +69,38 @@ err = (exact = relerr(K_exact), hsgp = relerr(K_hsgp))
9669
map(e -> round(e, sigdigits = 2), err)
9770
```
9871

99-
The exact GP matches to the jitter it adds for a stable Cholesky factor, and the
100-
basis to two parts in ten thousand. That accuracy is not uniform in ``\ell``: the
101-
basis cannot resolve wiggles finer than ``2L/m``, so a short length scale needs a
102-
larger `m`, and a long one feels the ``[-L, L]`` boundary and needs a wider `c`.
72+
The exact GP matches to the jitter it adds for a stable Cholesky factor, and the basis to two parts in ten thousand.
73+
74+
That accuracy is not uniform in ``\ell``, and the two knobs fail at opposite ends.
75+
The basis cannot resolve wiggles finer than ``2L/m``, so a short length scale needs a larger `m`.
76+
A long one instead feels the ``[-L, L]`` boundary and needs a wider `c`, which more basis functions will not fix.
77+
78+
```@example gp
79+
function hsgp_relerr(ℓ, m)
80+
K_true = gp_cov(GP(σ0^2 * with_lengthscale(SqExponentialKernel(), ℓ))(
81+
standardised_index(n0)))
82+
K = gram([fix(as_turing_model(HilbertSpaceGP(m = m), n0),
83+
(ℓ = ℓ, σ = σ0, β = unit(m, j)))() for j in 1:m])
84+
return norm(K - K_true) / norm(K_true)
85+
end
86+
87+
ℓs = [0.1, 0.2, 0.4, 0.8]
88+
e20, e60 = hsgp_relerr.(ℓs, 20), hsgp_relerr.(ℓs, 60)
89+
@assert e60[1] < e20[1] / 100 && e60[4] ≈ e20[4] # m fixes short ℓ, not long
90+
(ℓ = ℓs, m20 = round.(e20, sigdigits = 2), m60 = round.(e60, sigdigits = 2))
91+
```
92+
93+
The default ``\ell`` prior puts about a third of its mass below 0.2, so a fit that settles on a short length scale wants a larger `m` than the default 20.
94+
Raising `m` does nothing at ``\ell = 0.8``, where the boundary factor `c` sets the floor.
10395

10496
## Simulate from an exact GP
10597

106-
To use a GP as the reproduction number we hand it to a [`Renewal`](@ref)
107-
infection model as its `rt` latent process. The generation interval is a
108-
``\mathrm{Gamma}(6.5, 0.62)`` serial interval discretised by [`Renewal`](@ref),
109-
and reported cases are overdispersed counts via [`NegativeBinomialError`](@ref).
110-
111-
We simulate a ground truth by driving the renewal model with an [`ExactGP`](@ref)
112-
whose hyperparameters are *fixed* to a known length scale, then drawing one
113-
trajectory. Passing `missing` observations makes the composed model a prior
114-
simulator; `fix` pins the GP hyperparameters and a single seeded draw gives the
115-
observed data — no rejection loop. The returned quantities include the reported
116-
cases `generated_y_t`, the latent infections `I_t`, and the GP path
117-
`Z_t = \log R_t`.
118-
119-
The epidemic is seeded at around fifty infections rather than a handful, which
120-
matters for what the page can claim. With only a few cases a day the first
121-
fortnight of counts would carry almost no information about ``R_t``, both fits
122-
would fall back on the prior there, and a comparison against the truth would
123-
mostly measure the seed size rather than either model.
98+
Handing a GP to a [`Renewal`](@ref) as its `rt` process makes it the reproduction number.
99+
The generation interval is a ``\mathrm{Gamma}(6.5, 0.62)`` serial interval discretised by [`Renewal`](@ref), and reported cases are overdispersed counts from [`NegativeBinomialError`](@ref).
100+
101+
Passing `missing` observations makes the composed model a prior simulator, `fix` pins the GP hyperparameters to a known length scale, and one seeded draw gives the data.
102+
The returned quantities include the reported cases `generated_y_t` and the GP path `Z_t`, which is ``\log R_t``.
103+
Seeding at around fifty infections keeps the early counts informative about ``R_t``; from a handful, both fits would sit on the prior for the first fortnight and the comparison would measure the seed size.
124104

125105
```@example gp
126106
si = Gamma(6.5, 0.62)
@@ -139,9 +119,7 @@ Z_true = sim.Z_t
139119
Rt_range = round.(extrema(exp.(Z_true)), digits = 2))
140120
```
141121

142-
The simulated ``R_t`` path starts around two, dips, peaks again around day 40 and
143-
falls through one near day 50, so the epidemic grows, turns over and declines —
144-
the shape the fits have to recover.
122+
The simulated ``R_t`` starts near two, dips, peaks again around day 40 and falls through one near day 50, so the epidemic grows, turns over and declines.
145123

146124
```@example gp
147125
using CairoMakie
@@ -161,16 +139,9 @@ fig_sim
161139

162140
## Fit both GPs and compare
163141

164-
Conditioning on the observed counts and sampling with NUTS recovers the
165-
posterior. We differentiate with
166-
[Mooncake](https://chalk-lab.github.io/Mooncake.jl/), the recommended backend for
167-
this package.
168-
169-
A small helper fits a chosen GP latent to the first `n_fit` days, times the run,
170-
recovers the per-draw ``\log R_t`` with [`generated_observables`](@ref), and
171-
scores the posterior mean against the truth. `sample` returns a
172-
[FlexiChains](https://github.com/penelopeysm/FlexiChains.jl) chain, read directly
173-
— no conversion.
142+
Conditioning on the counts and sampling with NUTS recovers the posterior, differentiated with
143+
[Mooncake](https://chalk-lab.github.io/Mooncake.jl/), the recommended backend for this package.
144+
The helper below fits a chosen GP latent to the first `n_fit` days, times the run, recovers the per-draw ``\log R_t`` with [`generated_observables`](@ref) and scores the posterior mean against the truth.
174145

175146
```@example gp
176147
using Turing, Mooncake, Statistics
@@ -206,17 +177,11 @@ scores() = "$(score(hs)), $(score(ex))"
206177
(hsgp = score(hs), exact = score(ex))
207178
```
208179

209-
Both posterior means correlate with the simulated ``\log R_t`` above 0.9 on the
210-
days they cover, and the trajectory figure below shows the two agreeing with
211-
each other over the days they share — the check the exact GP is here to provide.
180+
Both posterior means correlate with the simulated ``\log R_t`` above 0.9 over the days they cover, and the figure below shows the two fits agreeing where they overlap.
181+
The exact GP is fit to `n_ex` days rather than all `n` because its ``O(n^3)`` factorisation at the full length would dominate the cost of building this page.
212182

213-
The exact GP is fit to the first `n_ex` days rather than all `n`: its ``O(n^3)``
214-
factorisation is rebuilt and differentiated at every leapfrog step, and at the
215-
full length it would dominate the cost of building this page. The wall-clock
216-
times above are single un-warmed runs that include the model's compilation and
217-
cover different series lengths, so read them as indicative. Timing one gradient
218-
of each composed log-density on the *same* `n_ex` days is the like-for-like
219-
comparison, and it is what the sampler actually pays per leapfrog step:
183+
Those wall-clock times are single un-warmed runs over different series lengths, so read them as indicative.
184+
One gradient of each composed log-density over the same `n_ex` days is the like-for-like comparison, and it is what the sampler pays per leapfrog step.
220185

221186
```@example gp
222187
using Chairmarks: @b
@@ -237,14 +202,12 @@ grad = (hsgp = gradient_time(composed(HilbertSpaceGP(m = 20), n_ex)),
237202
round(grad.exact / grad.hsgp; sigdigits = 2)
238203
```
239204

240-
The exact GP costs more per gradient even on the shorter series, and the gap
241-
widens with the series length: that is the reason the approximation exists.
205+
The exact GP costs more per gradient even on the shorter series, and the gap widens with series length, which is why the approximation exists.
242206

243207
## Posterior trajectories
244208

245-
Following the plotting convention of the other case studies, two small helpers
246-
reduce the per-draw trajectories to credible bands and draw a median line with
247-
50% and 95% ribbons.
209+
``R_t = \exp(Z_t)`` comes from the returned `Z_t` draws.
210+
The reported counts are scored element-wise, so their posterior predictive distribution comes from `predict` on the same model with the observations set to `missing`, stacking the `y_t[i]` draws into a time × draws matrix.
248211

249212
```@example gp
250213
CI_QS = [0.025, 0.25, 0.5, 0.75, 0.975]
@@ -259,16 +222,7 @@ function ci_ribbon!(ax, ts, b; color, label)
259222
band!(ax, ts, b[:, 2], b[:, 4]; color = (color, 0.3))
260223
lines!(ax, ts, b[:, 3]; color = color, linewidth = 2, label = label)
261224
end
262-
```
263225
264-
The reproduction number ``R_t = \exp(Z_t)`` comes from the returned `Z_t` draws.
265-
The reported counts are scored element-wise, so their posterior *predictive*
266-
distribution — fresh counts under each posterior parameter set — comes from
267-
`predict` on the same model with the observations set to `missing`, stacking the
268-
`y_t[i]` draws into a time × draws matrix. We overlay both GP fits on the
269-
simulated truth.
270-
271-
```@example gp
272226
ts = 1:n
273227
fig = Figure(; size = (760, 620))
274228
ax1 = Axis(fig[1, 1]; ylabel = "Reproduction number Rₜ")

0 commit comments

Comments
 (0)