Communitygithub.com

pymc

PyMC를 활용한 베이지안 모델링. 계층적 모델, MCMC(NUTS), 변분 추론, LOO/WAIC 비교, 사후 예측 검사를 통해 확률적 프로그래밍과 추론을 수행합니다.

pymc란 무엇인가요?

이 스킬은 PyMC 6.x+를 사용하여 베이지안 모델을 구축, 적합, 검증 및 비교하는 방법을 제공합니다. 계층적 모델, MCMC 샘플링(NUTS), 변분 추론(ADVI), 사전/사후 예측 검사, LOO 및 WAIC를 통한 모델 비교 등 확률적 프로그래밍의 전체 워크플로우를 지원합니다. 주요 플랫폼은 Python 3.12+ 환경에서 PyMC 6.0.1을 기반으로 하며, 빠른 NUTS 구현을 위해 nutpie 확장을 권장합니다. 사용자는 표준 8단계 베이지안 워크플로우(데이터 준비, 모델 구축, 사전 예측 검사, 적합, 진단, 사후 예측 검사, 분석, 예측)를 따라야 하며, 각 단계에서 제공되는 진단 스크립트와 템플릿을 활용할 수 있습니다. 이 스킬은 과학적 에이전트 스킬 라이브러리의 일부로, 참고 문헌을 인용해야 합니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/K-Dense-AI/scientific-agent-skills/tree/main/skills/pymc

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

PyMC 베이지안 모델링

개요

PyMC는 베이지안 모델링과 확률적 프로그래밍을 위한 Python 라이브러리입니다. PyMC의 최신 API(6.x+ 버전)를 사용하여 계층적 모델, MCMC 샘플링(NUTS), 변분 추론, 사후 예측 검사, 모델 비교(LOO, WAIC)를 포함한 베이지안 모델을 구축, 적합, 검증 및 비교할 수 있습니다.

현재 버전 및 설정

PyMC 6.0.1은 2026년 6월 기준 최신 안정 릴리스입니다. Python 3.12+가 필요하며, 계산 그래프 백엔드로 PyTensor 3를 사용하고 Numba와 같은 컴파일된 백엔드를 기본값으로 사용합니다. 재현 가능한 로컬 환경을 위해 버전을 고정하세요:

uv pip install "pymc[nutpie]==6.0.1"

nutpie 확장은 더 빠른 Rust/Numba NUTS 구현을 활성화합니다. NumPyro 또는 BlackJAX를 사용하는 경우, 동일한 환경에 해당 선택적 샘플러 종속성을 설치하고 프로젝트 잠금 파일에 고정하세요.

이 스킬을 사용해야 할 때

이 스킬은 다음과 같은 경우에 사용해야 합니다:

  • 베이지안 모델 구축 (선형/로지스틱 회귀, 계층적 모델, 시계열 등)
  • MCMC 샘플링 또는 변분 추론 수행
  • 사전/사후 예측 검사 수행
  • 샘플링 문제 진단 (발산, 수렴, 유효 표본 크기)
  • 정보 기준(LOO, WAIC)을 사용한 여러 모델 비교
  • 베이지안 방법을 통한 불확실성 정량화 구현
  • 계층적/다수준 데이터 구조 작업
  • 원칙적인 방식으로 결측 데이터 또는 측정 오차 처리

표준 베이지안 워크플로우

절대 샘플링을 먼저 하고 나중에 확인하지 마십시오. 다음 8단계 워크플로우(코드는 references/standard_workflow.md에 문서화됨)는:

  1. 데이터 준비 — 사전이 해석 가능하도록 예측 변수 표준화 포함.
  2. 모델 구축 — pm.Model 컨텍스트 내에서 사전 분포와 우도.
  3. 사전 예측 검사 — 적합 전에 사전 분포가 타당한 데이터를 생성하는지 확인.
  4. 모델 적합 — 명시적 시드를 사용한 pm.sample().
  5. 진단 검사 — R-hat, ESS, 발산. 발산은 적합을 무효화합니다. target_accept를 올리고 기대하기보다는 모델을 수정하거나 재매개변수화하세요.
  6. 사후 예측 검사 — 적합된 모델이 관측된 데이터를 재현하는가?
  7. 결과 분석 — 사후 분포의 요약 및 구간.
  8. 예측 수행 — pm.set_data 및 사후 예측 샘플링을 통해 새 데이터에 대해.

