[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,90 +2,257 @@
|
||||
id: wiki-2026-0508-expectation-maximization
|
||||
title: Expectation Maximization
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-EXMA-001]
|
||||
aliases: [EM Algorithm, Expectation-Maximization, GMM-EM, Baum-Welch]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.94
|
||||
tags: [auto-reinforced, em-algorithm, expectation-maximization, latent-variable, gmm, Statistics, clustering, unSupervised-Learning]
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [statistics, machine-learning, latent-variables, optimization, probabilistic-models]
|
||||
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: unspecified
|
||||
framework: unspecified
|
||||
language: Python
|
||||
framework: scikit-learn / NumPy / PyTorch
|
||||
---
|
||||
|
||||
# [[Expectation-Maximization|Expectation-Maximization]]
|
||||
# Expectation Maximization
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "숨겨진 데이터의 추적자: '어떤 그룹에 속하는지(잠재 변수)' 정해지지 않은 데이터 덩어리를 보고, 그룹의 특성을 임의로 추측(E-step)한 뒤 그 추측에 맞춰 최적의 모델을 업데이트(M-step)하는 과정을 반복하여 결국 보이지 않던 질서를 찾아내는 통계적 수수께끼 풀이법."
|
||||
## 매 한 줄
|
||||
> **"매 latent variable 가진 model 의 maximum likelihood 의 iterative 추정 — E-step (posterior) ↔ M-step (parameter update) 교차"**. Dempster-Laird-Rubin 1977 의 unification — 매 GMM, HMM (Baum-Welch), LDA, factor analysis, missing data imputation 의 모두 instances. 매 modern variational autoencoder 의 amortized EM.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
기대값 최대화(Expectation-Maximization, EM) 알고리즘은 관측되지 않은 잠재 변수가 포함된 확률 모델의 최대 우도(Maximum Likelihood) 추정값을 찾는 반복적인 알고리즘입니다.
|
||||
## 매 핵심
|
||||
|
||||
1. **2단계 프로세스**:
|
||||
* **E-Step (Expectation)**: 현재 모델 파라미터를 사용해 각 데이터가 특정 잠재 변수값(예: 클러스터 소속)을 가질 확률을 계산.
|
||||
* **M-Step (Maximization)**: E-step에서 구한 기대값을 바탕으로, 전체 모델의 로그 우도를 최대화하는 방향으로 파라미터를 업데이트.
|
||||
2. **왜 중요한가?**:
|
||||
* 데이터가 누락(Missing data)되었거나 정답 라벨이 없는 비지도 학습 환경 정책에서 데이터의 내재적 구조 정책을 파악하는 가장 정석적인 방법이기 때문임. (Statistics와 연결)
|
||||
### 매 Algorithm
|
||||
Goal: maximize log p(X|θ) where X observed, Z latent.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌**: 과거에는 단순히 가우시안 혼합 모델(GMM) 정책 등에 사용되었으나, 현대 정책은 거대 언어 모델의 '지식 증강(Knowledge augmentation)' 과정이나 복잡한 추천 시스템의 '사용자 취향 잠재 공간 정책'을 찾아내는 데 핵심적으로 쓰임(RL Update).
|
||||
- **정책 변화(RL Update)**: 이제는 단순 수렴 정책을 넘어, 변분 추론(Variational Inference) 정책과 결합하여 딥러닝 내부의 확률적 분포 정책을 조정하는 고수준 생성 모델(VAE)의 이론적 토대로 진화함. (Deep Learning (DL)와 연결)
|
||||
- **E-step**: 매 posterior q(Z) = p(Z|X, θ_old).
|
||||
- **M-step**: θ_new = argmax_θ E_q[log p(X, Z | θ)].
|
||||
- **Repeat**: until convergence (likelihood plateau).
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Statistics|Statistics]], [[Analysis|Analysis]], Deep Learning (DL), [[Logic|Logic]], [[Complexity-Theory|Complexity-Theory]], Generalization
|
||||
- **Key Use Case**: Gaussian Mixture Models (GMM), Hidden Markov Models (HMM).
|
||||
---
|
||||
### 매 ELBO interpretation
|
||||
log p(X|θ) ≥ E_q[log p(X,Z|θ)] - E_q[log q(Z)] = ELBO(q, θ).
|
||||
- E-step: 매 maximize ELBO over q (equiv. KL(q||p(Z|X,θ))=0 — 매 exact).
|
||||
- M-step: 매 maximize ELBO over θ.
|
||||
- 매 monotonic increase of log-likelihood guaranteed.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 Convergence
|
||||
- 매 local optimum 으로만 converge (matter 의 likelihood 의 multimodal).
|
||||
- 매 multiple random init 권장.
|
||||
- 매 K-means 의 EM 의 hard-assignment limit (Gaussian variance → 0).
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### 매 응용
|
||||
1. **Gaussian Mixture Models**: 매 clustering with soft assignments.
|
||||
2. **Hidden Markov Models** (Baum-Welch): 매 speech recognition, NLP, bioinformatics.
|
||||
3. **Latent Dirichlet Allocation** (variational EM): topic modeling.
|
||||
4. **Factor analysis / PPCA**: 매 dimensionality reduction.
|
||||
5. **Missing data imputation**: 매 MICE.
|
||||
6. **VAE training** (amortized EM): 매 modern deep generative.
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
### GMM-EM (매 from scratch, NumPy)
|
||||
```python
|
||||
import numpy as np
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
class GaussianMixtureEM:
|
||||
def __init__(self, K, max_iter=100, tol=1e-6):
|
||||
self.K = K
|
||||
self.max_iter = max_iter
|
||||
self.tol = tol
|
||||
|
||||
def fit(self, X):
|
||||
n, d = X.shape
|
||||
# 매 init: random + uniform priors
|
||||
self.pi = np.ones(self.K) / self.K
|
||||
idx = np.random.choice(n, self.K, replace=False)
|
||||
self.mu = X[idx]
|
||||
self.sigma = np.array([np.cov(X.T) for _ in range(self.K)])
|
||||
|
||||
log_lik_old = -np.inf
|
||||
for it in range(self.max_iter):
|
||||
# E-step: posterior responsibilities γ_ik
|
||||
log_resp = self._log_responsibilities(X) # (n, K)
|
||||
resp = np.exp(log_resp - log_resp.max(axis=1, keepdims=True))
|
||||
resp /= resp.sum(axis=1, keepdims=True)
|
||||
|
||||
# M-step
|
||||
Nk = resp.sum(axis=0) # (K,)
|
||||
self.pi = Nk / n
|
||||
self.mu = (resp.T @ X) / Nk[:, None]
|
||||
for k in range(self.K):
|
||||
diff = X - self.mu[k]
|
||||
self.sigma[k] = (resp[:, k:k+1] * diff).T @ diff / Nk[k]
|
||||
self.sigma[k] += 1e-6 * np.eye(d) # 매 regularization
|
||||
|
||||
# convergence
|
||||
log_lik = self._log_likelihood(X)
|
||||
if abs(log_lik - log_lik_old) < self.tol:
|
||||
break
|
||||
log_lik_old = log_lik
|
||||
return self
|
||||
|
||||
def _log_gaussian(self, X, mu, sigma):
|
||||
d = X.shape[1]
|
||||
diff = X - mu
|
||||
inv = np.linalg.inv(sigma)
|
||||
det = np.linalg.det(sigma)
|
||||
return -0.5 * (d * np.log(2 * np.pi) + np.log(det) +
|
||||
np.einsum('ni,ij,nj->n', diff, inv, diff))
|
||||
|
||||
def _log_responsibilities(self, X):
|
||||
log_resp = np.zeros((X.shape[0], self.K))
|
||||
for k in range(self.K):
|
||||
log_resp[:, k] = np.log(self.pi[k] + 1e-12) + \
|
||||
self._log_gaussian(X, self.mu[k], self.sigma[k])
|
||||
return log_resp
|
||||
|
||||
def _log_likelihood(self, X):
|
||||
log_resp = self._log_responsibilities(X)
|
||||
from scipy.special import logsumexp
|
||||
return logsumexp(log_resp, axis=1).sum()
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
# Demo
|
||||
np.random.seed(42)
|
||||
X1 = np.random.randn(100, 2) + np.array([5, 0])
|
||||
X2 = np.random.randn(100, 2) + np.array([-5, 0])
|
||||
X = np.vstack([X1, X2])
|
||||
model = GaussianMixtureEM(K=2).fit(X)
|
||||
print(f"Means:\n{model.mu}")
|
||||
print(f"Mixing:\n{model.pi}")
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### scikit-learn (매 production)
|
||||
```python
|
||||
from sklearn.mixture import GaussianMixture
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
gmm = GaussianMixture(n_components=3, covariance_type='full',
|
||||
max_iter=100, n_init=10, random_state=42)
|
||||
gmm.fit(X)
|
||||
print(f"Converged: {gmm.converged_}")
|
||||
print(f"BIC: {gmm.bic(X):.2f}") # 매 model selection
|
||||
labels = gmm.predict(X)
|
||||
proba = gmm.predict_proba(X) # 매 soft assignment
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Baum-Welch (HMM, 매 EM 의 instance)
|
||||
```python
|
||||
def baum_welch(observations, n_states, n_iter=100):
|
||||
"""매 HMM 의 forward-backward + EM updates."""
|
||||
T = len(observations)
|
||||
pi = np.ones(n_states) / n_states
|
||||
A = np.random.rand(n_states, n_states); A /= A.sum(axis=1, keepdims=True)
|
||||
B = np.random.rand(n_states, max(observations)+1); B /= B.sum(axis=1, keepdims=True)
|
||||
|
||||
for it in range(n_iter):
|
||||
# E-step: forward α, backward β
|
||||
alpha = np.zeros((T, n_states))
|
||||
alpha[0] = pi * B[:, observations[0]]
|
||||
for t in range(1, T):
|
||||
alpha[t] = (alpha[t-1] @ A) * B[:, observations[t]]
|
||||
|
||||
beta = np.zeros((T, n_states))
|
||||
beta[T-1] = 1
|
||||
for t in range(T-2, -1, -1):
|
||||
beta[t] = A @ (B[:, observations[t+1]] * beta[t+1])
|
||||
|
||||
# γ_t(i), ξ_t(i,j)
|
||||
gamma = alpha * beta
|
||||
gamma /= gamma.sum(axis=1, keepdims=True)
|
||||
xi = np.zeros((T-1, n_states, n_states))
|
||||
for t in range(T-1):
|
||||
num = alpha[t][:, None] * A * B[:, observations[t+1]] * beta[t+1]
|
||||
xi[t] = num / num.sum()
|
||||
|
||||
# M-step
|
||||
pi = gamma[0]
|
||||
A = xi.sum(axis=0) / gamma[:-1].sum(axis=0)[:, None]
|
||||
for k in range(B.shape[1]):
|
||||
mask = (observations == k)
|
||||
B[:, k] = gamma[mask].sum(axis=0) / gamma.sum(axis=0)
|
||||
return pi, A, B
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### VAE — 매 amortized variational EM
|
||||
```python
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
class VAE(nn.Module):
|
||||
def __init__(self, input_dim, latent_dim):
|
||||
super().__init__()
|
||||
self.enc_mu = nn.Linear(input_dim, latent_dim)
|
||||
self.enc_logvar = nn.Linear(input_dim, latent_dim)
|
||||
self.dec = nn.Linear(latent_dim, input_dim)
|
||||
|
||||
def forward(self, x):
|
||||
# 매 E-step approximation: q(z|x) = N(μ_φ(x), σ²_φ(x))
|
||||
mu = self.enc_mu(x)
|
||||
logvar = self.enc_logvar(x)
|
||||
eps = torch.randn_like(mu)
|
||||
z = mu + torch.exp(0.5 * logvar) * eps
|
||||
x_recon = torch.sigmoid(self.dec(z))
|
||||
return x_recon, mu, logvar
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
def vae_loss(x, x_recon, mu, logvar):
|
||||
recon = nn.functional.binary_cross_entropy(x_recon, x, reduction='sum')
|
||||
kl = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
|
||||
return recon + kl
|
||||
# 매 SGD 의 joint optimization 의 amortized E+M
|
||||
```
|
||||
|
||||
### MAP-EM (매 with prior, regularized)
|
||||
```python
|
||||
# 매 prior 의 add 시 monotonic posterior 증가.
|
||||
# Example: GMM 에 Dirichlet prior on π, NIW on (μ, Σ).
|
||||
# 매 sklearn BayesianGaussianMixture 의 internal.
|
||||
from sklearn.mixture import BayesianGaussianMixture
|
||||
bgmm = BayesianGaussianMixture(n_components=10, weight_concentration_prior=1e-2)
|
||||
bgmm.fit(X)
|
||||
# 매 effective K 의 자동 sparsification.
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
|
||||
| 상황 | Variant |
|
||||
|---|---|
|
||||
| Standard mixture clustering | Vanilla EM (sklearn) |
|
||||
| Sequential / temporal | Baum-Welch (HMM) |
|
||||
| Topic modeling | Variational EM (LDA) |
|
||||
| Scalable / online | Online EM, stochastic |
|
||||
| Deep latent model | VAE (amortized) |
|
||||
| Need MAP / regularization | MAP-EM, Bayesian-EM |
|
||||
| Hard assignment baseline | K-means (EM degenerate) |
|
||||
| Discrete latent | Categorical EM |
|
||||
|
||||
**기본값**: 매 GMM clustering 매 sklearn `GaussianMixture(n_init=10)`. 매 deep 매 VAE.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Maximum-Likelihood-Estimation]] · [[Latent-Variable-Models]]
|
||||
- 변형: [[Variational-EM]] · [[Stochastic-EM]] · [[MAP-EM]] · [[Hard-EM]]
|
||||
- 응용: [[Gaussian-Mixture-Models]] · [[Hidden-Markov-Models]] · [[LDA-Topic-Modeling]] · [[VAE]]
|
||||
- Adjacent: [[Variational-Inference]] · [[Maximum-A-Posteriori]] · [[K-Means-Clustering-Foundations]] · [[Baum-Welch]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 derivation 의 walk-through, 매 ELBO 의 explain, 매 model selection (BIC) 의 advice, 매 troubleshooting (e.g., 매 singular covariance).
|
||||
**언제 X**: 매 large-scale fitting — 매 sklearn / dedicated library 사용. 매 numerical issue 의 diagnosis 시 actual data 의 inspection 필요.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Single random init**: 매 local optimum trap — n_init=10 권장.
|
||||
- **Singular covariance ignore**: 매 sigma += εI 의 regularization 필수.
|
||||
- **Convergence 의 likelihood 가 아닌 parameter 의 monitor**: 매 wrong — likelihood / ELBO 의 monitor.
|
||||
- **K 의 randomly choose**: 매 BIC / AIC / cross-validation 사용.
|
||||
- **K-means 의 GMM 결과 비교**: 매 different — GMM 의 soft assignment + covariance.
|
||||
- **EM 의 global optimum 가정**: 매 local optimum 만 — multi-start 필수.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Dempster-Laird-Rubin 1977, Bishop "PRML" Ch9, Murphy "Probabilistic ML" Ch11).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — algorithm, ELBO, GMM/HMM/VAE applications, NumPy from-scratch |
|
||||
|
||||
Reference in New Issue
Block a user