refactor(topics): 멀티 에이전트용 지식 재편 — _Common(공통 기본기) + Domain_* 구조
에이전트 8종(대화형/프로그래머 C·S/디자이너/설계자/기획자/QA/PD/PM)에게 [공통 기본 능력 + 롤별 Specialty] 2층으로 지식을 주입하기 위한 재분류. 문서 내용·포맷은 무수정, 폴더 이동만 (6,372개 문서 수 보존 확인). - Topic_Programming → Domain_Programming (내부 구조 보존) - Topic_Graphic → Domain_Design - Topic_Business → Domain_Product - Topic_General → Domain_General - _Common 신설: Math(구 Topic_Math_Specialty), Reasoning(구 General/From_Thinking & Reasoning), Reasoning_Creativity(구 General/From_창의성), Communication(Poetic_Blog_Writing + From_writing) - 타 도메인의 From_* 폴더는 유지 (출처 표기일 뿐, 이미 도메인에 맞게 분류된 문서) - 빈 폴더 정리 (memory/procedures) - 에이전트→폴더 매핑은 workspace의 .astra/agent-knowledge-map.json (9개 에이전트) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,201 @@
|
||||
---
|
||||
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.
|
||||
Reference in New Issue
Block a user