[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
@@ -2,88 +2,164 @@
id: wiki-2026-0508-probabilistic-graphical-models
title: Probabilistic Graphical Models
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [MATH-PGM-001]
aliases: [PGM, Bayesian Network, Markov Random Field, MRF]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [math, probability, graphical-models, bayesian-networks, markov-random-fields, Reasoning, causality]
confidence_score: 0.9
verification_status: applied
tags: [pgm, bayesian-network, mrf, inference, machine-learning]
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: unspecified
framework: unspecified
language: Python
framework: pgmpy/pyro/numpyro
---
# Probabilistic Graphical Models (확률적 그래픽 모델)
# Probabilistic Graphical Models
## 📌 한 줄 통찰 (The Karpathy Summary)
> "복잡하게 얽힌 세상의 변수들을 노드와 간선으로 해체하여, 불확실성 속에서도 명료한 '인과와 의존'의 지도를 그려라" — 확률 변수들 사이의 독립성 및 종속성 관계를 그래프 구조로 표현하여, 복잡한 다변량 확률 분포를 효율적으로 추론하고 학습하는 프레임워크.
## 한 줄
> **"매 graph 로 joint distribution 의 factorization 표현"**. 매 random variable = node, dependency = edge. Bayesian Network (DAG) 와 Markov Random Field (undirected) 의 두 family. 2026 의 매 deep learning 시대에도 medical diagnosis, fault detection, causal inference 에서 핵심.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Graph-structured Dependency and Factorization" — 전체 결합 확률 분포를 각 변수와 그 이웃(부모)들 사이의 국소적인 조건부 확률의 곱으로 분해하여, 연산의 복잡도를 획기적으로 낮추고 명확한 인과 추론을 가능케 하는 패턴.
- **주요 모델 분류:**
- **Bayesian Networks (Directed):** 방향성이 있는 간선으로 인과 관계 표현 (예: 질병 -> 증상).
- **Markov Random Fields (Undirected):** 방향성 없는 간선으로 상호 의존성 표현 (예: 인접한 픽셀 사이의 관계).
- **Factor Graphs:** 함수적 관계를 노드로 추가하여 더 일반적인 표현 가능.
- **의의:** 의료 진단, 유전자 분석, 자연어 이해, 컴퓨터 비전의 이미지 복원 등 데이터 사이의 '구조적 관계' 파악이 중요한 모든 분야의 핵심 도구.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 변수가 많아지면 추론이 불가능(NP-hard)해진다는 한계를 극복하기 위해, 최근에는 변이 추론(Variational Inference)이나 신경망과 결합된 심층 그래픽 모델(Deep Graphical Models)로 발전하여 거대 데이터셋에도 대응함.
- **정책 변화:** Antigravity 프로젝트는 에이전트의 지식 베이스 내 주제들 사이의 인과 관계를 분석할 때, 확률적 그래픽 모델 원리를 적용하여 사용자 질문에 대한 가장 타당한 답변 경로를 추론함.
### 매 Two Families
- **Bayesian Network (Directed)**: P(X) = ∏ᵢ P(Xᵢ | Pa(Xᵢ)). 매 causal direction 명시.
- **Markov Random Field (Undirected)**: P(X) = (1/Z) ∏ φc(Xc). 매 symmetric correlation.
- **Factor Graph**: 매 두 family 통합 representation — bipartite (variable + factor nodes).
## 🔗 지식 연결 (Graph)
- [[Posterior-and-Prior-Probability|Posterior-and-Prior-Probability]], [[Markov-Decision-Process-MDP|Markov-Decision-Process-MDP]], Bayesian-Inference, Conditional-Random-Fields-CRF
- **Raw Source:** 10_Wiki/Topics/AI/Probabilistic-Graphical-Models.md
### 매 핵심 Operation
- **Marginal inference**: P(Xᵢ) 매 sum out 다른 variable.
- **MAP inference**: argmax P(X) — most likely assignment.
- **Conditional**: P(Xᵢ | E=e) — evidence 주어진 belief update.
- **Learning**: 매 parameter (MLE, EM) + structure (score-based, constraint-based).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 Inference Algorithm
- **Exact**: Variable Elimination, Belief Propagation (tree), Junction Tree.
- **Approx**: MCMC (Gibbs, Metropolis-Hastings), Variational Inference, Loopy BP.
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 응용
1. Medical diagnosis: 매 symptom → disease causal network.
2. Fault detection: 매 sensor reading → root cause.
3. Computer vision: 매 CRF for image segmentation (DeepLab v3 의 backbone).
4. Causal inference: 매 do-calculus, counterfactual.
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
### pgmpy: Bayesian Network 정의
```python
from pgmpy.models import DiscreteBayesianNetwork
from pgmpy.factors.discrete import TabularCPD
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
model = DiscreteBayesianNetwork([('Rain', 'Sprinkler'), ('Rain', 'Wet'), ('Sprinkler', 'Wet')])
## 🧬 중복 검사 (Duplicate Check)
cpd_rain = TabularCPD('Rain', 2, [[0.8], [0.2]])
cpd_sprinkler = TabularCPD('Sprinkler', 2, [[0.9, 0.5], [0.1, 0.5]], evidence=['Rain'], evidence_card=[2])
cpd_wet = TabularCPD('Wet', 2,
[[1.0, 0.2, 0.1, 0.01], [0.0, 0.8, 0.9, 0.99]],
evidence=['Rain', 'Sprinkler'], evidence_card=[2, 2])
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
model.add_cpds(cpd_rain, cpd_sprinkler, cpd_wet)
assert model.check_model()
```
## 🤔 의사결정 기준 (Decision Criteria)
### Variable Elimination inference
```python
from pgmpy.inference import VariableElimination
**선택 A를 써야 할 때:**
- *(TODO)*
infer = VariableElimination(model)
result = infer.query(variables=['Rain'], evidence={'Wet': 1})
print(result)
```
**선택 B를 써야 할 때:**
- *(TODO)*
### NumPyro: Bayesian regression
```python
import numpyro
import numpyro.distributions as dist
from numpyro.infer import MCMC, NUTS
import jax.numpy as jnp
**기본값:**
> *(TODO)*
def model(X, y=None):
beta = numpyro.sample('beta', dist.Normal(jnp.zeros(X.shape[1]), 1.0))
sigma = numpyro.sample('sigma', dist.HalfNormal(1.0))
mu = jnp.dot(X, beta)
numpyro.sample('y', dist.Normal(mu, sigma), obs=y)
## ❌ 안티패턴 (Anti-Patterns)
mcmc = MCMC(NUTS(model), num_warmup=500, num_samples=1000)
mcmc.run(jax.random.PRNGKey(0), X, y)
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Markov Random Field (CRF for sequence labeling)
```python
import torch
from torchcrf import CRF
num_tags = 5
crf = CRF(num_tags, batch_first=True)
emissions = torch.randn(2, 10, num_tags) # (batch, seq, tags)
tags = torch.randint(0, num_tags, (2, 10))
loss = -crf(emissions, tags) # neg log likelihood
best = crf.decode(emissions) # Viterbi
```
### Pyro: Variational Inference
```python
import pyro
import pyro.distributions as dist
from pyro.infer import SVI, Trace_ELBO
from pyro.optim import Adam
def model(data):
z = pyro.sample('z', dist.Normal(0, 1))
pyro.sample('obs', dist.Normal(z, 1), obs=data)
def guide(data):
mu = pyro.param('mu', torch.tensor(0.))
sigma = pyro.param('sigma', torch.tensor(1.), constraint=dist.constraints.positive)
pyro.sample('z', dist.Normal(mu, sigma))
svi = SVI(model, guide, Adam({'lr': 0.01}), Trace_ELBO())
for step in range(1000):
svi.step(data)
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Discrete, small state space, exact inference | pgmpy + VE |
| Continuous, large model | NumPyro + NUTS |
| Sequence labeling | CRF |
| Image segmentation | CRF + CNN (DeepLab) |
| Causal inference | DoWhy + pgmpy |
| Real-time, approx OK | Loopy BP / VI |
**기본값**: 매 small problem → pgmpy. 매 large continuous → NumPyro NUTS.
## 🔗 Graph
- 부모: [[Probability_Theory]] · [[Graph_Theory]]
- 변형: [[Bayesian_Network]] · [[Markov_Random_Field]] · [[Factor_Graph]] · [[CRF]]
- 응용: [[Medical_Diagnosis]] · [[Image_Segmentation]] · [[Causal_Inference]]
- Adjacent: [[Hidden_Markov_Model]] · [[Variational_Inference]] · [[MCMC]]
## 🤖 LLM 활용
**언제**: 매 explicit causal structure 필요, interpretability 중요, small-data domain (medicine).
**언제 X**: 매 large-scale perception (이미지/음성) — neural network 가 우수.
## ❌ 안티패턴
- **모든 변수 fully connected**: 매 parameter explosion — sparsity 활용.
- **Exact inference 의 강행 in dense graph**: NP-hard — approximate 사용.
- **Causal direction 의 임의 가정**: 매 domain knowledge 없으면 PC algorithm 등으로 학습.
## 🧪 검증 / 중복
- Verified (Koller & Friedman 2009, Murphy 2012, pgmpy 0.1.26, NumPyro 0.16).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — pgmpy/NumPyro/Pyro modern stack |