-
Notifications
You must be signed in to change notification settings - Fork 1
/
software_options.qmd
550 lines (402 loc) · 14.6 KB
/
software_options.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
---
title: "Software Options for Bayesian Modelling"
subtitle: "Should we still use WinBugs?"
author:
- name: "Theo Rashid"
email: "theo.rashid15@imperial.ac.uk"
institute: "Imperial College London"
date: 2023-08-15
date-format: medium
title-slide-attributes:
data-background-color: "#f3f4f4"
data-background-image: "../../assets/bmeh_normal.png"
data-background-size: 80%
data-background-position: 60% 120%
format:
revealjs:
slide-number: true
incremental: true
chalkboard:
buttons: false
preview-links: auto
logo: "../../assets/bmeh_normal.png"
theme: [default, ../../assets/style.scss]
---
# What did people do before packages?
## They wrote their posterior probability density
$$
\begin{align}
y_i &\sim \text{Normal}(\mu_i, \sigma) \\
\mu_i &= \alpha + \mathbf{x_i^\top} \mathbf{\beta} \\
\alpha &\sim \text{Normal}(0, 10) \\
\mathbf{\beta} &\sim \text{Normal}(0, 1) \\
\sigma &\sim \text{Uniform}(0, 100)
\end{align}
$$
## They wrote their posterior probability density
```{.python code-line-numbers="5-15"}
import numpy as np
from scipy.stats import norm, uniform
from scipy.special import logsumexp
def logpdf(params, data):
log_prior = (
norm.logpdf(params.alpha, loc=0.0, scale=10.0) +
uniform.logpdf(params.sigma, low=0.0, high=100.0) +
np.sum(norm.logpdf(params.beta, loc=0.0, scale=1.0))
)
mu = params.alpha + jnp.matmul(x, params.beta)
log_likelihood = norm.logpdf(data, mu, params.sigma)
return logsumexp(log_prior + log_likelihood, axis=0)
```
## They wrote their own samplers
```{.python code-line-numbers="8-9"}
import numpy as np
def rw_metropolis_kernel(logpdf, data, position, log_prob):
move_proposals = np.random.normal(0, 0.1, size=position.shape)
proposal = position + move_proposals
proposal_log_prob = logpdf(proposal, data)
log_uniform = np.log(np.random.uniform(low=0, high=1))
do_accept = log_uniform < proposal_log_prob - log_prob
position = np.where(do_accept, proposal, position)
log_prob = np.where(do_accept, proposal_log_prob, log_prob)
return position, log_prob
```
## You are not Arianna Rosenbluth
- You will make a mistake.
- Why write code that people have written before?
- Do you enjoy calibrating samplers?
::: {.notes}
You will make a mistake.
People have done this before, and spent a lot more time doing this.
They write better inference algorithms than you.
It turns out that he and Arianna Rosenbluth (his wife) did most of the work. More specifically, he did the mathematical work, Arianna wrote the code that ran on the MANIAC, August Teller wrote an earlier version of the code, and Edward Teller gave some critical suggestions about the methodology. Finally, Nick Metropolis provided the computing time; as he was first author the method is therefore named after him. But perhaps a more appropriate name would have been the Rosenbluth algorithm.
:::
# Probabilistic programming languages
# "Monolithic"
::: {.notes}
Thomas Wiecki, PyMC dev
:::
# WinBUGS
## Write models in the BUGS language
```{.R}
model(
# prior
alpha ~ dnorm(0, pow(10, -2))
sigma ~ dunif(0, 100)
tau <- pow(sigma, -2) # precision
for (k in 1:p) beta[k] ~ dnorm(0, 1)
# likelihood
for (i in 1:n) {
y[i] ~ dnorm(mu[i], tau)
mu[i] <- alpha + inprod(beta[1:p], x[i, 1:p])
}
)
```
## Look at this <span style="color:#f928d2;">thrilling</span> output.
![](assets/winbugs_screenshot.jpeg)
## Is WinBugs still good?^[No]
:::: {.columns}
::: {.column width="50%"}
::: {style="color: #58b364"}
- Point and click
- See your chains as they run
:::
:::
::: {.column width="50%"}
::: {style="color: #fc6161"}
- Slow
- Old
:::
:::
::::
- No
# Stan
## Model in Stan
```
data {
int<lower=0> N; // number of data items
int<lower=0> P; // number of predictors
matrix[N, K] x; // predictor matrix
vector[N] y; // outcome vector
}
parameters {
real alpha; // intercept
vector[P] beta; // coefficients for predictors
real<lower=0> sigma; // error scale
}
transformed parameters {
vector[N] mu;
mu = alpha + X * beta;
}
model {
alpha ~ normal(0., 10.);
beta ~ normal(0., 1.);
sigma ~ uniform(0., 100.);
y ~ normal(mu, sigma); // likelihood
}
```
::: aside
Stan, not STAN
:::
::: {.notes}
Stanislaw Ulam is probably best known for realising that electronic computers made it practical to apply statistical methods to functions without known solutions, and as computers have developed, the Monte Carlo method has become a common and standard approach to many problems.
:::
## The granddaddy of PPLs
:::: {.columns}
::: {.column width="50%"}
::: {style="color: #58b364"}
- The statistician's choice
- Reliable, battle-tested samplers (including NUTS)
- Interface with `python`, `R` or `Julia`
:::
:::
::: {.column width="50%"}
::: {style="color: #fc6161"}
- Difficult to extend
- Writing things like `int<lower=0> N`
:::
:::
::::
- Using `brms` or `rstanarm`, you can write models like base `R` (like `y ~ 1 + x`) and the inference is done in Stan.
# NIMBLE
## NIMBLE model is like WinBUGS, but more flexible
```{.R}
model(
# prior
alpha ~ dnorm(0, sd = 10)
sigma ~ dunif(0, 100)
beta[1:k] ~ dnorm(0, 1)
# likelihood
for (i in 1:n) {
y[i] ~ dnorm(mu[i], sd = sigma)
mu[i] <- alpha + (beta[1:p] %*% x[i, 1:p])[1,1]
}
)
```
## I like NIMBLE, but
:::: {.columns}
::: {.column width="50%"}
::: {style="color: #58b364"}
- Compiles `R` to `C++` for speed and scalability
- Automatically finds conjugate relationships
- Can pick a different sampler for each parameter
:::
:::
::: {.column width="50%"}
::: {style="color: #fc6161"}
- If the sampler is not conjugate, it can mix poorly
:::
:::
::::
## Ranking these PPLs^[Entirely subjective]
Usability:
- How easy is it to fit a model?
- How easy is it to run the model?
- How good is the documentation?
- Does it have everything I need?
- How good is the performance?
## Ranking these PPLs^[Entirely subjective]
Extensibility:
- If it can't do something, how easily can I make it do that?
- How modular is it? Can other packages work with it?
## Ranking these PPLs
![](assets/usability-extensibility.png)
![](assets/stan.png){.fragment .absolute top="72%" left="74%" width="6%"}
![](assets/winbugs.png){.fragment .absolute top="82%" left="10%" width="6%"}
![](assets/nimble.jpeg){.fragment .absolute top="55%" left="65%" width="6%"}
# Decoupled
## Decoupled
Separate the __model__ from the __inference__.
- PPL defines the __log posterior probability density__
- Makes use of great tensor libraries (`jax`, `tensorflow`, `PyTorch`, `aesara`) to do the maths
## tensorflow probability
```{.python}
def model(np, x):
def joint_dist():
alpha = yield tfd.Normal(loc=0.0, scale=10.0)
sigma = yield tfd.Uniform(low=0.0, high=100.0)
beta = yield tfd.Normal(loc=tf.zeros(np), scale=1.0)
mu = alpha + tf.linalg.matmul(x, beta)
yield tfd.Normal(loc=mu, scale=sigma)
return tfd.JointDistributionCoroutineAutoBatched(joint_dist)
```
This is terrible.
Don't use it.
## Ranking these PPLs
![](assets/usability-extensibility.png)
![](assets/stan.png){.absolute top="72%" left="74%" width="6%"}
![](assets/winbugs.png){.absolute top="82%" left="10%" width="6%"}
![](assets/nimble.jpeg){.absolute top="55%" left="65%" width="6%"}
![](assets/tensorflow.png){.fragment .absolute top="55%" left="35%" width="6%"}
## PyMC
```{.python}
import pymc as pm
with pm.Model() as model:
alpha = pm.Normal("alpha", 0.0, sigma=10.0)
sigma = pm.Uniform("sigma", low=0.0, high=100.0)
beta = pm.Normal("beta", 0, sigma=1.0, shape=(np,))
mu = alpha + pt.matmul(x, beta)
likelihood = pm.Normal("y", mu=mu, sigma=sigma, observed=y)
```
## PyMC is the dev choice
:::: {.columns}
::: {.column width="50%"}
::: {style="color: #58b364"}
- Great open source community
- `aesara` backend can compile to `jax`, `C`, `numba` (and more)
- Runs on GPU easily
- Best documentation
:::
:::
::: {.column width="50%"}
::: {style="color: #fc6161"}
- Always in development/flux
- Multiple backends can be confusing
:::
:::
::::
## Ranking these PPLs
![](assets/usability-extensibility.png)
![](assets/stan.png){.absolute top="72%" left="74%" width="6%"}
![](assets/winbugs.png){.absolute top="82%" left="10%" width="6%"}
![](assets/nimble.jpeg){.absolute top="55%" left="65%" width="6%"}
![](assets/tensorflow.png){.absolute top="55%" left="35%" width="6%"}
![](assets/pymc.png){.fragment .absolute top="25%" left="75%" width="8%"}
## numpyro
```{.python}
import jax.numpy as jnp
def model(np, x, y=None):
alpha = numpyro.sample("alpha", dist.Normal(0.0, 10.0))
sigma = numpyro.sample("sigma", dist.Uniform(0.0, 100.0))
with numpyro.plate("plate_predictors", np):
beta = numpyro.sample("beta", dist.Normal(0.0, 1.0))
mu = alpha + jnp.matmul(x, beta)
with numpyro.plate("data", len(x)):
numpyro.sample("y", dist.Normal(mu, sigma), obs=y)
```
::: aside
There is a related package called Pyro with a PyTorch backend, but numpyro's `jax` backend is better for sampling.
:::
## numpyro is my favourite (for now)
:::: {.columns}
::: {.column width="50%"}
::: {style="color: #58b364"}
- Really quick
- Runs on GPU easily
- Works with entire `jax` ecosystem
:::
:::
::: {.column width="50%"}
::: {style="color: #fc6161"}
- Small learning curve to get used to `plate` notation
:::
:::
::::
## Ranking these PPLs
![](assets/usability-extensibility.png)
![](assets/stan.png){.absolute top="72%" left="74%" width="6%"}
![](assets/winbugs.png){.absolute top="82%" left="10%" width="6%"}
![](assets/nimble.jpeg){.absolute top="55%" left="65%" width="6%"}
![](assets/tensorflow.png){.absolute top="55%" left="35%" width="6%"}
![](assets/pymc.png){.absolute top="25%" left="75%" width="8%"}
![](assets/numpyro.png){.fragment .absolute top="22%" left="78%" width="10%"}
## Other packages
`JAGS`, `greta`, `beanmachine`, `Turing.jl` etc
## Ranking these PPLs
![](assets/usability-extensibility.png)
![](assets/stan.png){.absolute top="72%" left="74%" width="6%"}
![](assets/winbugs.png){.absolute top="82%" left="10%" width="6%"}
![](assets/nimble.jpeg){.absolute top="55%" left="65%" width="6%"}
![](assets/tensorflow.png){.absolute top="55%" left="35%" width="6%"}
![](assets/pymc.png){.absolute top="25%" left="75%" width="8%"}
![](assets/numpyro.png){.absolute top="22%" left="78%" width="10%"}
![](assets/jags.png){.fragment .absolute top="81%" left="30%" width="8%"}
![](assets/greta.png){.fragment .absolute top="68%" left="34%" width="8%"}
![](assets/beanmachine.png){.fragment .absolute top="65%" left="25%" width="6%"}
![](assets/turing.png){.fragment .absolute top="40%" left="62%" width="6%"}
## A note on blackjax
1. Write any log probability function (either manually or in numpyro, PyMC, tfp etc)
2. Sample using a vast array of samplers/inference algorithms written in `jax`
## A note on blackjax
```{.python}
logdensity = lambda x: logdensity_fn(**x)
def inference_loop(rng_key, kernel, initial_state, num_samples):
@jax.jit
def one_step(state, rng_key):
state, _ = kernel(rng_key, state)
return state, state
keys = jax.random.split(rng_key, num_samples)
_, states = jax.lax.scan(one_step, initial_state, keys)
return states
nuts = blackjax.nuts(logdensity, **nuts_params)
states = inference_loop(rng_key, jax.jit(nuts.step), nuts.init(initial_position), 10_000)
```
## And what about the samples
Use `posterior` for `R`.
```{.R}
eight_schools_df <- as_draws_df(eight_schools_array)
summarise_draws(eight_schools_df)
#> # A tibble: 10 × 10
#> variable mean median sd mad q5 q95 rhat ess_bulk ess_tail
#> <chr> <num> <num> <num> <num> <num> <num> <num> <num> <num>
#> 1 mu 4.18 4.16 3.40 3.57 -0.854 9.39 1.02 558. 322.
#> 2 tau 4.16 3.07 3.58 2.89 0.309 11.0 1.01 246. 202.
#> 3 theta[1] 6.75 5.97 6.30 4.87 -1.23 18.9 1.01 400. 254.
#> 4 theta[2] 5.25 5.13 4.63 4.25 -1.97 12.5 1.02 564. 372.
#> 5 theta[3] 3.04 3.99 6.80 4.94 -10.3 11.9 1.01 312. 205.
```
## And what about the samples
And `ArviZ` for `python` or `Julia`
```{.python}
data = az.from_pystan(posterior=fit)
az.summary(data, var_names=["mu", "tau"])
Out[1]:
mean sd hdi_3% hdi_97% ... mcse_sd ess_bulk ess_tail r_hat
mu 4.486 3.487 -1.623 10.693 ... 0.160 241.0 659.0 1.02
tau 4.124 3.102 0.896 9.668 ... 0.186 67.0 38.0 1.06
[2 rows x 9 columns]
```
# Is sampling the only way?
## Variational inference
- Turn the inference problem into an optimisation problem
- Minimise the difference between true posterior distribution, $p(z|x)$, and variational distribution, $q(z)$
![](assets/variational_inference.png)
::: {.notes}
No guarantees like sampling of true posterior.
Minimise the ELBO (minimise the sum of the log likelihood and the KL divergence between the variation distribution and the prior).
Optimise the variational parameters of the variational (surrogate) distribution.
In this case, variational approximation is a Gaussian (Laplace approximation)
:::
## I've heard people talk about INLA. What is INLA?
- Approximate Bayesian inference for latent Gaussian models^[has extensions for non-Gaussian]
- Really good for spatial statistics
- Really quick
- Most real world cases are latent Gaussian – it just works
- Only used by 3 people, 2 of whom are here today
## So how does it work?
INLA computes accurate and fast approximations to the posterior marginals of the components of the latent Gaussian variables.
## So how does it work???
![](assets/laplace_approximation.png)
Basically, the Laplace Approximation (IN __LA__) means that we approximate a distribution with a Gaussian.
Most things in the real world are Gaussian, so this works well.
## Do I fit models like all the PPLs above?
No, actually, the syntax is really similar to base `R`.
For example, this is how to specify a model with an intercept and a random effect.
```{.R}
formula_iid <- y ~ 1 + f(x, model = "iid")
```
So it's easier to specify models, and there's a lot of inbuilt functionality.
__But__ it's much more difficult to *customise*.
## I think I'm <span style="color:#f928d2;">INLA</span>
Good, we'll cover more in the practical.
---
![](assets/probabilistic-programming.png)
# Getting ready for the lab
## The lab for this session {.smaller}
- The goal of this lab is to use `INLA` to run some hierarchical models.
- During this lab session, we will:
1. Translate a model from `NIMBLE` into `INLA`;
2. Fit spatial models with `INLA`;
3. Learn how to work with `INLA` objects; and
4. See how to write models in different probabilistic programming languages.
# Questions?