---
id: wiki-2026-0508-probabilistic-graphical-models
title: Probabilistic Graphical Models
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [PGM, Bayesian Network, Markov Random Field, MRF]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [pgm, bayesian-network, mrf, inference, machine-learning]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
  language: Python
  framework: pgmpy/pyro/numpyro
---

# Probabilistic Graphical Models

## 매 한 줄
> **"매 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 에서 핵심.

## 매 핵심

### 매 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).

### 매 핵심 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).

### 매 Inference Algorithm
- **Exact**: Variable Elimination, Belief Propagation (tree), Junction Tree.
- **Approx**: MCMC (Gibbs, Metropolis-Hastings), Variational Inference, Loopy BP.

### 매 응용
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.

## 💻 패턴

### pgmpy: Bayesian Network 정의
```python
from pgmpy.models import DiscreteBayesianNetwork
from pgmpy.factors.discrete import TabularCPD

model = DiscreteBayesianNetwork([('Rain', 'Sprinkler'), ('Rain', 'Wet'), ('Sprinkler', 'Wet')])

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])

model.add_cpds(cpd_rain, cpd_sprinkler, cpd_wet)
assert model.check_model()
```

### Variable Elimination inference
```python
from pgmpy.inference import VariableElimination

infer = VariableElimination(model)
result = infer.query(variables=['Rain'], evidence={'Wet': 1})
print(result)
```

### NumPyro: Bayesian regression
```python
import numpyro
import numpyro.distributions as dist
from numpyro.infer import MCMC, NUTS
import jax.numpy as jnp

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)

mcmc = MCMC(NUTS(model), num_warmup=500, num_samples=1000)
mcmc.run(jax.random.PRNGKey(0), X, y)
```

### 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]]
- 응용: [[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 |
