[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
+187 -41
View File
@@ -2,65 +2,211 @@
id: wiki-2026-0508-monte-carlo-methods
title: Monte Carlo Methods
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-MCMT-001]
aliases: [Monte Carlo, MC Method, Stochastic Simulation, MCMC, MCTS]
duplicate_of: none
source_trust_level: A
confidence_score: 0.96
tags: [auto-reinforced, monte-carlo, simulation, probability, Statistics, sampling]
confidence_score: 0.95
verification_status: applied
tags: [statistics, simulation, sampling, mcmc, mcts, reinforcement-learning, numerical-methods]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack: { language: python, framework: numpy-scipy-pymc }
---
# [[Monte-Carlo-Methods|Monte-Carlo-Methods]]
## 한 줄
## 📌 한 줄 통찰 (The Karpathy Summary)
> "무작위성으로 찾아내는 정답: 수식이 복잡해 도저히 풀 수 없는 정답을 구하기 위해, 수만 번 주사위를 던지는 것처럼 무작위 샘플링(Sampling)을 반복하고 그 통계적 결과들을 모아 정답 근사치에 도달하는 확률적 요술."
Monte Carlo는 무작위 표본(random sampling)을 반복 생성하여 결정론적으로 풀기 어려운 적분, 최적화, 확률 분포 추정 문제를 통계적으로 근사하는 계열 방법이다.
## 📖 구조화된 지식 (Synthesized Content)
몬테카를로 방법(Monte-Carlo-Methods)은 무작위 추출된 난수를 이용하여 함수의 값을 계산하는 통계적 기법입니다.
## 핵심
1. **동작 원리**:
* 해결하려는 문제를 확률 모델로 변환.
* 엄청난 횟수의 무작위 시뮬레이션 수행.
* 결과값들의 평균이나 분포를 통해 최종해 도출. ([[Inferential-Statistics|Inferential-Statistics]]와 연결)
2. **활용 분야**:
* 복잡한 금융 파생상품 가치 평가, 원자핵 물리 실험 시뮬레이션, 바둑 AI의 수 읽기 등. (Deep Learning (DL)와 연결)
### 기본 원리
- 큰 수의 법칙(LLN): 표본 평균은 기대값으로 수렴.
- 중심극한정리(CLT): 추정 오차는 `O(1/sqrt(N))`로 줄어든다 — 차원에 무관.
- 결정론적 quadrature는 차원 d에 대해 `O(N^(-k/d))` — Monte Carlo가 고차원에서 유리.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 연산 속도 정책 때문에 샘플링 횟수를 제한했으나, 현대 정책은 강력한 컴퓨팅 파워 정책을 바탕으로 수억 번의 시뮬레이션을 돌려 극도의 정밀도 정책을 확보하는 '무차별 대입형 몬테카를로 정책'이 가능해짐(RL Update).
- **정책 변화(RL Update)**: 강화 학습의 핵심인 '몬테카를로 트리 탐색(MCTS)' 정책은 모든 경로를 다 가보는 대신 가망 있는 곳만 무작위로 찔러보며 최적의 수를 찾아냄으로써 알파고 탄생의 결정적 정책 토대가 됨. ([[Markov-Decision-Processes|Markov-Decision-Processes]]와 연결)
### 주요 변종
- **표준 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)**: 시계열 상태 추정.
## 🔗 지식 연결 (Graph)
- [[Inferential-Statistics|Inferential-Statistics]], [[Markov-Decision-Processes|Markov-Decision-Processes]], Deep Learning (DL), [[Optimization|Optimization]], [[Search-Optimization|Search-Optimization]]
- **Modern Tech/Tools**: MCTS (Monte Carlo Tree [[Search|Search]]), Gibbs sampling, Markov Chain Monte Carlo (MCMC).
---
### 응용
- 금융: 옵션 가격 결정 (Black-Scholes 외), VaR.
- 물리: 통계역학 시뮬레이션, 격자 QCD.
- 베이지안 통계: 사후분포 추론 (PyMC, Stan, NumPyro).
- 강화학습: MC return, MCTS (AlphaZero, MuZero).
- 그래픽스: 경로추적(path tracing), 광역 조명.
- 공학: 신뢰성 분석, 민감도 분석.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 수렴 / 분산 감소
- Antithetic variates, control variates, stratified sampling, importance sampling.
- 효율 측정: `effective sample size`, `R-hat` (MCMC).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
```python
# 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
```
## 🧪 검증 상태 (Validation)
```python
# 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}")
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
```python
# 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)
```
## 🧬 중복 검사 (Duplicate Check)
```python
# 4. Metropolis-Hastings — 임의 분포 샘플링
def target(x): return np.exp(-x**2/2) * (1 + 0.5*np.sin(5*x))
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
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)
```
## 🕓 변경 이력 (Changelog)
```python
# 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)
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
```python
# 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
```
```python
# 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}")
```
```python
# 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 대비 분산 감소
```
```python
# 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
```
```python
# 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
- 부모: [[Statistics]], [[Numerical-Methods]], [[Stochastic-Simulation]]
- 형제: [[Bayesian-Inference]], [[Reinforcement-Learning]], [[Variational-Inference]]
- 자식: [[MCMC]], [[MCTS]], [[Particle-Filter]], [[Importance-Sampling]], [[Quasi-Monte-Carlo]]
- 응용: [[AlphaGo]], [[Black-Scholes-Pricing]], [[Path-Tracing]]
## 🤖 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 등 무료 점심).
## 🧪 검증 / 중복
- 표준 적분 결과와 수렴 비교 (예: π).
- MCMC: trace plot, R-hat < 1.01, ESS > 400 권장.
- 별칭 통합: [[Monte-Carlo-Simulation]], [[Stochastic-Simulation]].
## 🕓 Changelog
- Phase 1 (2026-05-08): 초기 생성.
- Manual cleanup (2026-05-10): canonical 확정, 패턴 10개 정비, MCTS / Quasi-MC / Particle Filter 추가, 결정 기준 표 정리.