--- id: wiki-2026-0508-markov-chains title: Markov Chains category: 10_Wiki/Topics status: verified canonical_id: self aliases: [Markov Chain, MC, Markov Process, Discrete-Time Markov Chain, DTMC] duplicate_of: none source_trust_level: A confidence_score: 0.95 verification_status: applied tags: [probability, stochastic-process, markov, mcmc, hmm, pagerank, statistics] raw_sources: [] last_reinforced: 2026-05-10 github_commit: pending tech_stack: { language: python, framework: numpy|scipy|pymc } --- # Markov Chains > 한 줄: "미래는 현재에만 의존" (memoryless) — 상태 전이 확률 행렬로 표현되는 확률 과정. PageRank·MCMC·HMM의 수학적 토대. ## 핵심 - **Markov property**: P(X_{t+1} | X_t, X_{t-1}, ...) = P(X_{t+1} | X_t). 과거 무관, 현재만. - **Transition matrix P**: 행 합 = 1 (right stochastic). P[i][j] = i→j 확률. - **Stationary distribution π**: πP = π. 충분히 오래 돌리면 수렴하는 분포 (ergodic 가정). - **분류**: irreducible (모든 상태 도달), aperiodic (주기 없음), recurrent vs transient. 둘 다 만족 → ergodic → unique π. - **Continuous-time (CTMC)**: rate matrix Q, e^{Qt}로 t-step 분포. queueing/생존분석. ## 결정 기준 | 문제 | 도구 | 비고 | |---|---|---| | 정상 분포 계산 | π = left eigenvector of P (eigval=1) | `scipy.linalg.eig` | | 큰 sparse P | power iteration | PageRank 방식 | | 사후분포 샘플링 | MCMC (Metropolis-Hastings, Gibbs) | PyMC, Stan, NumPyro | | 숨은 상태 추론 | HMM (Forward-Backward, Viterbi) | hmmlearn | | 강화학습 | MDP (action 추가) | gymnasium, stable-baselines3 | | 시퀀스 생성(텍스트) | n-gram MC | 단순 baseline, LLM에 밀림 | ## 💻 패턴 ### Transition matrix & 정상 분포 ```python import numpy as np P = np.array([[0.7, 0.2, 0.1], [0.3, 0.4, 0.3], [0.2, 0.3, 0.5]]) # Method 1: eigenvector w, v = np.linalg.eig(P.T) pi = np.real(v[:, np.isclose(w, 1)].flatten()); pi /= pi.sum() # Method 2: power iteration (sparse-friendly) x = np.ones(3) / 3 for _ in range(1000): x = x @ P print(pi, x) # 동일 ``` ### Simulation ```python def simulate(P, x0, T, rng=np.random.default_rng(0)): states = [x0] for _ in range(T): states.append(rng.choice(len(P), p=P[states[-1]])) return states ``` ### PageRank ```python def pagerank(M, d=0.85, tol=1e-8): n = M.shape[0] r = np.ones(n) / n teleport = np.ones(n) / n while True: r_new = d * (M.T @ r) + (1 - d) * teleport if np.linalg.norm(r_new - r, 1) < tol: return r_new r = r_new ``` ### Metropolis-Hastings (MCMC) ```python def metropolis(log_p, x0, n=10000, sigma=1.0, rng=np.random.default_rng()): samples = [x0]; x = x0 for _ in range(n): x_prop = x + rng.normal(scale=sigma) if np.log(rng.random()) < log_p(x_prop) - log_p(x): x = x_prop samples.append(x) return np.array(samples) ``` ### Hidden Markov Model ```python from hmmlearn import hmm model = hmm.GaussianHMM(n_components=3, covariance_type="diag", n_iter=100) model.fit(X) # Baum-Welch states = model.predict(X) # Viterbi log_prob = model.score(X) # Forward ``` ### Mean first passage time ```python def mean_first_passage(P, target): n = len(P); Q = np.delete(np.delete(P, target, 0), target, 1) return np.linalg.solve(np.eye(n-1) - Q, np.ones(n-1)) ``` ## 🔗 Graph - 상위: [[Probability]] - 관련: [[MCMC]] · [[MDP]] · [[Reinforcement-Learning]] · [[Bayesian-Inference]] ## 🤖 LLM 활용 - LLM에게 transition matrix 입력 → 정상 분포·mixing time 해석 부탁 가능. 단, 수치 계산은 NumPy로 검증. - "내 도메인 문제를 MC로 모델링 가능한가?" 프레이밍에 LLM 유용 (state space 설계). ## ❌ 안티패턴 - **Markov property 위반 데이터에 MC 적용** — 장기 의존 → HMM/RNN/Transformer 고려. - **Ergodicity 미확인 정상 분포** — reducible/주기 그래프에 π 가정 → 무의미. - **MCMC chain 1개로 수렴 판정** — R-hat (Gelman-Rubin) 다중 chain으로 확인. - **n-gram으로 자연어 생성 시도** — LLM 시대에 baseline 외 의미 적음. - **희소 상태 dense matrix** — 100k+ 상태는 `scipy.sparse` 필수. ## 🧪 검증 / 중복 - 중복 후보: [[MCMC]], [[Hidden-Markov-Models]], [[PageRank]] — 각각 응용 페이지로 분리. 본 문서는 이론 허브. - 검증: 행 합 1, π·P = π, eigenvalue=1 다중도로 reducibility 확인. ## 🕓 Changelog - 2026-05-08 | Phase 1 — 자동 시드. - 2026-05-10 | Manual cleanup — 정상 분포·MCMC·HMM·PageRank 코드, 결정 기준, 안티패턴 정리.