Files
2nd/10_Wiki/Topics/AI_and_ML/Monte-Carlo-Methods.md
T
koriweb d8a80f6272 chore(wiki): dangling 링크 canonical 정규화 (768파일/1200건)
이름만 다른(표기 변형) [[위키링크]]를 대상 문서의 canonical 제목으로 치환해
끊겼던 1,200개 링크를 연결. 제목/파일명 정규화 일치만 적용하고 별칭 매칭은
과병합 위험으로 제외(애매성 가드). 원본은 _link_reconcile_backup/ 에 백업.
도구: Datacollect/scripts/link_reconcile_apply.mjs

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 12:24:15 +09:00

7.0 KiB

id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title category status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-monte-carlo-methods Monte Carlo Methods 10_Wiki/Topics verified self
Monte Carlo
MC Method
Stochastic Simulation
MCMC
MCTS
none A 0.95 applied
statistics
simulation
sampling
mcmc
mcts
reinforcement-learning
numerical-methods
2026-05-10 pending
language framework
python numpy-scipy-pymc

한 줄

Monte Carlo는 무작위 표본(random sampling)을 반복 생성하여 결정론적으로 풀기 어려운 적분, 최적화, 확률 분포 추정 문제를 통계적으로 근사하는 계열 방법이다.

핵심

기본 원리

  • 큰 수의 법칙(LLN): 표본 평균은 기대값으로 수렴.
  • 중심극한정리(CLT): 추정 오차는 O(1/sqrt(N))로 줄어든다 — 차원에 무관.
  • 결정론적 quadrature는 차원 d에 대해 O(N^(-k/d)) — Monte Carlo가 고차원에서 유리.

주요 변종

  • 표준 MC 적분: ∫ f(x) p(x) dx ≈ (1/N) Σ f(x_i), x_i ~ p(x).
  • 중요도 표집(Importance Sampling): 효율적인 분포 q에서 샘플링 후 가중치 p(x)/q(x) 보정.
  • MCMC (Markov Chain Monte Carlo): Metropolis-Hastings, Gibbs, HMC, NUTS — 사후분포 샘플링.
  • MCTS (Monte Carlo Tree Search): 게임 트리에서 random playout으로 가치 추정 (AlphaGo).
  • Quasi-MC: 저편차 수열(Sobol, Halton) — 결정론적이지만 균등 분포 우수.
  • Sequential MC (Particle Filter): 시계열 상태 추정.

응용

  • 금융: 옵션 가격 결정 (Black-Scholes 외), VaR.
  • 물리: 통계역학 시뮬레이션, 격자 QCD.
  • 베이지안 통계: 사후분포 추론 (PyMC, Stan, NumPyro).
  • 강화학습: MC return, MCTS (AlphaZero, MuZero).
  • 그래픽스: 경로추적(path tracing), 광역 조명.
  • 공학: 신뢰성 분석, 민감도 분석.

수렴 / 분산 감소

  • Antithetic variates, control variates, stratified sampling, importance sampling.
  • 효율 측정: effective sample size, R-hat (MCMC).

💻 패턴

# 1. π 추정 — 가장 단순한 MC
import numpy as np
N = 1_000_000
x, y = np.random.uniform(-1, 1, (2, N))
pi_est = 4 * np.mean(x**2 + y**2 <= 1)
print(pi_est)  # ~3.1416
# 2. MC 적분 — ∫₀¹ exp(-x²) dx
N = 100_000
samples = np.random.uniform(0, 1, N)
estimate = np.mean(np.exp(-samples**2))
stderr = np.std(np.exp(-samples**2)) / np.sqrt(N)
print(f"{estimate:.5f} ± {1.96*stderr:.5f}")
# 3. 중요도 표집 — heavy tail 분포
def f(x): return np.exp(-x**2 / 2)
# q: 평균 3 정규분포 (target 영역에 집중)
N = 10_000
x = np.random.normal(3, 1, N)
q = lambda x: np.exp(-(x-3)**2/2) / np.sqrt(2*np.pi)
p = lambda x: 1.0 if 2 < x < 4 else 0.0
weights = np.array([p(xi) for xi in x]) / q(x)
estimate = np.mean(f(x) * weights)
# 4. Metropolis-Hastings — 임의 분포 샘플링
def target(x): return np.exp(-x**2/2) * (1 + 0.5*np.sin(5*x))

