Bayesian modeling with PyMC 6 and ArviZ 1.x — hierarchical models, MCMC (NUTS), variational inference, PSIS-LOO comparison, and prior/posterior predictive checks.
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.
This skill should be used when:
| 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.
Follow this 8-step workflow for building and validating Bayesian models:
coordsdims, pm.Data() for predictablespm.sample_prior_predictive; validate priors before fittingpm.sample(draws=2000, tune=1000, chains=4, target_accept=0.9), then pm.compute_log_likelihood(idata) if you will compare modelspm.sample_posterior_predictive; check fit vs. observed dataaz.summary, az.plot_dist (was plot_posterior), az.plot_forestpm.set_data then pm.sample_posterior_predictive; extract HDI intervalsFull step-by-step code: references/workflow_examples.md.
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.
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.
scripts/model_comparison.py); interpret elpd_diff against dse and check Pareto-k. ArviZ 1.x has no WAIC.target_accept for divergences; ADVI for fast approximation.scripts/model_diagnostics.py (check_diagnostics, create_diagnostic_report).Code and decision rules: references/model_comparison.md. Detailed sampling-algorithm guide:
references/sampling_inference.md.
dims) for claritytarget_accept=0.9 as baseline (higher if needed)pm.compute_log_likelihood(idata) before model comparisonStart simple and add complexity gradually, iterating on the model based on each predictive check (see the 8-step workflow above).
This skill includes:
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: PSIS-LOO 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/)model_diagnostics.py: Automated diagnostic checking and report generation (handles both PyMC-NUTS and nutpie sample stats). Functions: check_diagnostics() for quick checks, create_diagnostic_report() for comprehensive analysis with plots.
model_comparison.py: PSIS-LOO model comparison utilities. Functions: compare_models(), check_loo_reliability(), model_averaging().
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.
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)
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
from scripts.model_diagnostics import check_diagnostics
check_diagnostics(idata)
from scripts.model_comparison import compare_models
compare_models({'m1': idata1, 'm2': idata2}) # PSIS-LOO; higher elpd is better
# 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
pm.model_to_graphviz(model) to visualize model structure (needs the graphviz package)idata.to_netcdf('results.nc') (requires h5netcdf or netCDF4, e.g. arviz[h5netcdf]); load with az.from_netcdf('results.nc')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.
xarray.DataTree, not az.InferenceData. Group access (idata.posterior, idata["posterior"]) still works; idata.extend(other) became idata.update(other); list groups with list(idata.children).pm.compute_log_likelihood(idata) after sampling. pm.sample(idata_kwargs={"log_likelihood": True}) is deprecated.nuts_sampler="pymc" | "nutpie" | "numpyro" | "blackjax". Sample-stat names differ (tree_depth vs depth), so diagnostics code should check which exists. Starting values go in initvals= (start= fails).az.summary reports 89% equal-tailed intervals (eti89_lb, eti89_ub) instead of 94% HDI (hdi_3%, hdi_97%). Use az.summary(idata, ci_kind="hdi", ci_prob=0.94) or set az.rcParams["stats.ci_kind"] / ["stats.ci_prob"]. az.hdi(..., prob=0.95) replaces hdi_prob=.PlotCollection (save with pc.savefig("file.png"), show with pc.show()); ax= / axes= arguments are gone. Renames: plot_posterior → plot_dist, plot_ppc → plot_ppc_dist (prior checks: group="prior_predictive", num_samples= instead of num_pp_samples=), plot_trace → plot_trace_dist (trace plus density), plot_dist_comparison → plot_prior_posterior. Install a backend with arviz[matplotlib].az.waic is gone and az.compare(dict) takes no ic=/scale=; it ranks by PSIS-LOO elpd (higher is better) with stacking weights and reports elpd_diff, dse, p_worse, and diag_* columns.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).pm.sample_posterior_predictive(idata, predictions=True, extend_inferencedata=True, ...); results then live in idata.predictions, not idata.posterior_predictive.assets/hierarchical_model_template.py (opens in a new tab)assets/linear_regression_template.py (opens in a new tab)evals/evals.json (opens in a new tab)references/distribution_selection.md (opens in a new tab)references/distributions.md (opens in a new tab)references/model_comparison.md (opens in a new tab)references/model_patterns.md (opens in a new tab)references/sampling_inference.md (opens in a new tab)references/workflow_examples.md (opens in a new tab)references/workflows.md (opens in a new tab)scripts/model_comparison.py (opens in a new tab)scripts/model_diagnostics.py (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
2 plugins in one repository ship this exact skill · first indexed Nov 9, 2026
241 skills in this plugin
/alterlab-abm-mesaBuilds agent-based models of social systems with Mesa 3 — the current AgentSet API (model.agents.shuffle_do('step'), auto-assigned unique_id, mandatory super().__init__(rng=...)), cell spaces (mesa.discrete_space OrthogonalMooreGrid / classic mesa.space grids), the DataCollector, batch_run parameter sweeps, and SolaraViz — for emergence, segregation, diffusion, opinion dynamics, and cooperation models. It uses the Mesa 3.x API (the old mesa.time schedulers like RandomActivation are removed) and treats the model as a generative theory to be validated, not just run. Use when the request mentions an agent-based model, Mesa, simulating interacting agents, or emergent macro behavior from micro rules. For discrete-event (queueing/process) simulation prefer alterlab-simpy; for reinforcement learning prefer alterlab-stable-baselines3. Part of the AlterLab Academic Skills suite./alterlab-academic-careerPrepares academic career documents and professional-development materials for faculty and researchers. Use when drafting academic CVs, research statements, teaching philosophies, diversity statements, faculty-position cover letters, tenure dossiers, promotion narratives, academic portfolios, or mentorship statements, and when planning conference-networking strategy, building academic web presence, setting up ORCID profiles, or understanding impact metrics. Part of the AlterLab Academic Skills suite.Not loaded · from alterlab-writing-tools
Claude Code won't load this skill
It ships in alterlab-writing-tools at skills/, but Claude Code only loads skills/<name>/SKILL.md and folders listed under skills in plugin.json. Installing the plugin doesn't add it.
Generated from the plugin's indexed repository (alterlab-ieu/alterlab-academic-skills) — no native marketplace selected
npx claudepluginhub p/alterlab-ieu-alterlab-writing-toolsOther plugins' skills for the same job