@@ -25,13 +25,13 @@ import bambi as bmb
25
25
import matplotlib.pyplot as plt
26
26
import numpy as np
27
27
import pandas as pd
28
- import pymc3 as pm
28
+ import pymc as pm
29
29
import seaborn as sns
30
30
import xarray as xr
31
31
32
32
from ipywidgets import fixed, interactive
33
33
34
- print(f"Running on PyMC3 v{pm.__version__}")
34
+ print(f"Running on PyMC v{pm.__version__}")
35
35
```
36
36
37
37
``` {code-cell} ipython3
@@ -44,7 +44,7 @@ plt.rcParams["figure.constrained_layout.use"] = False
44
44
```
45
45
46
46
## Introduction
47
- A fairly minimal reproducible example of Model Selection using WAIC, and LOO as currently implemented in PyMC3 .
47
+ A fairly minimal reproducible example of Model Selection using WAIC, and LOO as currently implemented in PyMC .
48
48
49
49
This example creates two toy datasets under linear and quadratic models, and then tests the fit of a range of polynomial linear models upon those datasets by using Widely Applicable Information Criterion (WAIC), and leave-one-out (LOO) cross-validation using Pareto-smoothed importance sampling (PSIS).
50
50
@@ -198,12 +198,18 @@ def plot_posterior_cr(models, idatas, rawdata, xlims, datamodelnm="linear", mode
198
198
# Get traces and calc posterior prediction for npoints in x
199
199
npoints = 100
200
200
mdl = models[modelnm]
201
- trc = idatas[modelnm].posterior.copy().drop_vars("y_sigma")
202
- da = xr.concat([var for var in trc.values()], dim="order")
201
+ trc = idatas[modelnm].posterior.copy()
203
202
204
- ordr = int(modelnm[-1:])
203
+ # Extract variables and stack them in correct order
204
+ vars_to_concat = []
205
+ for var in ["Intercept", "x"] + [f"np.power(x, {i})" for i in range(2, int(modelnm[-1:]) + 1)]:
206
+ if var in trc:
207
+ vars_to_concat.append(trc[var])
208
+ da = xr.concat(vars_to_concat, dim="order")
209
+
210
+ ordr = len(vars_to_concat)
205
211
x = xr.DataArray(np.linspace(xlims[0], xlims[1], npoints), dims=["x_plot"])
206
- pwrs = xr.DataArray(np.arange(ordr + 1 ), dims=["order"])
212
+ pwrs = xr.DataArray(np.arange(ordr), dims=["order"])
207
213
X = x**pwrs
208
214
cr = xr.dot(X, da, dims="order")
209
215
@@ -337,7 +343,7 @@ $$y = a + bx + \epsilon$$
337
343
338
344
+++
339
345
340
- ### Define model using explicit PyMC3 method
346
+ ### Define model using explicit PyMC method
341
347
342
348
``` {code-cell} ipython3
343
349
with pm.Model() as mdl_ols:
@@ -417,7 +423,7 @@ def create_poly_modelspec(k=1):
417
423
def run_models(df, upper_order=5):
418
424
"""
419
425
Convenience function:
420
- Fit a range of pymc3 models of increasing polynomial complexity.
426
+ Fit a range of pymc models of increasing polynomial complexity.
421
427
Suggest limit to max order 5 since calculation time is exponential.
422
428
"""
423
429
@@ -432,7 +438,9 @@ def run_models(df, upper_order=5):
432
438
models[nm] = bmb.Model(
433
439
fml, df, priors={"intercept": bmb.Prior("Normal", mu=0, sigma=100)}, family="gaussian"
434
440
)
435
- results[nm] = models[nm].fit(draws=2000, tune=1000, init="advi+adapt_diag")
441
+ results[nm] = models[nm].fit(
442
+ draws=2000, tune=1000, init="advi+adapt_diag", idata_kwargs={"log_likelihood": True}
443
+ )
436
444
437
445
return models, results
438
446
```
@@ -499,11 +507,11 @@ dfwaic_quad
499
507
_, axs = plt.subplots(1, 2)
500
508
501
509
ax = axs[0]
502
- az.plot_compare(dfwaic_lin, ax=ax)
510
+ az.plot_compare(dfwaic_lin, ax=ax, legend=False )
503
511
ax.set_title("Linear data")
504
512
505
513
ax = axs[1]
506
- az.plot_compare(dfwaic_quad, ax=ax)
514
+ az.plot_compare(dfwaic_quad, ax=ax, legend=False )
507
515
ax.set_title("Quadratic data");
508
516
```
509
517
@@ -545,11 +553,11 @@ dfloo_quad
545
553
_, axs = plt.subplots(1, 2)
546
554
547
555
ax = axs[0]
548
- az.plot_compare(dfloo_lin, ax=ax)
556
+ az.plot_compare(dfloo_lin, ax=ax, legend=False )
549
557
ax.set_title("Linear data")
550
558
551
559
ax = axs[1]
552
- az.plot_compare(dfloo_quad, ax=ax)
560
+ az.plot_compare(dfloo_quad, ax=ax, legend=False )
553
561
ax.set_title("Quadratic data");
554
562
```
555
563
@@ -601,6 +609,7 @@ spiegelhalter2002bayesian
601
609
* Re-executed by Alex Andorra and Michael Osthege on June, 2020 ([ pymc #3955 ] ( https://github.com/pymc-devs/pymc/pull/3955 ) )
602
610
* Updated by Raul Maldonado on March, 2021 ([ pymc-examples #24 ] ( https://github.com/pymc-devs/pymc-examples/pull/24 ) )
603
611
* Updated by Abhipsha Das and Oriol Abril on June, 2021 ([ pymc-examples #173 ] ( https://github.com/pymc-devs/pymc-examples/pull/173 ) )
612
+ * Updated by Chris Fonnesbeck on December, 2024 ([ pymc-examples #761 ] ( https://github.com/pymc-devs/pymc-examples/pull/761 ) )
604
613
605
614
+++
606
615
@@ -613,7 +622,3 @@ spiegelhalter2002bayesian
613
622
614
623
:::{include} ../page_footer.md
615
624
:::
616
-
617
- ``` {code-cell} ipython3
618
-
619
- ```
0 commit comments