PyMC Bayesian Modeling
Overview
PyMC is a Python library for Bayesian modeling and probabilistic programming. Build, fit, validate, and compare Bayesian models using PyMC's modern API (version 5.x+), including hierarchical models, MCMC sampling (NUTS), variational inference, and model comparison (LOO, WAIC).
When to Use This Skill
This skill should be used when:
- Building Bayesian models (linear/logistic regression, hierarchical models, time series, etc.)
- Performing MCMC sampling or variational inference
- Conducting prior/posterior predictive checks
- Diagnosing sampling issues (divergences, convergence, ESS)
- Comparing multiple models using information criteria (LOO, WAIC)
- Implementing uncertainty quantification through Bayesian methods
- Working with hierarchical/multilevel data structures
- Handling missing data or measurement error in a principled way
Standard Bayesian Workflow
Follow this 8-step workflow for building and validating Bayesian models:
- Data preparation — standardize predictors, handle missing data, set up
coords
- Model building — weakly informative priors, named
dims, pm.Data() for predictables
- Prior predictive check —
pm.sample_prior_predictive; validate priors before fitting
- Fit —
pm.sample(draws=2000, tune=1000, chains=4, target_accept=0.9); include log_likelihood=True for comparison
- Diagnostics — R-hat < 1.01, ESS > 400, no divergences, good trace mixing
- Posterior predictive check —
pm.sample_posterior_predictive; check fit vs. observed data
- Analyze —
az.summary, az.plot_posterior, az.plot_forest
- Predict —
pm.set_data then pm.sample_posterior_predictive; extract HDI intervals
Full step-by-step code: references/workflow_examples.md.
Common Model Patterns
PyMC supports linear/logistic/Poisson regression, hierarchical (multilevel) models, and
time-series (AR). Ready-to-adapt code for each lives in references/model_patterns.md.
Critical: Always use non-centered parameterization for hierarchical models to avoid divergences.
Templates: assets/linear_regression_template.py, assets/hierarchical_model_template.py.
Distribution Selection
Choosing priors and likelihoods is the highest-leverage modeling decision. A quick chooser
(scale params, unbounded, positive, probabilities, correlation matrices; continuous/count/binary/
categorical likelihoods) is in references/distribution_selection.md. The comprehensive catalog
is in references/distributions.md.
Model Comparison and Sampling
- Compare models with LOO/WAIC (
scripts/model_comparison.py); interpret Δloo and Pareto-k.
- Sample with NUTS by default; raise
target_accept for divergences; ADVI for fast approximation.
- Diagnose with
scripts/model_diagnostics.py (check_diagnostics, create_diagnostic_report).
- Troubleshoot divergences, low ESS, high R-hat, slow sampling.
Code and decision rules: references/model_comparison.md. Detailed sampling-algorithm guide:
references/sampling_inference.md.
Best Practices
Model Building
- Always standardize predictors for better sampling
- Use weakly informative priors (not flat)
- Use named dimensions (
dims) for clarity
- Non-centered parameterization for hierarchical models
- Check prior predictive before fitting
Sampling
- Run multiple chains (at least 4) for convergence
- Use
target_accept=0.9 as baseline (higher if needed)
- Include
log_likelihood=True for model comparison
- Set random seed for reproducibility
Validation
- Check diagnostics before interpretation (R-hat, ESS, divergences)
- Posterior predictive check for model validation
- Compare multiple models when appropriate
- Report uncertainty (HDI intervals, not just point estimates)
Start simple and add complexity gradually, iterating on the model based on each
predictive check (see the 8-step workflow above).
Resources
This skill includes:
References (references/)
workflow_examples.md: Full step-by-step code for the 8-step Bayesian workflow (data prep → predictions).
model_patterns.md: Ready-to-adapt code for linear/logistic/Poisson regression, hierarchical, and AR time-series models.
distribution_selection.md: Quick chooser for priors and likelihoods by parameter/outcome type.
model_comparison.md: LOO/WAIC comparison, diagnostic scripts, and troubleshooting (divergences, ESS, R-hat, slow sampling).
distributions.md: Comprehensive catalog of PyMC distributions organized by category (continuous, discrete, multivariate, mixture, time series). Use when selecting priors or likelihoods.
sampling_inference.md: Detailed guide to sampling algorithms (NUTS, Metropolis, SMC), variational inference (ADVI, SVGD), and handling sampling issues. Use when encountering convergence problems or choosing inference methods.
workflows.md: A single end-to-end runnable script (data prep → save) plus extra cookbook recipes not in workflow_examples.md — missing-data imputation, QR reparameterization, mixture models, and a model-averaging helper.
Scripts (scripts/)
model_diagnostics.py: Automated diagnostic checking and report generation. Functions: check_diagnostics() for quick checks, create_diagnostic_report() for comprehensive analysis with plots.
model_comparison.py: Model comparison utilities using LOO/WAIC. Functions: compare_models(), check_loo_reliability(), model_averaging().
Templates (assets/)
linear_regression_template.py: Complete template for Bayesian linear regression with full workflow (data prep, prior checks, fitting, diagnostics, predictions).
hierarchical_model_template.py: Complete template for hierarchical/multilevel models with non-centered parameterization and group-level analysis.
Quick Reference
Model Building
with pm.Model(coords={'var': names}) as model:
# Priors
param = pm.Normal('param', mu=0, sigma=1, dims='var')
# Likelihood
y = pm.Normal('y', mu=..., sigma=..., observed=data)
Sampling
idata = pm.sample(draws=2000, tune=1000, chains=4, target_accept=0.9)
Diagnostics
from scripts.model_diagnostics import check_diagnostics
check_diagnostics(idata)
Model Comparison
from scripts.model_comparison import compare_models
compare_models({'m1': idata1, 'm2': idata2}, ic='loo')
Predictions
# X must have been wrapped at build time: pm.Data('X', X, dims=('obs', 'predictors'))
with model:
pm.set_data({'X': X_new}, coords={'obs': range(len(X_new))})
pm.sample_posterior_predictive(idata, predictions=True, extend_inferencedata=True)
# predictions land in idata.predictions
Additional Notes
- PyMC integrates with ArviZ for visualization and diagnostics
- Use
pm.model_to_graphviz(model) to visualize model structure
- Save results with
idata.to_netcdf('results.nc'); load with az.from_netcdf('results.nc')
- For very large models, consider minibatch ADVI or data subsampling
Common gotchas (PyMC 5.x / ArviZ):
- To predict on new data, the predictors must be wrapped in
pm.Data('X', X, dims=...) at build time — only then can pm.set_data({'X': X_new}, coords={...}) swap them. A plain NumPy array baked into the graph cannot be replaced.
pm.sample_prior_predictive takes draws= (the old samples= keyword was removed).
- For out-of-sample predictions call
pm.sample_posterior_predictive(idata, predictions=True, extend_inferencedata=True, ...); results then live in idata.predictions, not idata.posterior_predictive.
1---2name: alterlab-pymc3description: Bayesian modeling and probabilistic programming with PyMC — hierarchical models, MCMC (NUTS) sampling, variational inference, LOO/WAIC model comparison, and posterior predictive checks. Use when fitting Bayesian or hierarchical models, estimating posteriors and credible intervals, running probabilistic inference, or comparing models with LOO/WAIC. Part of the AlterLab Academic Skills suite.4license: Apache-2.05---67# PyMC Bayesian Modeling89## Overview1011PyMC is a Python library for Bayesian modeling and probabilistic programming. Build, fit, validate, and compare Bayesian models using PyMC's modern API (version 5.x+), including hierarchical models, MCMC sampling (NUTS), variational inference, and model comparison (LOO, WAIC).1213## When to Use This Skill1415This skill should be used when:16- Building Bayesian models (linear/logistic regression, hierarchical models, time series, etc.)17- Performing MCMC sampling or variational inference18- Conducting prior/posterior predictive checks19- Diagnosing sampling issues (divergences, convergence, ESS)20- Comparing multiple models using information criteria (LOO, WAIC)21- Implementing uncertainty quantification through Bayesian methods22- Working with hierarchical/multilevel data structures23- Handling missing data or measurement error in a principled way2425## Standard Bayesian Workflow2627Follow this 8-step workflow for building and validating Bayesian models:28291. **Data preparation** — standardize predictors, handle missing data, set up `coords`302. **Model building** — weakly informative priors, named `dims`, `pm.Data()` for predictables313. **Prior predictive check** — `pm.sample_prior_predictive`; validate priors *before* fitting324. **Fit** — `pm.sample(draws=2000, tune=1000, chains=4, target_accept=0.9)`; include `log_likelihood=True` for comparison335. **Diagnostics** — R-hat < 1.01, ESS > 400, no divergences, good trace mixing346. **Posterior predictive check** — `pm.sample_posterior_predictive`; check fit vs. observed data357. **Analyze** — `az.summary`, `az.plot_posterior`, `az.plot_forest`368. **Predict** — `pm.set_data` then `pm.sample_posterior_predictive`; extract HDI intervals3738Full step-by-step code: `references/workflow_examples.md`.3940## Common Model Patterns4142PyMC supports linear/logistic/Poisson regression, hierarchical (multilevel) models, and43time-series (AR). Ready-to-adapt code for each lives in `references/model_patterns.md`.4445**Critical:** Always use non-centered parameterization for hierarchical models to avoid divergences.46Templates: `assets/linear_regression_template.py`, `assets/hierarchical_model_template.py`.4748## Distribution Selection4950Choosing priors and likelihoods is the highest-leverage modeling decision. A quick chooser51(scale params, unbounded, positive, probabilities, correlation matrices; continuous/count/binary/52categorical likelihoods) is in `references/distribution_selection.md`. The comprehensive catalog53is in `references/distributions.md`.5455## Model Comparison and Sampling5657- **Compare models** with LOO/WAIC (`scripts/model_comparison.py`); interpret Δloo and Pareto-k.58- **Sample** with NUTS by default; raise `target_accept` for divergences; ADVI for fast approximation.59- **Diagnose** with `scripts/model_diagnostics.py` (`check_diagnostics`, `create_diagnostic_report`).60- **Troubleshoot** divergences, low ESS, high R-hat, slow sampling.6162Code and decision rules: `references/model_comparison.md`. Detailed sampling-algorithm guide:63`references/sampling_inference.md`.6465## Best Practices6667### Model Building68691. **Always standardize predictors** for better sampling702. **Use weakly informative priors** (not flat)713. **Use named dimensions** (`dims`) for clarity724. **Non-centered parameterization** for hierarchical models735. **Check prior predictive** before fitting7475### Sampling76771. **Run multiple chains** (at least 4) for convergence782. **Use `target_accept=0.9`** as baseline (higher if needed)793. **Include `log_likelihood=True`** for model comparison804. **Set random seed** for reproducibility8182### Validation83841. **Check diagnostics** before interpretation (R-hat, ESS, divergences)852. **Posterior predictive check** for model validation863. **Compare multiple models** when appropriate874. **Report uncertainty** (HDI intervals, not just point estimates)8889Start simple and add complexity gradually, iterating on the model based on each90predictive check (see the 8-step workflow above).9192## Resources9394This skill includes:9596### References (`references/`)9798- **`workflow_examples.md`**: Full step-by-step code for the 8-step Bayesian workflow (data prep → predictions).99- **`model_patterns.md`**: Ready-to-adapt code for linear/logistic/Poisson regression, hierarchical, and AR time-series models.100- **`distribution_selection.md`**: Quick chooser for priors and likelihoods by parameter/outcome type.101- **`model_comparison.md`**: LOO/WAIC comparison, diagnostic scripts, and troubleshooting (divergences, ESS, R-hat, slow sampling).102- **`distributions.md`**: Comprehensive catalog of PyMC distributions organized by category (continuous, discrete, multivariate, mixture, time series). Use when selecting priors or likelihoods.103- **`sampling_inference.md`**: Detailed guide to sampling algorithms (NUTS, Metropolis, SMC), variational inference (ADVI, SVGD), and handling sampling issues. Use when encountering convergence problems or choosing inference methods.104- **`workflows.md`**: A single end-to-end runnable script (data prep → save) plus extra cookbook recipes not in `workflow_examples.md` — missing-data imputation, QR reparameterization, mixture models, and a model-averaging helper.105106### Scripts (`scripts/`)107108- **`model_diagnostics.py`**: Automated diagnostic checking and report generation. Functions: `check_diagnostics()` for quick checks, `create_diagnostic_report()` for comprehensive analysis with plots.109110- **`model_comparison.py`**: Model comparison utilities using LOO/WAIC. Functions: `compare_models()`, `check_loo_reliability()`, `model_averaging()`.111112### Templates (`assets/`)113114- **`linear_regression_template.py`**: Complete template for Bayesian linear regression with full workflow (data prep, prior checks, fitting, diagnostics, predictions).115116- **`hierarchical_model_template.py`**: Complete template for hierarchical/multilevel models with non-centered parameterization and group-level analysis.117118## Quick Reference119120### Model Building121```python122with pm.Model(coords={'var': names}) as model:123 # Priors124 param = pm.Normal('param', mu=0, sigma=1, dims='var')125 # Likelihood126 y = pm.Normal('y', mu=..., sigma=..., observed=data)127```128129### Sampling130```python131idata = pm.sample(draws=2000, tune=1000, chains=4, target_accept=0.9)132```133134### Diagnostics135```python136from scripts.model_diagnostics import check_diagnostics137check_diagnostics(idata)138```139140### Model Comparison141```python142from scripts.model_comparison import compare_models143compare_models({'m1': idata1, 'm2': idata2}, ic='loo')144```145146### Predictions147```python148# X must have been wrapped at build time: pm.Data('X', X, dims=('obs', 'predictors'))149with model:150 pm.set_data({'X': X_new}, coords={'obs': range(len(X_new))})151 pm.sample_posterior_predictive(idata, predictions=True, extend_inferencedata=True)152# predictions land in idata.predictions153```154155## Additional Notes156157- PyMC integrates with ArviZ for visualization and diagnostics158- Use `pm.model_to_graphviz(model)` to visualize model structure159- Save results with `idata.to_netcdf('results.nc')`; load with `az.from_netcdf('results.nc')`160- For very large models, consider minibatch ADVI or data subsampling161162**Common gotchas (PyMC 5.x / ArviZ):**163- To predict on new data, the predictors must be wrapped in `pm.Data('X', X, dims=...)` at build time — only then can `pm.set_data({'X': X_new}, coords={...})` swap them. A plain NumPy array baked into the graph cannot be replaced.164- `pm.sample_prior_predictive` takes `draws=` (the old `samples=` keyword was removed).165- For out-of-sample predictions call `pm.sample_posterior_predictive(idata, predictions=True, extend_inferencedata=True, ...)`; results then live in `idata.predictions`, not `idata.posterior_predictive`.166