Alterlab pymc

From AlterLab-IEU/AlterLab-Academic-Skills · View interactive version

Alterlab pymc is an AI agent skill from the GitHub repository AlterLab-IEU/AlterLab-Academic-Skills. Bayesian modeling and probabilistic programming with PyMC 6 and ArviZ 1.x — hierarchical models, MCMC (NUTS via PyMC, nutpie, NumPyro, or BlackJAX), variational inference, PSIS-LOO model comparison, and prior/posterior predictive checks. Use when fitting Bayesian or hierarchical models, estimating p

How to use this skill

Skill file

PyMC Bayesian Modeling

Overview

PyMC is a Python library for Bayesian modeling and probabilistic programming. Build, fit, validate, and compare Bayesian models using the current API (PyMC ≥ 6 with ArviZ ≥ 1.1), including hierarchical models, MCMC sampling (NUTS), variational inference, and PSIS-LOO model comparison.

# no install step (PyMC 6 and ArviZ 1.x need Python >= 3.12): nutpie sampler, plotting backend, NetCDF I/O
uv run --python ">=3.12" --with "pymc[nutpie]>=6" --with "arviz[matplotlib,h5netcdf]>=1.1" python model.py

PyMC 6 changed several defaults and names that most tutorials still use — read Version notes at the end before reusing PyMC 5 / ArviZ 0.x code.

When to Use This Skill

This skill should be used when:

Does NOT Trigger

| Scenario | Use Instead |

|----------|-------------|

| Frequentist regression with p-values, standard errors, and residual diagnostics | alterlab-statsmodels |

| Reporting-focused mixed-effects model for nested data (lme4/glmmTMB/brms, statsmodels MixedLM, or bambi formulas) with ICC and variance-component reporting | alterlab-multilevel-models |

| Pooling effect sizes across studies (fixed/random effects, heterogeneity, funnel plots) | alterlab-meta-analysis |

| Point-prediction machine learning (random forests, gradient boosting, CV tuning) | alterlab-scikit-learn |

Hand-off rule. When the request matches a row above, open your answer by naming that skill by its exact id (for example alterlab-statsmodels) and saying in one line why it fits better, then stop applying this skill's procedure. Name it even when you also need to ask for missing input. If only part of the request is out of scope, name the skill for that part and do only the in-scope part. A brief general pointer is fine; the named skill does the work.

Standard Bayesian Workflow

Follow this 8-step workflow for building and validating Bayesian models:

  1. Data preparation — standardize predictors, handle missing data, set up coords
  2. Model building — weakly informative priors, named dims, pm.Data() for predictables
  3. Prior predictive check — pm.sample_prior_predictive; validate priors before fitting
  4. Fit — pm.sample(draws=2000, tune=1000, chains=4, target_accept=0.9), then pm.compute_log_likelihood(idata) if you will compare models
  5. Diagnostics — R-hat < 1.01, ESS > 400, no divergences, good trace mixing
  6. Posterior predictive check — pm.sample_posterior_predictive; check fit vs. observed data
  7. Analyze — az.summary, az.plot_dist (was plot_posterior), az.plot_forest
  8. 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.

Use the non-centered parameterization for hierarchical models when groups have few observations: the centered form creates funnel geometry that NUTS explores poorly, which shows up as 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

Code and decision rules: references/model_comparison.md. Detailed sampling-algorithm guide:

references/sampling_inference.md.

Best Practices

Model Building

  1. Always standardize predictors for better sampling
  2. Use weakly informative priors (not flat)
  3. Use named dimensions (dims) for clarity
  4. Non-centered parameterization for hierarchical models
  5. Check prior predictive before fitting

Sampling

  1. Run multiple chains (at least 4) for convergence
  2. Use target_accept=0.9 as baseline (higher if needed)
  3. Call pm.compute_log_likelihood(idata) before model comparison
  4. Set random seed for reproducibility

Validation

  1. Check diagnostics before interpretation (R-hat, ESS, divergences)
  2. Posterior predictive check for model validation
  3. Compare multiple models when appropriate
  4. 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/`)

Scripts (`scripts/`)

Templates (`assets/`)

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)  # returns xarray.DataTree
pm.compute_log_likelihood(idata)  # needed for LOO / az.compare

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})  # PSIS-LOO; higher elpd is better

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

Version notes (PyMC 6 / ArviZ 1.x)

PyMC 6.0 (May 2026) moved to ArviZ 1.x and PyTensor 3. Code written for PyMC 5 / ArviZ 0.x fails in the ways below.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.