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:
Antigravity Agent
2026-07-11 11:05:56 +09:00
parent 6549ead309
commit c24165b8bc
6193 changed files with 1717 additions and 31 deletions
@@ -0,0 +1,185 @@
---
id: wiki-2026-0508-natural-language-processing-nlp
title: Natural Language Processing (NLP)
status: verified
canonical_id: wiki-2026-0508-natural-language-processing-nlp
aliases: [NLP, Natural Language Processing, 자연어 처리]
duplicate_of: none
source_trust_level: A
confidence_score: 0.95
verification_status: applied
tags: [nlp, ai, language, llm, transformer, tokenization, embedding]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack: [python, transformers, spacy, nltk, sentence-transformers, anthropic]
---
# Natural Language Processing (NLP)
## 한 줄 정의
컴퓨터가 인간 언어를 **이해·생성·변환**하도록 하는 AI 분야. 통계 모델 → 단어 임베딩 → seq2seq → Transformer → LLM 으로 진화했고, 2020년대 이후 사실상 모든 실무 NLP 파이프라인이 **사전학습 Transformer/LLM 기반**.
## 핵심
### 진화 단계
1. **규칙·통계** (~2010): 정규식, n-gram, HMM, CRF.
2. **임베딩** (20132017): word2vec, GloVe, fastText.
3. **딥러닝 seq** (20142018): LSTM, BiLSTM-CRF, attention, seq2seq.
4. **Transformer 사전학습** (20182022): BERT, GPT-2/3, T5.
5. **LLM/Foundation** (2022+): GPT-4, Claude, Llama, Qwen — instruction/RLHF, multimodal.
### 핵심 작업
- **토큰화**: word/subword(BPE, WordPiece, SentencePiece). LLM 시대엔 BPE/Unigram이 default.
- **임베딩**: dense vector. modern: sentence-transformers, OpenAI/Cohere/Voyage embedding API.
- **분류**: 감성, 의도, 스팸 — 미세조정 BERT or LLM zero-shot.
- **NER / 정보 추출**: spaCy, BERT-CRF, LLM JSON output.
- **요약/번역/QA**: seq2seq → LLM.
- **RAG**: 임베딩 + vector DB + LLM.
### 응용
검색·랭킹, 챗봇/에이전트, 문서 분석, 의료/법률 정보추출, 코드 이해, 음성→텍스트 후처리, 모더레이션, 개인화.
## 💻 패턴
### Subword 토큰화
```python
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("bert-base-multilingual-cased")
print(tok.tokenize("자연어 처리는 흥미롭다"))
# ['자', '##연', '##어', '처', '##리', '##는', '흥', '##미', '##롭', '##다']
```
### Sentence embedding (현대 default)
```python
from sentence_transformers import SentenceTransformer
m = SentenceTransformer("BAAI/bge-m3")
emb = m.encode(["NLP는 재밌다", "자연어 처리는 흥미롭다"], normalize_embeddings=True)
sim = (emb[0] @ emb[1]).item()
```
### Zero-shot 분류 (LLM)
```python
import anthropic, json
client = anthropic.Anthropic()
SYS = '리뷰의 감성을 JSON {"label":"pos|neg|neu","conf":0..1}로 출력.'
def classify(text):
r = client.messages.create(
model="claude-opus-4-7", max_tokens=80, system=SYS,
messages=[{"role":"user","content":text}])
return json.loads(r.content[0].text)
```
### NER — spaCy
```python
import spacy
nlp = spacy.load("ko_core_news_lg")
doc = nlp("OpenAI의 샘 알트먼은 2026년 서울을 방문했다.")
for ent in doc.ents:
print(ent.text, ent.label_)
```
### 미세조정 — BERT 분류 (transformers)
```python
from transformers import (AutoTokenizer, AutoModelForSequenceClassification,
TrainingArguments, Trainer)
tok = AutoTokenizer.from_pretrained("klue/bert-base")
mdl = AutoModelForSequenceClassification.from_pretrained("klue/bert-base", num_labels=3)
def enc(b): return tok(b["text"], truncation=True, padding=True, max_length=128)
ds_tok = ds.map(enc, batched=True)
args = TrainingArguments(output_dir="out", per_device_train_batch_size=32,
num_train_epochs=3, learning_rate=2e-5,
eval_strategy="epoch")
Trainer(model=mdl, args=args, train_dataset=ds_tok["train"],
eval_dataset=ds_tok["validation"]).train()
```
### RAG — 검색 + 생성
```python
import chromadb
emb_model = SentenceTransformer("BAAI/bge-m3")
db = chromadb.PersistentClient("./chroma").get_or_create_collection("docs")
def index(docs):
embs = emb_model.encode(docs, normalize_embeddings=True).tolist()
db.add(documents=docs, embeddings=embs, ids=[f"d{i}" for i in range(len(docs))])
def answer(q, k=5):
qe = emb_model.encode([q], normalize_embeddings=True).tolist()
hits = db.query(query_embeddings=qe, n_results=k)["documents"][0]
ctx = "\n\n".join(hits)
r = client.messages.create(
model="claude-opus-4-7", max_tokens=512,
messages=[{"role":"user",
"content": f"<context>{ctx}</context>\n질문: {q}"}])
return r.content[0].text
```
### 다국어 LID (언어 감지)
```python
import fasttext
m = fasttext.load_model("lid.176.bin")
labels, _ = m.predict("Bonjour le monde")
print(labels) # ('__label__fr',)
```
## 결정 기준
| 작업 | 추천 |
|---|---|
| 빠른 프로토타입·zero-shot | **LLM API** |
| 대량·저비용 분류 | 미세조정 BERT/distil |
| 검색 retrieval | sentence-transformers + vector DB |
| NER 한국어 | spaCy `ko_core_news_lg` 또는 KoELECTRA |
| 토큰화 학습 새 도메인 | SentencePiece BPE |
| 다국어 임베딩 | BGE-M3, multilingual-e5 |
| 데이터셋 < 1k | LLM few-shot |
| 데이터셋 100k+ | fine-tune 작은 모델 |
기본값: **LLM zero/few-shot** → 비용·latency 문제 시 **fine-tuned 작은 모델**.
## 🔗 Graph
- 부모: [[Artificial-Intelligence]] · [[Machine-Learning]]
- 변형: [[Natural-Language-Generation-NLG]]
- 응용: [[RAG]] · [[Information-Extraction]]
- Adjacent: [[Large-Language-Models]] · [[Transformer_Architecture_and_LLM_Foundations|Transformer-Architecture]] · [[Tokenization]] · [[Word-Embeddings]] · [[Sentence-Transformers]]
## 🤖 LLM 활용
**언제**: NLP 파이프라인 설계 자문, dataset annotation, 평가셋 생성, 코드 리뷰, 도메인 어휘 정규화.
**언제 X**: PII 포함 데이터 무필터 LLM 전송, 결정론적 정규식으로 충분한 단순 추출에 LLM 호출(비용·latency), 평가에 동일 모델 self-judge(편향).
## ❌ 안티패턴
- 한국어에 영어 BERT(`bert-base-uncased`) 사용.
- 토큰 수 한도 무시하고 긴 문서 truncate → 핵심 정보 누락.
- Fine-tune 시 valid set 누출.
- Cosine 유사도 사용하면서 `normalize_embeddings=False` (vector 길이 영향).
- Stopword 제거를 LLM 입력에서 강제 → 구문 정보 파괴.
- 평가 지표 단일(Accuracy)로 class imbalance 무시.
## 🧪 검증 / 중복
Verified source: Jurafsky & Martin *Speech and Language Processing* (3rd ed. draft), Hugging Face course, ACL/EMNLP 최근 surveys, spaCy/transformers/sentence-transformers 공식 문서. 신뢰도 A.
[[Natural-Language-Processing-NLP|Natural-Language-Processing]] (약식), [[Natural-Language-Processing-NLP|National-Language-Processing]] (오타) 은 본 페이지로 redirect.
## 🕓 Changelog
- 2026-05-08 Phase 1 — 초기 stub.
- 2026-05-10 Manual cleanup — FULL canonical 재작성. 진화 5단계, 코드 7개(tok/emb/zero-shot/NER/fine-tune/RAG/LID), 결정 기준 표.