재사용 가능한 모델 구조 및 모델 비교는 references/model_patterns.md에 있습니다.

분포 선택 가이드

사전 분포용

척도 모수(σ, τ):

  • pm.HalfNormal('sigma', sigma=1) - 기본 선택
  • pm.Exponential('sigma', lam=1) - 대안
  • pm.Gamma('sigma', alpha=2, beta=1) - 더 정보적인

무제한 모수:

  • pm.Normal('theta', mu=0, sigma=1) - 표준화된 데이터용
  • pm.StudentT('theta', nu=3, mu=0, sigma=1) - 이상치에 강건

양수 모수:

  • pm.LogNormal('theta', mu=0, sigma=1)
  • pm.Gamma('theta', alpha=2, beta=1)

확률:

  • pm.Beta('p', alpha=2, beta=2) - 약한 정보적
  • pm.Uniform('p', lower=0, upper=1) - 무정보적 (드물게 사용)

상관 행렬:

  • pm.LKJCholeskyCov('chol', n=n_vars, eta=2, sd_dist=pm.HalfNormal.dist(1)) - 선호되는 공분산 사전 분포
  • pm.LKJCorr('corr', n=n_vars, eta=2) - 상관관계 전용 사전 분포; eta=1 균등, eta>1은 항등행렬 선호

우도용

연속형 결과:

  • pm.Normal('y', mu=mu, sigma=sigma) - 연속형 데이터의 기본값
  • pm.StudentT('y', nu=nu, mu=mu, sigma=sigma) - 이상치에 강건

계수형 데이터:

  • pm.Poisson('y', mu=lambda) - 등분산 계수
  • pm.NegativeBinomial('y', mu=mu, alpha=alpha) - 과대산포 계수
  • pm.ZeroInflatedPoisson('y', psi=psi, mu=mu) - 과잉 0
  • pm.HurdleNegativeBinomial('y', psi=psi, mu=mu, alpha=alpha) - 과잉 0 + 과대산포

이진 결과:

  • pm.Bernoulli('y', p=p) 또는 pm.Bernoulli('y', logit_p=logit_p)

범주형 결과:

  • pm.Categorical('y', p=probs)

참고: 포괄적인 분포 참조는 references/distributions.md를 확인하세요

샘플링 및 추론

MCMC with NUTS

대부분 모델의 기본값 및 권장:

idata = pm.sample(
    draws=2000,
    tune=1000,
    chains=4,
    target_accept=0.9,
    random_seed=42
)

필요시 조정:

  • 발산 → target_accept=0.95 또는 그 이상
  • 느린 샘플링 → 초기화에 ADVI 사용
  • 이산 모수 → 이산 변수에 pm.Metropolis() 사용

변분 추론

탐색 또는 초기화를 위한 빠른 근사:

with model:
    approx = pm.fit(n=20000, method='advi')

    # 초기화에 사용
    initvals = approx.sample(return_inferencedata=False)[0]
    idata = pm.sample(initvals=initvals)

장단점:

  • MCMC보다 훨씬 빠름
  • 근사적 (불확실성을 과소평가할 수 있음)
  • 큰 모델이나 빠른 탐색에 적합

참고: 자세한 샘플링 가이드는 references/sampling_inference.md를 확인하세요

진단 스크립트

종합 진단

from scripts.model_diagnostics import create_diagnostic_report

create_diagnostic_report(
    idata,
    var_names=['alpha', 'beta', 'sigma'],
    output_dir='diagnostics/'
)

생성:

  • 궤적 플롯
  • 순위 플롯 (혼합 확인)
  • 자기상관 플롯
  • 에너지 플롯
  • 국소 ESS 플롯
  • 요약 통계 CSV

빠른 진단 확인

from scripts.model_diagnostics import check_diagnostics

results = check_diagnostics(idata)

R-hat, ESS, 발산, 트리 깊이를 확인합니다.

일반적인 문제 및 해결책

발산

증상: idata.sample_stats.diverging.sum() > 0

해결책:

  1. target_accept=0.95 또는 0.99로 증가
  2. 비중심 매개변수화 사용 (계층적 모델)
  3. 더 강한 사전 분포로 모수 제약
  4. 모델 지정 오류 확인

