Логотип Alterlab Pymc

Alterlab Pymc

Спільнота
AlterLab-IEU
alterlab-pymc

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 posteriors and credible intervals, diagnosing divergences, R-hat, or ESS, running probabilistic inference, or comparing models with LOO (WAIC was removed from ArviZ 1.x). Part of the AlterLab Academic Skills suite.

Add to TypingMind

Огляд

ВидавецьAlterLab-IEU
РепозиторійAlterLab-Academic-Skills
Назва навичкиalterlab-pymc
Зірки
84
Форки
16
Файли в пакеті
12
ЛіцензіяApache-2.0
Посилання
  • Інструкції у форматі Markdown

    Файл SKILL.md, який модель завантажує за потреби, тож токени витрачаються лише тоді, коли запит справді відповідає навичці.

  • Працює з будь-якою LLM

    Навички ШІ — це звичайний Markdown, а не код для певного постачальника, тому вони працюють із GPT, Claude, Gemini, Grok або локальною моделлю.

  • Файлів у комплекті: 12

    Скрипти, шаблони й довідкові матеріали, які модель може читати під час роботи. Файли доступні лише для читання й ніколи не виконуються.

  • Відкритий вихідний код

    Видавець на GitHub: AlterLab-IEU. Перед установленням перегляньте вихідні файли навички.

Встановлення

Установіть навичку ШІ Alterlab Pymc у TypingMind, щоб використовувати її з будь-якою LLM, або додайте її до іншого агента, що читає SKILL.md.

1

Встановити в TypingMind

TypingMind встановлює навичку безпосередньо з її папки на GitHub — читає SKILL.md, збирає файли ресурсів у пакет і зберігає результат локально.

  1. Відкрийте застосунок і перейдіть до розділу «Плагіни» → «Навички».
  2. Виберіть «Встановити з GitHub».
  3. Вставте наведений нижче URL папки навички та підтвердьте встановлення.
    https://github.com/AlterLab-IEU/AlterLab-Academic-Skills/tree/main/skills/data-science/alterlab-pymc
  4. Увімкніть навичку в кожному чаті, де хочете її використовувати.
Плагіни → Навички → Додати навичку → За URL GitHub, потім вставте URL папки й натисніть «Продовжити».
2

Встановити в іншому агенті

Будь-який агент, що підтримує формат Agent Skills, може використовувати цю навичку — скопіюйте папку до каталогу навичок цього агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/AlterLab-IEU/AlterLab-Academic-Skills.git /tmp/AlterLab-Academic-Skills
mkdir -p .claude/skills
cp -r /tmp/AlterLab-Academic-Skills/skills/data-science/alterlab-pymc .claude/skills/alterlab-pymc
Після копіювання перезапустіть Claude Code, щоб завантажити нову навичку.

Використовуйте навичку в TypingMind

Увімкніть навичку Alterlab Pymc в будь-якому чаті TypingMind, і далі модель усе зробить сама. Назва й опис навички містяться в системному промпті, а щойно надходить відповідний запит, модель самостійно завантажує повні інструкції — вам не потрібно викликати навичку вручну, і до фактичного використання вона не витрачає токенів.

Модель самостійно завантажує навичку Alterlab Pymc, щойно надходить відповідний запит.

Працює з будь-якою моделлю ШІ

Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для певного постачальника, тому навичка Alterlab Pymc не прив’язана до моделі, для якої її створено. Установіть її один раз у TypingMind і використовуйте з GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama або локальною моделлю, яку ви запускаєте самостійно, — усе з вашими власними ключами API.

  • Завантажується лише за потреби

    Системний промпт містить лише назву й опис. Інструкції завантажуються за першого відповідного запиту, тож поки навичка не потрібна, токени на її інструкції не витрачаються.

  • Змінюйте моделі під час чату

    Оскільки навичка — це інструкції, а не код, зміна моделі не порушує її роботу: наступна модель читає той самий файл SKILL.md.

Інструкції навички

Це вміст файлу SKILL.md, який завантажує модель. Прочитайте його перед установленням — навичка містить інструкції, яких дотримуватиметься ваша модель.

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.

bash
uv pip install "pymc[nutpie]" "arviz[matplotlib,h5netcdf]"   # nutpie sampler, plotting backend, NetCDF I/O

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:

  • 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 with PSIS-LOO cross-validation
  • Implementing uncertainty quantification through Bayesian methods
  • Working with hierarchical/multilevel data structures
  • Handling missing data or measurement error in a principled way

Does NOT Trigger

ScenarioUse Instead
Frequentist regression with p-values, standard errors, and residual diagnosticsalterlab-statsmodels
Reporting-focused mixed-effects model for nested data (lme4/glmmTMB/brms, statsmodels MixedLM, or bambi formulas) with ICC and variance-component reportingalterlab-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

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

  • Compare models with PSIS-LOO (scripts/model_comparison.py); interpret elpd_diff against dse and check Pareto-k. ArviZ 1.x has no WAIC.
  • Sample with NUTS by default (nutpie when installed); 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

  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/)

  • 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 (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().

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

python
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

python
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

python
from scripts.model_diagnostics import check_diagnostics
check_diagnostics(idata)

Model Comparison

python
from scripts.model_comparison import compare_models
compare_models({'m1': idata1, 'm2': idata2})  # PSIS-LOO; higher elpd is better

Predictions

python
# 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 (needs the graphviz package)
  • Save results with idata.to_netcdf('results.nc') (requires h5netcdf or netCDF4, e.g. arviz[h5netcdf]); load with az.from_netcdf('results.nc')
  • For very large models, consider minibatch ADVI or data subsampling

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.

  • Results are an 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).
  • Log-likelihood: call pm.compute_log_likelihood(idata) after sampling. pm.sample(idata_kwargs={"log_likelihood": True}) is deprecated.
  • Sampler: nutpie is the default NUTS sampler when installed (400 tuning steps by default; PyMC's own NUTS keeps 1000). Select explicitly with 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).
  • Backend: PyTensor 3 compiles with Numba by default, so the first call includes JIT-compilation time.
  • Summaries: 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=.
  • Plots return a 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].
  • Model comparison: 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.
  • 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.

Файли в пакеті

Модель читає ці файли за потреби, поки навичку завантажено. Вони доступні для читання й ніколи не виконуються.

Поширені запитання

Що робить навичка ШІ Alterlab Pymc?

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 posteriors and credible intervals, diagnosing divergences, R-hat, or ESS, running probabilistic inference, or comparing models with LOO (WAIC was removed from ArviZ 1.x). Part of the AlterLab Academic Skills suite.

Навіщо використовувати Alterlab Pymc у TypingMind?

Тому що ви встановлюєте її один раз і використовуєте з будь-якою моделлю. Alterlab Pymc — це звичайний Markdown, а не код для конкретного постачальника, тому та сама навичка працює з GPT-5, Claude, Gemini, Grok або локальною моделлю. Ви можете змінити модель навіть посеред чату, і навичка продовжить працювати. TypingMind використовує ваші власні ключі API, тож ви платите безпосередньо постачальникам замість передплати за кожне місце користувача, а ваші навички й чати залишаються у вашому сховищі.

Як встановити Alterlab Pymc у TypingMind?

Відкрийте в TypingMind Плагіни → Навички → Встановити з GitHub і вставте https://github.com/AlterLab-IEU/AlterLab-Academic-Skills/tree/main/skills/data-science/alterlab-pymc. TypingMind прочитає файл SKILL.md, додасть супровідні файли та встановить навичку, яку можна вмикати окремо для кожного чату.

Які моделі ШІ можуть використовувати Alterlab Pymc?

Будь-яка модель, яку ви підключите в TypingMind. Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для конкретного постачальника, тому GPT, Claude, Gemini, Grok і локальні моделі можуть завантажувати цю навичку, коли запит їй відповідає.

Зі скількома моделями ШІ можна використовувати Alterlab Pymc?

Зі скількома забажаєте. У TypingMind ви можете використовувати Alterlab Pymc із будь-якою моделлю, яка підтримує навички, зокрема з GPT, Claude, Gemini, Grok, DeepSeek, Mistral чи Llama. Для цього ви використовуєте власні ключі API.

Чи безкоштовна навичка ШІ Alterlab Pymc?

Так. На GitHub цю навичку публікує AlterLab-IEU за ліцензією Apache-2.0. Ви платите лише своєму постачальнику ШІ за використані токени.

Що таке навички ШІ?

Навичка ШІ — це набір інструкцій для повторного використання, який навчає модель ШІ виконувати одне конкретне завдання. Він відповідає відкритому формату Agent Skills: файл SKILL.md із назвою та описом, а також скрипти, шаблони чи довідкові файли, які можуть знадобитися моделі. Модель читає інструкції лише тоді, коли ваш запит відповідає навичці, тому встановлена навичка нічого не коштує, доки її не використано.

Чим навички ШІ відрізняються від плагінів або серверів MCP?

Плагін або сервер MCP надає моделі нові інструменти, які вона може викликати, — код, який десь виконується й повертає результат. Натомість навичка ШІ дає моделі знання й пояснює порядок дій: як підійти до завдання, яких кроків дотримуватися та яким має бути якісний результат. Навички — це звичайний Markdown, тож їм не потрібні ні сервер, ні ключ API, ні середовище виконання, і вони працюють із будь-якою моделлю.

Усі
Логотип openclaw

Openclaw Test Performance

openclaw
ОрганізаціяПопулярне

Вимірюйте продуктивність, діагностуйте й оптимізуйте час виконання тестів і наборів плагінів OpenClaw, вузькі місця імпорту, CPU/RSS, зростання heap і повільні шляхи покриття тестами.

82.2K
391K
Файлів: 1
Відкрити
Логотип openclaw

Openclaw Testing

openclaw
ОрганізаціяПопулярне

Добирайте пропорційні за обсягом тести й перевірки OpenClaw, діагностуйте помилки та передавайте завдання, чутливі до середовища, або підтвердження для релізу відповідальним особам.

82.2K
391K
Файлів: 2
Відкрити
Логотип openclaw

Release Openclaw Ci

openclaw
ОрганізаціяПопулярне

Запускайте, відстежуйте, налагоджуйте та підсумовуйте повний CI для релізів OpenClaw, перевірки релізів, контрольні перевірки робочих провайдерів, підтвердження встановлення й оновлення та попередні перевірки секретів для релізу.

82.2K
391K
Файлів: 3
Відкрити
Логотип openclaw

Release Openclaw Mac

openclaw
ОрганізаціяПопулярне

Виконуйте підписування релізів OpenClaw для macOS, нотаризацію, оновлення appcast і просування ресурсів або відновлюйте ці процеси.

82.2K
391K
Інструкції
Відкрити

Створіть власний робочий простір зі ШІ вже зараз

Підпишіться на нашу розсилку, щоб дізнаватися про нові функції та майбутні розіграші 👇