[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,62 +2,200 @@
id: wiki-2026-0508-naive-bayes-classifiers
title: Naive Bayes Classifiers
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [ML-NB-001]
aliases: [NB, Naive Bayes, Gaussian NB, Multinomial NB, Bernoulli NB]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [machine-learning, naive-bayes, classification, bayesian, probability, nlp]
confidence_score: 0.95
verification_status: applied
tags: [naive-bayes, ml, classification, sklearn, baseline, probabilistic]
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: python, framework: scikit-learn }
---
# Naive Bayes Classifiers (나이브 베이즈 분류기)
# Naive Bayes Classifiers
## 📌 한 줄 통찰 (The Karpathy Summary)
> "특징들 사이의 복잡한 관계를 '독립'이라는 단순함으로 치환하고, 베이즈 확률의 힘을 빌려 정답의 가능성을 계산하라" — 모든 특징(Feature)이 서로 독립적이라는 강한 가정 하에 베이즈 정리를 적용하여 데이터를 분류하는 확률론적 알고리즘.
## 한 줄
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Probabilistic Generative Modeling" — 정답(Class)이 주어졌을 때 각 특징이 나타날 확률(Likelihood)을 곱하여 최종적인 사후 확률(Posterior)을 구하고, 가장 높은 확률을 가진 클래스를 정답으로 선택하는 패턴.
- **주요 변종:**
- **Gaussian NB:** 특징이 연속적이고 정규 분포를 따를 때 사용.
- **Multinomial NB:** 특징이 단어 빈도와 같은 이산적인 카운트 데이터일 때 사용.
- **Bernoulli NB:** 특징이 이진(0 또는 1) 값으로 표현될 때 사용.
- **의의:** 학습 속도가 매우 빠르고 적은 데이터로도 준수한 성능을 내어, 딥러닝 이전의 텍스트 분류와 실시간 필터링 시스템의 중추 역할을 수행함.
**Naive Bayes**는 feature 간 독립이라는 *naive* 가정 아래 Bayes 정리로 P(c|x)를 계산하는 단순·고속 분류기 가족(Gaussian/Multinomial/Bernoulli)이며, 가정이 깨져도 자주 잘 동작하는 강력한 baseline이다.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 독립성 가정이 현실과 맞지 않아 성능이 낮을 것이라는 우려와 달리, 실제로는 특징 간의 상관관계가 존재하더라도 최종 분류 결정에는 큰 영향을 주지 않는 경우가 많아(나이브 베이즈의 역설) 여전히 강력한 베이스라인으로 생존함.
- **정책 변화:** Antigravity 프로젝트는 에이전트의 입력 쿼리를 '정보 검색', '코드 생성', '시스템 제어' 등 대분류로 빠르게 라우팅할 때, 최저 비용으로 최대 효율을 내는 가우시안 및 다항 나이브 베이즈 분류기를 병행 운용함.
## 매 핵심
## 🔗 지식 연결 (Graph)
- [[Multinomial-Naive-Bayes|Multinomial-Naive-Bayes]], Probability-Theory, [[Supervised-Learning-Foundations|Supervised-Learning-Foundations]], NLP-Foundations
- **Raw Source:** 10_Wiki/Topics/AI/Naive-Bayes-Classifiers.md
### 1. 모델
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
```
P(c|x) ∝ P(c) · ∏_i P(x_i|c) ← naive 독립 가정
ĉ = argmax_c [ log P(c) + Σ_i log P(x_i|c) ]
```
**언제 이 지식을 쓰는가:**
- *(TODO)*
학습 = 클래스 prior + 클래스 조건부 likelihood 추정.
**언제 쓰면 안 되는가:**
- *(TODO)*
### 2. 변형
## 🧪 검증 상태 (Validation)
| 변형 | feature | likelihood |
|------|--------|-----------|
| **Gaussian NB** | 연속 실수 | N(μ_c, σ²_c) |
| **Multinomial NB** | 비음수 카운트 | Multinomial + Laplace α |
| **Bernoulli NB** | 이진 0/1 | Bernoulli + smoothing |
| **Complement NB** | 카운트 (불균형) | MNB 보완 |
| **Categorical NB** | 카테고리 인덱스 | Categorical |
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### 3. 왜 naive 가정이 깨져도 잘 됨?
## 🧬 중복 검사 (Duplicate Check)
- 분류는 *argmax* 결정만 필요 — 확률 calibration이 틀려도 순서는 종종 맞음.
- 단어/feature 의존성이 있어도 독립 가정이 noise를 평균화 (실증).
- Domingos & Pazzani (1997): "On the Optimality of the Simple Bayesian Classifier".
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### 4. 장점
## 🕓 변경 이력 (Changelog)
- 학습 O(n·d), 추론 O(d) — 매우 빠름.
- 작은 데이터에서 견고 (low variance).
- 온라인 학습 (`partial_fit`).
- 해석 용이.
- 코드 5줄로 baseline.
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### 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
- 부모: [[Probabilistic Classifiers]], [[Bayes Theorem]]
- 변형: [[Multinomial-Naive-Bayes]], [[Gaussian Naive Bayes]], [[Bernoulli Naive Bayes]], [[Complement Naive Bayes]]
- 응용: [[Spam Detection]], [[Sentiment Analysis]], [[Document Categorization]]
- Adjacent: [[Logistic Regression]], [[TF-IDF]], [[Calibration]]
## 🤖 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.