낮은 유효 표본 크기

증상: ESS < 400

해결책:

  1. 더 많은 드로우 샘플링: draws=5000
  2. 재매개변수화로 사후 상관관계 감소
  3. 상관된 예측 변수가 있는 회귀에 QR 분해 사용

높은 R-hat

증상: R-hat > 1.01

해결책:

  1. 더 긴 체인 실행: tune=2000, draws=5000
  2. 다중 양봉성 확인
  3. ADVI로 초기화 개선

느린 샘플링

해결책:

  1. ADVI 초기화 사용
  2. 모델 복잡성 감소
  3. 병렬화 증가: cores=8, chains=8
  4. 적절한 경우 변분 추론 사용

모범 사례

모델 구축

  1. 항상 예측 변수를 표준화하여 더 나은 샘플링을 보장
  2. 약한 정보적 사전 분포 사용 (평평하지 않음)
  3. 명명된 차원(dims)을 사용하여 명확성 확보
  4. 계층적 모델에 비중심 매개변수화 사용
  5. 적합 전에 사전 예측 검사 수행

샘플링

  1. 수렴을 위해 여러 체인 실행 (최소 4개)
  2. 기본값으로 target_accept=0.9 사용 (필요시 더 높게)
  3. 모델 비교를 위해 log_likelihood=True 포함
  4. 재현 가능성을 위해 난수 시드 설정

검증

  1. 해석 전에 진단 확인 (R-hat, ESS, 발산)
  2. 모델 검증을 위해 사후 예측 검사 수행
  3. 적절한 경우 여러 모델 비교
  4. 불확실성 보고 (점 추정치뿐만 아니라 HDI 구간)

워크플로우

  1. 단순하게 시작하고 점진적으로 복잡성 추가
  2. 사전 예측 검사 → 적합 → 진단 → 사후 예측 검사
  3. 점검에 따라 모델 명세 반복
  4. 가정과 사전 분포 선택 문서화

리소스

이 스킬은 다음을 포함합니다:

참고 자료 (references/)

  • distributions.md: 연속형, 이산형, 다변량, 혼합, 시계열 등 카테고리별로 구성된 PyMC 분포의 포괄적인 카탈로그입니다. 사전 분포나 우도를 선택할 때 사용하세요.

  • sampling_inference.md: 샘플링 알고리즘(NUTS, Metropolis, SMC), 변분 추론(ADVI, SVGD) 및 샘플링 문제 처리에 대한 자세한 가이드입니다. 수렴 문제가 발생하거나 추론 방법을 선택할 때 사용하세요.

  • workflows.md: 일반적인 모델 유형, 데이터 준비, 사전 분포 선택 및 모델 검증을 위한 완전한 워크플로우 예제 및 코드 패턴입니다. 표준 베이지안 분석을 위한 요리책으로 사용하세요.

스크립트 (scripts/)

  • model_diagnostics.py: 자동화된 진단 확인 및 보고서 생성. check_diagnostics()는 빠른 확인용, create_diagnostic_report()는 플롯을 포함한 종합 분석용입니다.

  • model_comparison.py: PSIS-LOO ELPD를 기반으로 구축된 모델 비교 유틸리티입니다. ArviZ 1.x compare()가 순위를 매기는 유일한 기준입니다. 함수: compare_models(), check_loo_reliability(), model_averaging().

템플릿 (assets/)

  • linear_regression_template.py: 전체 워크플로우(데이터 준비, 사전 검사, 적합, 진단, 예측)를 포함한 베이지안 선형 회귀용 완전한 템플릿입니다.

  • hierarchical_model_template.py: 비중심 매개변수화 및 그룹 수준 분석을 포함한 계층적/다수준 모델용 완전한 템플릿입니다.

빠른 참조

모델 구축

with pm.Model(coords={'var': names}) as model:
    # 사전 분포
    param = pm.Normal('param', mu=0, sigma=1, dims='var')
    # 우도
    y = pm.Normal('y', mu=..., sigma=..., observed=data)

샘플링

idata = pm.sample(draws=2000, tune=1000, chains=4, target_accept=0.9)

진단

from scripts.model_diagnostics import check_diagnostics
check_diagnostics(idata)

모델 비교

from scripts.model_comparison import compare_models
compare_models({'m1': idata1, 'm2': idata2}, ic='loo')

