[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,61 +2,141 @@
id: wiki-2026-0508-latent-dirichlet-allocation
title: Latent Dirichlet Allocation
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [NLP-LDA-001]
aliases: [LDA, Topic Model, Latent Dirichlet]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [nlp, machine-learning, lda, topic-modeling, unSupervised-Learning, probability]
confidence_score: 0.9
verification_status: applied
tags: [nlp, topic-modeling, unsupervised, bayesian, gensim]
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: gensim
---
# Latent Dirichlet Allocation (LDA, 잠재 디리클레 할당)
# Latent Dirichlet Allocation
## 📌 한 줄 통찰 (The Karpathy Summary)
> "문서는 여러 주제의 혼합물이며, 각 주제는 특정 단어들의 모임이다. 이 보이지 않는 구조를 확률의 눈으로 투시하라" — 문서 집합에서 숨겨진 주제를 찾아내고, 각 문서가 어떤 주제들의 비중으로 구성되어 있는지 추론하는 생성적 확률 모델.
## 한 줄
> **"매 문서 = topic 의 mixture, topic = word 의 mixture"**. Blei 2003 의 generative bayesian model. 2026 현재는 BERTopic 류 embedding 기반에 점유율 양보 중이지만, 해석 가능성/저비용에서 여전히 baseline.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Generative Process Reverse" — 문서가 작성되는 과정을 "주제 선택 -> 단어 선택"이라는 확률적 시나리오로 가정하고, 거꾸로 관측된 단어들로부터 원래의 주제 분포를 역추론하는 비지도 학습 패턴.
- **핵심 가정:**
- **Bag-of-Words:** 단어의 순서는 무시하고 빈도만 고려.
- **Dirichlet Distribution:** 문서별 주제 분포와 주제별 단어 분포가 디리클레 분포를 따른다고 가정.
- **의의:** 사람이 일일이 읽지 않아도 수천만 건의 문서에서 주요 화두(Topic)를 자동으로 추출하여 지식을 체계화할 수 있게 함.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 문맥을 무시하는 단어 빈도 중심의 한계를 넘기 위해, 최근에는 문장의 의미를 임베딩 벡터로 파악하는 [[BERT|BERT]] 기반의 토픽 모델링(BERTopic)과 결합하여 정밀도를 높이는 추세.
- **정책 변화:** Antigravity 프로젝트는 `00_Raw`에 유입되는 대규모 텍스트 데이터를 1차 분류할 때 LDA를 활용하여 위키의 어떤 카테고리에 배정할지 결정하는 클러스터링 보조 도구로 사용함.
### 매 Generative story
1. 각 topic k 에 대해 word distribution `φ_k ~ Dir(β)` 생성.
2. 각 문서 d 에 대해 topic distribution `θ_d ~ Dir(α)`.
3. 단어 위치마다: topic `z ~ Mult(θ_d)` 뽑고, word `w ~ Mult(φ_z)`.
## 🔗 지식 연결 (Graph)
- Latent-Semantic-Analysis-LSA, Un[[Supervised-Learning-Foundations|Supervised-Learning-Foundations]], NLP-Foundations, [[Exploratory-Data-Analysis|Exploratory-Data-Analysis]]
- **Raw Source:** 10_Wiki/Topics/AI/Latent-Dirichlet-Allocation.md
### 매 추론 (inference)
- **Variational Bayes** (Blei): 빠르지만 근사 거침.
- **Collapsed Gibbs sampling**: gensim 기본, sample-based 정확.
- 2026: 대부분 Online VB (gensim `LdaModel`) 또는 Mallet wrapper.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 vs alternatives
- **NMF**: matrix factorization, sparse, deterministic. 짧은 텍스트에 종종 우세.
- **BERTopic**: sentence-transformer + UMAP + HDBSCAN. semantic, but heavy.
- **Top2Vec**: doc2vec 기반.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### gensim LDA 기본
```python
from gensim import corpora, models
## 🧪 검증 상태 (Validation)
texts = [doc.split() for doc in raw_docs]
dictionary = corpora.Dictionary(texts)
dictionary.filter_extremes(no_below=5, no_above=0.5)
corpus = [dictionary.doc2bow(t) for t in texts]
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
lda = models.LdaModel(corpus, num_topics=20, id2word=dictionary,
passes=10, alpha="auto", eta="auto")
for topic_id, words in lda.print_topics():
print(topic_id, words)
```
## 🧬 중복 검사 (Duplicate Check)
### Coherence 기반 K 선택
```python
from gensim.models.coherencemodel import CoherenceModel
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
scores = {}
for k in [10, 15, 20, 30, 50]:
m = models.LdaModel(corpus, num_topics=k, id2word=dictionary, passes=5)
cm = CoherenceModel(model=m, texts=texts, dictionary=dictionary,
coherence="c_v")
scores[k] = cm.get_coherence()
best_k = max(scores, key=scores.get)
```
## 🕓 변경 이력 (Changelog)
### sklearn LatentDirichletAllocation
```python
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.decomposition import LatentDirichletAllocation
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
cv = CountVectorizer(max_df=0.5, min_df=5, stop_words="english")
X = cv.fit_transform(raw_docs)
lda = LatentDirichletAllocation(n_components=20, learning_method="online",
random_state=0).fit(X)
doc_topic = lda.transform(X) # (n_docs, 20)
```
### 새 문서 inference
```python
new_bow = dictionary.doc2bow(new_doc.split())
topic_dist = lda.get_document_topics(new_bow, minimum_probability=0.01)
```
### pyLDAvis 시각화
```python
import pyLDAvis.gensim_models
vis = pyLDAvis.gensim_models.prepare(lda, corpus, dictionary)
pyLDAvis.save_html(vis, "lda.html")
```
### BERTopic (LDA 후속)
```python
from bertopic import BERTopic
topic_model = BERTopic(language="english", min_topic_size=10)
topics, probs = topic_model.fit_transform(raw_docs)
topic_model.get_topic_info()
```
## 매 결정 기준
| 상황 | 모델 |
|---|---|
| 긴 문서, 해석 가능성 우선 | LDA |
| 짧은 텍스트 (tweet) | NMF / BTM |
| Semantic clustering 필요 | BERTopic |
| 실시간 streaming | Online LDA |
| GPU 없음, 수백만 문서 | gensim LDA + multicore |
**기본값**: gensim `LdaMulticore`, K = 20-50, coherence c_v 로 튜닝.
## 🔗 Graph
- 부모: [[Topic-Modeling]], [[Bayesian-Models]]
- 변형: [[NMF]], [[BERTopic]], [[Top2Vec]]
- 응용: [[Document-Clustering]], [[Recommendation]], [[Trend-Analysis]]
- Adjacent: [[TF-IDF]], [[Word-Embeddings]], [[Dirichlet-Distribution]]
## 🤖 LLM 활용
**언제**: 대규모 코퍼스 빠른 EDA, 해석 가능한 topic label, BERTopic 비용 부담스러울 때.
**언제 X**: 짧은 텍스트, semantic 차이 중요, 다국어 mix.
## ❌ 안티패턴
- **불용어 미제거**: top word 가 the/of 로 도배.
- **K 임의 고정**: coherence/perplexity 없이 20 박는 것.
- **단일 단어 토큰화**: bigram 무시 → "machine learning" 분리.
- **너무 짧은 문서**: 트윗에 표준 LDA → 노이즈.
## 🧪 검증 / 중복
- Blei, Ng, Jordan 2003 (JMLR).
- gensim, sklearn, Mallet 공식 문서.
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — gensim/sklearn 패턴, BERTopic 비교, coherence 튜닝 |