samples, x = [], 0.0
for _ in range(50_000):
    proposal = x + np.random.normal(0, 1)
    alpha = min(1, target(proposal) / target(x))
    if np.random.rand() < alpha:
        x = proposal
    samples.append(x)
# 5. PyMC — Bayesian 회귀 (NUTS)
import pymc as pm
with pm.Model() as model:
    alpha = pm.Normal("alpha", 0, 10)
    beta = pm.Normal("beta", 0, 10)
    sigma = pm.HalfNormal("sigma", 1)
    mu = alpha + beta * X_data
    y_obs = pm.Normal("y", mu=mu, sigma=sigma, observed=y_data)
    trace = pm.sample(2000, tune=1000, target_accept=0.95)
# 6. MCTS — 간단한 tic-tac-toe selection
class Node:
    def __init__(self, state, parent=None):
        self.state, self.parent = state, parent
        self.children, self.visits, self.wins = [], 0, 0
    def ucb(self, c=1.41):
        if self.visits == 0: return float("inf")
        return self.wins/self.visits + c * np.sqrt(
            np.log(self.parent.visits) / self.visits
        )

def select(node):
    while node.children:
        node = max(node.children, key=lambda n: n.ucb())
    return node
# 7. 옵션 가격 결정 — European call
S0, K, r, sigma, T = 100, 105, 0.05, 0.2, 1.0
N = 100_000
Z = np.random.standard_normal(N)
ST = S0 * np.exp((r - 0.5*sigma**2)*T + sigma*np.sqrt(T)*Z)
payoff = np.maximum(ST - K, 0)
price = np.exp(-r*T) * np.mean(payoff)
print(f"Call price: {price:.2f}")
# 8. Quasi-MC — Sobol sequence
from scipy.stats import qmc
sampler = qmc.Sobol(d=2, scramble=True)
samples = sampler.random(n=4096)
# uniform [0,1]^2 — Monte Carlo 대비 분산 감소
# 9. Particle filter — 1D tracking
N = 1000
particles = np.random.normal(0, 1, N)
weights = np.ones(N) / N
for obs in observations:
    particles += np.random.normal(0, 0.5, N)  # transition
    weights *= np.exp(-(particles - obs)**2 / 2)
    weights /= weights.sum()
    if 1/np.sum(weights**2) < N/2:  # ESS 낮으면 resample
        idx = np.random.choice(N, N, p=weights)
        particles, weights = particles[idx], np.ones(N)/N
# 10. RL — Monte Carlo control (every-visit)
from collections import defaultdict
returns = defaultdict(list)
Q = defaultdict(float)
for episode in episodes:
    G = 0
    for t in reversed(range(len(episode))):
        s, a, r = episode[t]
        G = gamma * G + r
        returns[(s,a)].append(G)
        Q[(s,a)] = np.mean(returns[(s,a)])

결정 기준

문제 추천 방법
저차원 (d < 5) 적분 Quadrature (Gauss-Legendre)
고차원 (d ≥ 5) 적분 Monte Carlo / Quasi-MC
사후분포 샘플링 NUTS (PyMC, Stan, NumPyro)
이산 게임 의사결정 MCTS (UCB1)
이산상태 시계열 추정 Particle Filter
옵션 가격 / 금융 MC + control variate
Heavy tail 추정 Importance Sampling
빠른 수렴 필요 Quasi-MC (Sobol/Halton)

기본값: NumPy np.random + N=10⁵, MCMC는 PyMC NUTS, 게임 트리는 MCTS+UCB1.

🔗 Graph

🤖 LLM 활용

  • LLM이 모델 추론에 MC dropout으로 불확실성 추정.
  • AlphaProof / AlphaGeometry류는 MCTS + LLM 결합.
  • 코드 합성 평가에 pass@k는 본질적으로 Monte Carlo 추정.

안티패턴

  • N이 작은데 표본 평균 신뢰 — 신뢰구간 미산출.
  • MCMC burn-in / convergence diagnostic (R-hat, ESS) 무시.
  • 의사난수 시드 미고정 → 재현 불가.
  • High-dim에서 단순 rejection sampling — 채택률 0에 수렴.
  • 분산 감소 기법 미적용 (control variate 등 무료 점심).

🧪 검증 / 중복

🕓 Changelog

  • Phase 1 (2026-05-08): 초기 생성.
  • Manual cleanup (2026-05-10): canonical 확정, 패턴 10개 정비, MCTS / Quasi-MC / Particle Filter 추가, 결정 기준 표 정리.