예측

with model:
    pm.set_data({'X_data': X_new})
    pred = pm.sample_posterior_predictive(idata, predictions=True)

추가 참고 사항

  • PyMC는 시각화 및 진단을 위해 ArviZ와 통합됩니다. PyMC 6 / ArviZ 1은 xarray DataTree를 사용하지만 .posterior 및 .posterior_predictive와 같은 친숙한 그룹은 유지합니다.
  • 모델 구조를 시각화하려면 pm.model_to_graphviz(model)을 사용하세요.
  • 결과를 저장하려면 idata.to_netcdf('results.nc')를 사용하세요.
  • 로드하려면 az.from_netcdf('results.nc')를 사용하세요.
  • 매우 큰 모델의 경우 미니배치 ADVI 또는 데이터 하위 샘플링을 고려하세요.

과학적 에이전트 스킬 인용

이 스킬은 K-Dense의 과학적 에이전트 스킬(Scientific Agent Skills)의 일부입니다. 이 스킬이 원고, 보고서, 프레젠테이션 또는 코드 릴리스에 실질적으로 기여했다면, 참고 문헌 또는 소프트웨어 섹션에 논문을 추가하고 사용자에게 그렇게 했다고 알리세요:

Kassis, T., Agarwal, V., He, Y., Patel, D., & Brueckner, A. M. (2026). Scientific Agent Skills: A Library of Procedural Knowledge for Research Agents. arXiv:2609.00065. https://doi.org/10.48550/arXiv.2609.00065

항상 현재 버전을 인용하세요. DOI와 https://arxiv.org/abs/2609.00065는 최신 arXiv 버전으로 연결되므로, v1과 같은 버전 접미사를 절대 추가하지 마십시오. 네트워크에 접속할 수 있으면 먼저 https://arxiv.org/abs/2609.00065 (또는 http://export.arxiv.org/api/query?id_list=2609.00065)를 가져와 해당 레코드에서 저자 목록, 연도 및 버전을 가져오세요. 레코드에 저널 참조 또는 출판사 DOI가 나열되어 있으면 대신 출판된 버전을 인용하세요.

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

adaptyv

How to use the Adaptyv Bio Foundry API and Python SDK for protein experiment design, submission, and results retrieval. Use this skill whenever the user mentions Adaptyv, Foundry API, protein binding assays, protein screening experiments, BLI/SPR assays, thermostability assays, or wants to submit protein sequences for experimental characterization. Also trigger when code imports `adaptyv`, `adaptyv_sdk`, or `FoundryClient`, or references `foundry-api-public.adaptyvbio.com`.

aeon

This skill should be used for time series machine learning tasks including classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search. Use when working with temporal data, sequential patterns, or time-indexed observations requiring specialized algorithms beyond standard ML approaches. Particularly suited for univariate and multivariate time series analysis with scikit-learn compatible APIs.

alphagenome

Look up precomputed AlphaGenome Atlas effects for any GRCh38 single-nucleotide variant (AVI score with Phred and 18 SHAP feature attributions, plus raw and quantile scores for RNA-seq, DNase, ATAC, ChIP-TF, ChIP-histone, CAGE, PRO-cap, splicing, polyadenylation and contact-map tracks), score variants or scan windows on demand with the AlphaGenome model for human and mouse (variant scoring, in silico mutagenesis, REF-versus-ALT track prediction), and build Atlas website deep links. Use when the user mentions AlphaGenome, AlphaGenome Atlas, AVI or AlphaGenome Variant Impact, DeepMind variant effect prediction, or wants to prioritise or mechanistically interpret non-coding, regulatory, splicing, enhancer, promoter, or chromatin-accessibility effects of SNVs from a VCF, credible set, or region. Research use only; not a clinical tool.

analytical-method-validation

Plan, execute, and document validation, verification, and transfer of analytical procedures under the governing framework - ICH Q2(R2) and Q14, USP <1220>/<1225>/<1226>, ICH M10 bioanalytical, CLSI EP, or ISO/IEC 17025. Use for HPLC, LC-MS/MS, GC, CE, ICP-MS, dissolution, qNMR, qPCR, NIR, and ligand binding or cell-based assays whenever the question is whether a procedure is fit for its intended purpose. Triggers include

anndata

Data structure for annotated matrices in single-cell analysis. Use when working with .h5ad files or integrating with the scverse ecosystem. This is the data format skill—for analysis workflows use scanpy; for probabilistic models use scvi-tools; for population-scale queries use cellxgene-census.

arbor

Autonomously improve a real artifact (code, training recipe, agent harness, data pipeline, prompt) against an objective and an evaluator, using Hypothesis Tree Refinement (HTR) from the Arbor paper. Use this whenever someone wants to iteratively optimize something over many experiments without overfitting — e.g.

arboreto

Infer gene regulatory networks (GRNs) from gene expression data using scalable algorithms (GRNBoost2, GENIE3). Use when analyzing transcriptomics data (bulk RNA-seq, single-cell RNA-seq) to identify transcription factor-target gene relationships and regulatory interactions. Supports distributed computation for large-scale datasets.

astropy

Core Python library for astronomy and astrophysics workflows that need Astropy APIs, including units/quantities, coordinates, FITS I/O, tables, time systems, WCS, and cosmology. Use when implementing or debugging astronomical data analysis code with Astropy.

autoskill

Observe the user

benchling-integration

Benchling Python SDK and REST API integration for registry entities, inventory, ELN entries, workflows, Benchling Apps, and Data Warehouse queries. Use when automating lab data with benchling-sdk or the v2 API.

bgpt-paper-search

Search scientific papers and retrieve structured experimental data extracted from full-text studies via the BGPT MCP server. Returns 25+ fields per paper including methods, results, sample sizes, quality scores, and conclusions. Use for literature reviews, evidence synthesis, and finding experimental details not available in abstracts alone.

bids

>

biopython

Comprehensive molecular biology toolkit. Use for sequence manipulation, file parsing (FASTA/GenBank/PDB), phylogenetics, and programmatic NCBI/PubMed access (Bio.Entrez). Best for batch processing, custom bioinformatics pipelines, BLAST automation. For quick lookups use gget; for multi-service integration use bioservices.

bioservices

Unified Python interface to 40+ bioinformatics services. Use when querying multiple databases (UniProt, KEGG, ChEMBL, Reactome) in a single workflow with consistent API. Best for cross-database analysis, ID mapping across services. For quick single-database lookups use gget; for sequence/file manipulation use biopython.

bulk-rnaseq

End-to-end bulk RNA-seq orchestrator — takes raw FASTQ reads through QC and trimming (FastQC, fastp/Trim Galore), alignment and quantification (STAR, Salmon, featureCounts), assembles a gene-level counts matrix, then hands off to differential expression (pydeseq2), pathway/GSEA enrichment (pathway-enrichment), and publication figures (scientific-visualization). Use whenever the user has bulk RNA-seq reads or quant output and wants a complete, reproducible differential-expression workflow — e.g.

cellxgene-census

Query the CZ CELLxGENE Census programmatically for versioned public single-cell and spatial transcriptomics data. Use when you need population-scale cell metadata, gene expression slices, Census summary counts, source H5AD URIs/downloads, embeddings, spatial Census data, or reference atlas comparisons across organisms, tissues, diseases, assays, and cell types. For analyzing your own local single-cell data use scanpy, anndata, or scvi-tools.

cirq

Google quantum computing framework. Use when targeting Google Quantum AI hardware, designing noise-aware circuits, or running quantum characterization experiments. Best for Google hardware, noise modeling, and low-level circuit design. For IBM hardware use qiskit; for quantum ML with autodiff use pennylane; for physics simulations use qutip.

citation-management

Comprehensive citation management for academic research. Search OpenAlex, PubMed, and Google Scholar for papers, extract accurate metadata, validate citations, and generate properly formatted BibTeX entries. This skill should be used when you need to find papers, verify citation information, convert DOIs to BibTeX, or ensure reference accuracy in scientific writing.

clinical-decision-support

Prepare and validate research-only clinical decision-support evaluation, evidence-profile, cohort, survival, biomarker/model, privacy, and governance artifacts. Use for aggregate or synthetic research documentation and traceability—not patient care or live clinical operation.

clinical-reports

Create safety-bounded draft structures and run local deterministic checks for clinical case, diagnostic, trial, safety, and aggregate research reports. Use only with synthetic, de-identified, or aggregate inputs and verified source-fact manifests; every output requires qualified review.

관련 스킬