docs(10_Wiki): 위키 전체 재구성 — Topic_* 폴더를 4개 카테고리로 통합 + 대규모 중복 제거

Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를
Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류.

- 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로
  자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거,
  동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거.
- 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming,
  Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business,
  Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로,
  나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는
  title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백).
  원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지.
- 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서.
- 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는
  지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지.
- Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경.
- 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
This commit is contained in:
Antigravity Agent
2026-07-05 00:33:48 +09:00
parent 1cfd3bbb56
commit 9148c358d0
6455 changed files with 1 additions and 86875 deletions
@@ -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.