f8b21af4be
10_Wiki/Topics 대규모 정리: - 오류 캡처/미완성 stub 문서 227개 제거 - 교차폴더 중복 43클러스터 병합 (63파일 → redirect) - 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건 - 카테고리 MOC 6개 신규 생성 - Graph 섹션 미해결 related-keyword 링크 10,058건 제거 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
202 lines
6.3 KiB
Markdown
202 lines
6.3 KiB
Markdown
---
|
||
id: wiki-2026-0508-naive-bayes-classifiers
|
||
title: Naive Bayes Classifiers
|
||
category: 10_Wiki/Topics
|
||
status: verified
|
||
canonical_id: self
|
||
aliases: [NB, Naive Bayes, Gaussian NB, Multinomial NB, Bernoulli NB]
|
||
duplicate_of: none
|
||
source_trust_level: A
|
||
confidence_score: 0.95
|
||
verification_status: applied
|
||
tags: [naive-bayes, ml, classification, sklearn, baseline, probabilistic]
|
||
raw_sources: []
|
||
last_reinforced: 2026-05-10
|
||
github_commit: pending
|
||
tech_stack: { language: python, framework: scikit-learn }
|
||
---
|
||
|
||
# Naive Bayes Classifiers
|
||
|
||
## 매 한 줄
|
||
|
||
**Naive Bayes**는 feature 간 독립이라는 *naive* 가정 아래 Bayes 정리로 P(c|x)를 계산하는 단순·고속 분류기 가족(Gaussian/Multinomial/Bernoulli)이며, 가정이 깨져도 자주 잘 동작하는 강력한 baseline이다.
|
||
|
||
## 매 핵심
|
||
|
||
### 1. 모델
|
||
|
||
```
|
||
P(c|x) ∝ P(c) · ∏_i P(x_i|c) ← naive 독립 가정
|
||
ĉ = argmax_c [ log P(c) + Σ_i log P(x_i|c) ]
|
||
```
|
||
|
||
학습 = 클래스 prior + 클래스 조건부 likelihood 추정.
|
||
|
||
### 2. 변형
|
||
|
||
| 변형 | feature | likelihood |
|
||
|------|--------|-----------|
|
||
| **Gaussian NB** | 연속 실수 | N(μ_c, σ²_c) |
|
||
| **Multinomial NB** | 비음수 카운트 | Multinomial + Laplace α |
|
||
| **Bernoulli NB** | 이진 0/1 | Bernoulli + smoothing |
|
||
| **Complement NB** | 카운트 (불균형) | MNB 보완 |
|
||
| **Categorical NB** | 카테고리 인덱스 | Categorical |
|
||
|
||
### 3. 왜 naive 가정이 깨져도 잘 됨?
|
||
|
||
- 분류는 *argmax* 결정만 필요 — 확률 calibration이 틀려도 순서는 종종 맞음.
|
||
- 단어/feature 의존성이 있어도 독립 가정이 noise를 평균화 (실증).
|
||
- Domingos & Pazzani (1997): "On the Optimality of the Simple Bayesian Classifier".
|
||
|
||
### 4. 장점
|
||
|
||
- 학습 O(n·d), 추론 O(d) — 매우 빠름.
|
||
- 작은 데이터에서 견고 (low variance).
|
||
- 온라인 학습 (`partial_fit`).
|
||
- 해석 용이.
|
||
- 코드 5줄로 baseline.
|
||
|
||
### 5. 단점
|
||
|
||
- 독립 가정 위반 시 calibration 나쁨 — 확률값 신뢰 X (logit/Platt scaling 필요).
|
||
- 연속 feature는 정규분포 가정 → 위반 시 전처리 필요.
|
||
- 0 카운트 → smoothing 필수 (α>0).
|
||
- LLM/딥러닝 대비 정확도 SOTA 아님.
|
||
|
||
### 6. 2026 위치
|
||
|
||
- **Baseline 표준**: 5분 만에 텍스트 분류 v0.
|
||
- **엣지/모바일**: 수 KB 모델 + ms 추론.
|
||
- **라벨 부족 / weak supervision** + Snorkel.
|
||
- **해석 필요한 의료/금융 보조 분류기**.
|
||
|
||
## 💻 패턴
|
||
|
||
```python
|
||
# 1. Gaussian NB — iris 분류
|
||
from sklearn.naive_bayes import GaussianNB
|
||
from sklearn.datasets import load_iris
|
||
X, y = load_iris(return_X_y=True)
|
||
gnb = GaussianNB().fit(X, y)
|
||
print(gnb.score(X, y))
|
||
```
|
||
|
||
```python
|
||
# 2. Multinomial NB — 텍스트
|
||
from sklearn.feature_extraction.text import TfidfVectorizer
|
||
from sklearn.naive_bayes import MultinomialNB
|
||
from sklearn.pipeline import Pipeline
|
||
pipe = Pipeline([("tfidf", TfidfVectorizer()), ("mnb", MultinomialNB(alpha=0.1))])
|
||
pipe.fit(train_texts, train_labels)
|
||
```
|
||
|
||
```python
|
||
# 3. Bernoulli NB — 짧은 문서, 단어 존재 여부
|
||
from sklearn.feature_extraction.text import CountVectorizer
|
||
from sklearn.naive_bayes import BernoulliNB
|
||
vec = CountVectorizer(binary=True)
|
||
X = vec.fit_transform(short_texts)
|
||
bnb = BernoulliNB(alpha=1.0).fit(X, y)
|
||
```
|
||
|
||
```python
|
||
# 4. Complement NB — 불균형 텍스트
|
||
from sklearn.naive_bayes import ComplementNB
|
||
clf = ComplementNB(alpha=0.5).fit(X, y)
|
||
```
|
||
|
||
```python
|
||
# 5. partial_fit — streaming
|
||
import numpy as np
|
||
from sklearn.naive_bayes import MultinomialNB
|
||
mnb = MultinomialNB()
|
||
classes = np.array([0, 1, 2])
|
||
for X_b, y_b in batch_iter:
|
||
mnb.partial_fit(X_b, y_b, classes=classes)
|
||
```
|
||
|
||
```python
|
||
# 6. Calibration (NB 확률 신뢰 향상)
|
||
from sklearn.calibration import CalibratedClassifierCV
|
||
cal = CalibratedClassifierCV(GaussianNB(), method="isotonic", cv=5)
|
||
cal.fit(X_train, y_train)
|
||
proba = cal.predict_proba(X_test)
|
||
```
|
||
|
||
```python
|
||
# 7. NB + non-Gaussian 연속 feature → 변환
|
||
from sklearn.preprocessing import QuantileTransformer
|
||
qt = QuantileTransformer(output_distribution="normal")
|
||
X_g = qt.fit_transform(X)
|
||
gnb = GaussianNB().fit(X_g, y)
|
||
```
|
||
|
||
```python
|
||
# 8. Top features per class (해석)
|
||
import numpy as np
|
||
mnb = MultinomialNB().fit(X, y)
|
||
names = vec.get_feature_names_out()
|
||
for c, lp in zip(mnb.classes_, mnb.feature_log_prob_):
|
||
print(c, names[np.argsort(lp)[-10:]])
|
||
```
|
||
|
||
```python
|
||
# 9. NB vs LogReg 빠른 비교
|
||
from sklearn.linear_model import LogisticRegression
|
||
from sklearn.model_selection import cross_val_score
|
||
for clf in [MultinomialNB(), LogisticRegression(max_iter=1000)]:
|
||
print(type(clf).__name__, cross_val_score(clf, X, y, cv=5).mean())
|
||
```
|
||
|
||
```python
|
||
# 10. CategoricalNB — 범주형 feature
|
||
from sklearn.naive_bayes import CategoricalNB
|
||
from sklearn.preprocessing import OrdinalEncoder
|
||
X_enc = OrdinalEncoder().fit_transform(X_cat)
|
||
cnb = CategoricalNB(alpha=1.0).fit(X_enc, y)
|
||
```
|
||
|
||
## 매 결정 기준
|
||
|
||
| 입력 / 상황 | 추천 변형 |
|
||
|-----------|----------|
|
||
| 연속 수치 feature | **GaussianNB** |
|
||
| 텍스트 카운트/TF-IDF | **MultinomialNB** |
|
||
| 짧은 문서, 단어 존재 여부 | **BernoulliNB** |
|
||
| 불균형 텍스트 | **ComplementNB** |
|
||
| 범주형 feature | **CategoricalNB** |
|
||
| Streaming / online | NB + `partial_fit` |
|
||
| SOTA 정확도 | Transformer / GBDT |
|
||
| 빠른 baseline | NB + LogReg 비교 |
|
||
|
||
## 🔗 Graph
|
||
|
||
- 부모: [[Bayes Theorem]]
|
||
- 변형: [[Multinomial-Naive-Bayes]]
|
||
- 응용: [[Sentiment Analysis]]
|
||
- Adjacent: [[Logistic Regression]], [[TF-IDF]]
|
||
|
||
## 🤖 LLM 활용
|
||
|
||
- LLM이 unlabeled data 라벨링 → 작은 NB가 추론 (간단한 distillation).
|
||
- "이 NB classifier가 false positive 내는 이유 — top features로 설명".
|
||
- LLM이 feature engineering 제안 (예: "stop word 제거하면 정확도 ↑").
|
||
|
||
## ❌ 안티패턴
|
||
|
||
- **NB 확률값 그대로 신뢰**: calibration 종종 나쁨 — `CalibratedClassifierCV` 사용.
|
||
- **alpha=0**: log(0) 발산.
|
||
- **Gaussian NB에 highly skewed feature**: 정규 가정 위반 — 변환 또는 다른 모델.
|
||
- **Multinomial에 음수**: 에러.
|
||
- **거대 텍스트 데이터에서 NB만 고집**: Transformer가 5-15%pt 우수.
|
||
|
||
## 🧪 검증 / 중복
|
||
|
||
- 검증: sklearn docs, Domingos & Pazzani (1997), McCallum & Nigam (1998).
|
||
- 중복: 없음 (canonical). 변형별 자식 문서 [[Multinomial-Naive-Bayes]] 등.
|
||
|
||
## 🕓 Changelog
|
||
|
||
- 2026-05-10: 신규 작성. NB family overview + 5 variant + sklearn 패턴 + calibration.
|