본문으로 건너뛰기
Skillpedia
머신러닝33k · #9006

pymc

하는 일

이 스킬은 에이전트에게 PyMC로 베이즈 모델을 만들고 맞추는 방법을 가르칩니다. 계층 모델, 샘플링, 모델 비교를 다룹니다. 불확실성 추정이 필요한 통계학자와 연구자를 위한 스킬입니다.

사용하는 경우

  • ✓베이즈 회귀나 계층 모델을 만들고 싶을 때.
  • ✓발산이나 낮은 유효 표본 크기 같은 샘플링 문제를 점검해야 할 때.
  • ✓LOO나 WAIC로 여러 모델을 비교하고 싶을 때.

스킬 링크

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

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/davila7/claude-code-templates/blob/main/cli-tool/components/skills/scientific/pymc/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“학생 시험 점수를 학교별로 나눈 계층 베이즈 모델을 만들고, 사후 분포에서 샘플링한 뒤 더 간단한 모델과 비교해 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

에이전트는 PyMC로 모델 구조를 정의하고, 샘플러를 실행하며, 진단을 점검합니다. 그다음 정보 기준을 사용해 모델을 비교합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

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',
자주 묻는 질문

어떤 샘플링 방법을 쓰나요?

스킬은 MCMC 샘플링을 위한 NUTS 방법과, 대안으로 변분 추론을 다룹니다.

결과를 어떻게 점검하나요?

스킬은 사후 예측 점검과, 발산 및 유효 표본 크기 같은 진단을 다룹니다.

어떤 모델 비교 방법이 포함되나요?

스킬은 모델 비교를 위한 LOO와 WAIC를 언급합니다.

상세 정보

작성자의 원본 설명

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

인기도

GitHub 스타
33k
순위
#9006
라이선스
MIT
업데이트
2026. 11. 2.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