Chuyển đến nội dung
Skillpedia
Học máy33k · #9006

pymc

Skill này làm gì

Skill này dạy agent của bạn xây dựng và khớp mô hình Bayes bằng PyMC. Nó bao gồm mô hình phân cấp, lấy mẫu và so sánh mô hình. Skill dành cho nhà thống kê và nhà nghiên cứu cần ước lượng độ không chắc chắn.

Khi nào nên dùng

  • ✓Khi bạn muốn xây dựng mô hình hồi quy Bayes hoặc mô hình phân cấp.
  • ✓Khi bạn cần kiểm tra các vấn đề lấy mẫu như phân kỳ hoặc kích thước mẫu hiệu dụng thấp.
  • ✓Khi bạn muốn so sánh nhiều mô hình bằng LOO hoặc WAIC.

Liên kết skill

https://github.com/davila7/claude-code-templates/blob/main/cli-tool/components/skills/scientific/pymc/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/davila7/claude-code-templates/blob/main/cli-tool/components/skills/scientific/pymc/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Xây dựng mô hình Bayes phân cấp về điểm kiểm tra của học sinh theo trường, lấy mẫu từ hậu nghiệm, và so sánh với một mô hình đơn giản hơn.”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Agent định nghĩa cấu trúc mô hình trong PyMC, chạy bộ lấy mẫu và kiểm tra chẩn đoán. Sau đó nó so sánh các mô hình bằng tiêu chí thông tin.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

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 workflow for building and validating Bayesian models:

1. Data Preparation

import pymc as pm
import arviz as az
import numpy as np

# Load and prepare data
X = ...  # Predictors
y = ...  # Outcomes

# Standardize predictors for better sampling
X_mean = X.mean(axis=0)
X_std = X.std(axis=0)
X_scaled = (X - X_mean) / X_std

Key practices:

  • Standardize continuous predictors (improves sampling efficiency)
  • Center outcomes when possible
  • Handle missing data explicitly (treat as parameters)
  • Use named dimensions with coords for clarity

2. Model Building

coords = {
    'predictors': ['var1', 'var2', 'var3'],
    'obs_id': np.arange(len(y))
}

with pm.Model(coords=coords) as model:
    # Priors
    alpha = pm.Normal('alpha', mu=0, sigma=1)
    beta = pm.Normal('beta', mu=0, sigma=1, dims='predictors')
    sigma = pm.HalfNormal('sigma', sigma=1)

    # Linear predictor
    mu = alpha + pm.math.dot(X_scaled, beta)

    # Likelihood
    y_obs = pm.Normal('y_obs', mu=mu, sigma=sigma, observed=y, dims='obs_id')

Key practices:

  • Use weakly informative priors (not flat priors)
  • Use HalfNormal or Exponential for scale parameters
  • Use named dimensions (dims) instead of shape when possible
  • Use pm.Data() for values that will be updated for predictions

3. Prior Predictive Check

Always validate priors before fitting:

with model:
    prior_pred = pm.sample_prior_predictive(samples=1000, random_seed=42)

# Visualize
az.plot_ppc(prior_pred, group='prior')

Check:

  • Do prior predictions span reasonable values?
  • Are extreme values plausible given domain knowledge?
  • If priors generate implausible data, adjust and re-check

4. Fit Model

with model:
    # Optional: Quick exploration with ADVI
    # approx = pm.fit(n=20000)

    # Full MCMC inference
    idata = pm.sample(
        draws=2000,
        tune=1000,
        chains=4,
        target_accept=0.9,
        random_seed=42,
        idata_kwargs={'log_likelihood': True}  # For model comparison
    )

Key parameters:

  • draws=2000: Number of samples per chain
  • tune=1000: Warmup samples (discarded)
  • chains=4: Run 4 chains for convergence checking
  • target_accept=0.9: Higher for difficult posteriors (0.95-0.99)
  • Include log_likelihood=True for model comparison

5. Check Diagnostics

Use the diagnostic script:

from scripts.model_diagnostics import check_diagnostics

results = check_diagnostics(idata, var_names=['alpha', 'beta', 'sigma'])

Check:

  • R-hat < 1.01: Chains have converged
  • ESS > 400: Sufficient effective samples
  • No divergences: NUTS sampled successfully
  • Trace plots: Chains should mix well (fuzzy caterpillar)

If issues arise:

  • Divergences → Increase target_accept=0.95, use non-centered parameterization
  • Low ESS → Sample more draws, reparameterize to reduce correlation
  • High R-hat → Run longer, check for multimodality

6. Posterior Predictive Check

Validate model fit:

with model:
    pm.sample_posterior_predictive(idata, extend_inferencedata=True, random_seed=42)

# Visualize
az.plot_ppc(idata)

Check:

  • Do posterior predictions capture observed data patterns?
  • Are systematic deviations evident (model misspecification)?
  • Consider alternative models if fit is poor

7. Analyze Results

# Summary statistics
print(az.summary(idata, var_names=['alpha', 'beta', 'sigma']))

# Posterior distributions
az.plot_posterior(idata, var_names=['alpha', 'beta',
Câu hỏi thường gặp

Nó dùng phương pháp lấy mẫu nào?

Skill bao gồm phương pháp NUTS cho lấy mẫu MCMC và suy diễn biến phân như một lựa chọn thay thế.

Nó kiểm tra kết quả như thế nào?

Skill bao gồm kiểm tra dự đoán hậu nghiệm và các chẩn đoán như phân kỳ và kích thước mẫu hiệu dụng.

Những phương pháp so sánh mô hình nào được bao gồm?

Skill đề cập đến LOO và WAIC để so sánh mô hình.

Chi tiết

Mô tả gốc của tác giả

Bayesian modeling with PyMC. Build hierarchical models, MCMC (NUTS), variational inference, LOO/WAIC comparison, posterior checks, for probabilistic programming and inference.

repo: davila7/claude-code-templates

Độ phổ biến

Sao GitHub
33k
Vị trí xếp hạng
#9006
Giấy phép
MIT
Cập nhật
2/11/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự