[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,62 +1,159 @@
|
||||
---
|
||||
id: wiki-2026-0508-markov-chain-monte-carlo
|
||||
title: Markov Chain Monte Carlo
|
||||
title: Markov Chain Monte Carlo (MCMC)
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [MATH-MCMC-001]
|
||||
aliases: [MCMC, Metropolis-Hastings, Gibbs Sampling, HMC, NUTS]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: ["Statistics|[Statistics", math, mcmc, bayesian-inference, sampling, machine-learning]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [bayesian, sampling, mcmc, hmc, pymc, numpyro]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-26
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack: { language: Python, framework: PyMC/NumPyro }
|
||||
---
|
||||
|
||||
# Markov Chain Monte Carlo (MCMC, 마르코프 체인 몬테카를로)
|
||||
# Markov Chain Monte Carlo (MCMC)
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "계산할 수 없는 거대한 확률의 바다를, 무작위의 발걸음(Random Walk)으로 방랑하며 지도를 그려라" — 복잡한 고차원 확률 분포로부터 샘플을 추출하여 기댓값이나 사후 확률(Posterior)을 근사적으로 계산하는 알고리즘 체계.
|
||||
## 매 한 줄
|
||||
> **"매 MCMC = stationary distribution이 target인 chain 만들기"**. 정규화 상수 모르고도 posterior 샘플 가능.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** "Guided Random Sampling" — 단순히 무작위로 점을 찍는 대신, 현재 위치를 기반으로 확률이 높은 곳으로 이동할 가능성을 열어두는 마르코프 체인을 형성하여 타겟 분포에 수렴하게 만드는 지능형 샘플링 패턴.
|
||||
- **핵심 알고리즘:**
|
||||
- **Metropolis-Hastings:** 새로운 상태를 제안하고, 확률 비율에 따라 수락하거나 거절하며 분포 탐색.
|
||||
- **Gibbs Sampling:** 각 변수를 순차적으로 고정하고 조건부 확률에 따라 샘플링 (고차원에서 유리).
|
||||
- **의의:** 베이즈 통계학에서 해석적으로 풀 수 없는 복잡한 적분 문제를 해결 가능케 하여, 현대 데이터 과학과 물리학, AI 추론의 핵심 도구로 자리 잡음.
|
||||
## 매 핵심
|
||||
### 매 알고리즘
|
||||
- **Metropolis-Hastings**: propose q(x'|x), accept α=min(1, π(x')q(x|x')/(π(x)q(x'|x))).
|
||||
- **Random walk MH**: q = Normal(x, σ²). σ가 acceptance 결정.
|
||||
- **Gibbs**: 조건부 p(x_i | x_{-i}) 순차 샘플. conjugate에 강함.
|
||||
- **Slice sampling**: 보조 변수, tuning 적음.
|
||||
- **HMC (Hamiltonian)**: gradient + leapfrog. high-dim 효율.
|
||||
- **NUTS**: HMC trajectory 자동 결정. Stan/PyMC/NumPyro 기본.
|
||||
- **SMC, parallel tempering**: multi-modal에 유리.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 연산 성능의 한계로 이론 속에만 머물던 기법이었으나, 컴퓨팅 파워의 증대와 Hamiltonian Monte Carlo(HMC) 같은 고효율 변종의 등장으로 대규모 데이터 분석의 실전 도구가 됨.
|
||||
- **정책 변화:** Antigravity 프로젝트는 모델의 불확실성(Uncertainty)을 정교하게 측정하거나, 복잡한 지식 그래프의 확률적 잠재 경로를 탐색할 때 MCMC 기반의 시뮬레이션 기법을 고려함.
|
||||
### 매 진단
|
||||
- **Trace plot**: chain 안정성 시각 검사
|
||||
- **R̂ (Gelman-Rubin)**: 다중 chain 수렴, <1.01 권장
|
||||
- **ESS (effective sample size)**: 자기상관 보정 샘플 수
|
||||
- **Energy diagnostic** (HMC): divergent transitions 0 목표
|
||||
- **Posterior predictive check**: model fit
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- Probability-Theory, [[Markov-Decision-Process-MDP|Markov-Decision-Process-MDP]], Bayesian-Networks, [[Global-vs-Local-Optima|Global-vs-Local-Optima]]
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/Markov-Chain-Monte-Carlo.md
|
||||
### 매 응용
|
||||
1. Bayesian posterior 추정 (intractable normalizer)
|
||||
2. Hierarchical models (multilevel regression)
|
||||
3. Latent variable models
|
||||
4. Bayesian deep learning (BNN, variational alternative)
|
||||
5. Phylogenetics, epidemiology
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
## 💻 패턴
|
||||
### Metropolis-Hastings (numpy)
|
||||
```python
|
||||
import numpy as np
|
||||
def mh(log_target, x0, n=10000, step=0.5, rng=np.random.default_rng()):
|
||||
x = np.array(x0, dtype=float); samples = [x.copy()]
|
||||
log_p = log_target(x); accepts = 0
|
||||
for _ in range(n):
|
||||
x_new = x + rng.normal(scale=step, size=x.shape)
|
||||
log_p_new = log_target(x_new)
|
||||
if np.log(rng.uniform()) < log_p_new - log_p:
|
||||
x, log_p = x_new, log_p_new; accepts += 1
|
||||
samples.append(x.copy())
|
||||
return np.array(samples), accepts / n # target ~0.234 (high-d), 0.44 (1d)
|
||||
```
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### Gibbs sampling (bivariate normal)
|
||||
```python
|
||||
def gibbs_bvn(rho, n=10000, rng=np.random.default_rng()):
|
||||
x = y = 0.0; out = np.empty((n, 2))
|
||||
for i in range(n):
|
||||
x = rng.normal(rho * y, np.sqrt(1 - rho**2))
|
||||
y = rng.normal(rho * x, np.sqrt(1 - rho**2))
|
||||
out[i] = (x, y)
|
||||
return out
|
||||
```
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### PyMC (NUTS)
|
||||
```python
|
||||
import pymc as pm, numpy as np
|
||||
y = np.random.normal(2, 1, 100)
|
||||
with pm.Model() as m:
|
||||
mu = pm.Normal("mu", 0, 10)
|
||||
sigma = pm.HalfNormal("sigma", 1)
|
||||
pm.Normal("y", mu, sigma, observed=y)
|
||||
idata = pm.sample(2000, tune=1000, chains=4, target_accept=0.9)
|
||||
print(pm.summary(idata, var_names=["mu", "sigma"])) # r_hat, ess
|
||||
```
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
### NumPyro (JAX, fast)
|
||||
```python
|
||||
import jax, numpyro
|
||||
import numpyro.distributions as dist
|
||||
from numpyro.infer import MCMC, NUTS
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
def model(y):
|
||||
mu = numpyro.sample("mu", dist.Normal(0, 10))
|
||||
sigma = numpyro.sample("sigma", dist.HalfNormal(1))
|
||||
numpyro.sample("obs", dist.Normal(mu, sigma), obs=y)
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
mcmc = MCMC(NUTS(model), num_warmup=1000, num_samples=2000, num_chains=4)
|
||||
mcmc.run(jax.random.PRNGKey(0), y=y)
|
||||
mcmc.print_summary()
|
||||
```
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
### Diagnostics (ArviZ)
|
||||
```python
|
||||
import arviz as az
|
||||
az.plot_trace(idata)
|
||||
az.plot_rank(idata)
|
||||
print(az.rhat(idata).max(), az.ess(idata).min())
|
||||
az.plot_pair(idata, divergences=True)
|
||||
```
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
### 효율 팁
|
||||
```python
|
||||
# 1) Reparameterize (non-centered): theta = mu + sigma * z, z~N(0,1)
|
||||
# 2) target_accept 0.9~0.99 if divergences
|
||||
# 3) 표준화/스케일링 → leapfrog 안정
|
||||
# 4) Initial values: pm.find_MAP() or jitter+adapt_diag
|
||||
```
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
## 매 결정 기준
|
||||
| 상황 | Sampler |
|
||||
|---|---|
|
||||
| Low-dim, custom posterior | MH (간단) |
|
||||
| Conjugate hierarchical | Gibbs |
|
||||
| Continuous, gradient 가능 | NUTS/HMC |
|
||||
| Discrete latent | MH within Gibbs, SMC |
|
||||
| Multi-modal | Parallel tempering, SMC |
|
||||
| 대용량 / GPU | NumPyro (JAX), BlackJAX |
|
||||
| 빠른 prod 근사 | VI (대안), Laplace |
|
||||
|
||||
**기본값**: continuous → NumPyro/PyMC NUTS. Discrete → Gibbs / SMC.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Bayesian-Inference]], [[Sampling-Methods]]
|
||||
- 변형: [[Metropolis-Hastings]], [[Gibbs-Sampling]], [[Hamiltonian-Monte-Carlo]], [[NUTS]]
|
||||
- 응용: [[Hierarchical-Models]], [[Bayesian-Regression]], [[Probabilistic-Programming]]
|
||||
- Adjacent: [[Variational-Inference]], [[Importance-Sampling]], [[ArviZ]], [[Stan]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 모델 작성, sampler 선택, divergence 진단 가이드.
|
||||
**언제 X**: 복잡 hierarchical model 검증은 도메인 전문가 + posterior predictive.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- Centered hierarchical에 NUTS 그대로 (divergences) → non-centered
|
||||
- Single chain → R̂ 불가, 수렴 진단 X
|
||||
- Burn-in/warmup 무시
|
||||
- Acceptance rate 99% (step 너무 작음) or 1% (너무 큼)
|
||||
- Trace plot 안 보고 mean만 신뢰
|
||||
- VI로 충분한데 MCMC 돌리기 (시간 낭비)
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Gelman BDA3, Neal HMC review, Hoffman NUTS, PyMC/NumPyro docs). 신뢰도 A.
|
||||
- 중복: 없음.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — PyMC/NumPyro 패턴, ArviZ diagnostic |
|
||||
|
||||
Reference in New Issue
Block a user