[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,89 +1,179 @@
|
||||
---
|
||||
id: wiki-2026-0508-natural-language-generation-nlg
|
||||
title: Natural Language Generation NLG
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
canonical_id: self
|
||||
aliases: [NLP-NLG-001]
|
||||
title: Natural Language Generation (NLG)
|
||||
status: verified
|
||||
canonical_id: wiki-2026-0508-natural-language-generation-nlg
|
||||
aliases: [NLG, Text Generation, Natural-Language-Generation]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [nlp, nlg, natural-language-generation, llm, decoding-strategies, Generative-AI]
|
||||
confidence_score: 0.93
|
||||
verification_status: applied
|
||||
tags: [nlp, nlg, text-generation, llm, evaluation]
|
||||
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: unspecified
|
||||
framework: unspecified
|
||||
tech_stack: [python, transformers, openai, anthropic, sacrebleu]
|
||||
---
|
||||
|
||||
# Natural Language Generation (NLG, 자연어 생성)
|
||||
# Natural Language Generation (NLG)
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "데이터의 정적 정보를 유려한 언어의 흐름으로 치환하여, 기계와 인간이 소통하는 '표현의 창'을 열어라" — 구조화된 데이터나 내부 지식을 인간이 읽고 이해할 수 있는 자연스러운 텍스트 문장으로 변환하는 자연어 처리의 핵심 세부 분야.
|
||||
## 한 줄 정의
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** "Probabilistic Token Sequence Prediction" — 이전까지 생성된 단어들의 맥락을 바탕으로, 다음에 올 가장 적절한 단어를 확률적으로 예측하고 연결하여 하나의 완결된 문장을 완성해 나가는 패턴.
|
||||
- **핵심 프로세스:**
|
||||
- **Content Planning:** 무엇을 말할지 결정 (정보 추출 및 요약).
|
||||
- **Sentence Realization:** 문법적 규칙이나 확률 모델을 사용하여 문장 형성.
|
||||
- **Decoding Strategies:** Greedy [[Search|Search]], Beam Search, Top-k/Top-p Sampling 등을 통해 생성의 창의성과 정확도 조절.
|
||||
- **의의:** 챗봇, 자동 기사 작성, 코드 생성, 텍스트 요약 등 현대 생성형 AI(Generative AI)의 사용자 경험을 결정짓는 최종 출력 단계 기술.
|
||||
구조화된 입력(데이터·표·의도)이나 unstructured prompt에서 **자연어 텍스트를 생성**하는 NLP 하위 분야. 2020년대 LLM 등장 이후 사실상 "프롬프트 → LLM 호출"이 default가 되며, 전통적 template/규칙 기반은 하이브리드 fallback 역할.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 규칙 기반의 템플릿 방식에서 벗어나, 이제는 거대 언어 모델(LLM)이 문맥을 완전히 이해하고 인간과 구분이 불가능할 정도의 고품질 문장을 생성하는 딥러닝 기반 NLG가 지배적인 패러다임이 됨.
|
||||
- **정책 변화:** Antigravity 프로젝트는 에이전트의 응답 생성 시, 할루시네이션(Hallucination)을 억제하기 위해 지식 기반(RAG)을 참조한 '근거 중심 생성' 가이드라인을 최우선으로 적용함.
|
||||
## 핵심
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Natural-Language-Processing|Natural-Language-[[Processing]]-NLP]], [[Transformer-Architecture|Transformer-Architecture]]-Foundations, Decoding-Strategies-in-LLM, [[Hallucination-in-LLM|Hallucination-in-LLM]]
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/Natural-Language-Generation-NLG.md
|
||||
### 세대 구분
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
- **Template-based**: 슬롯 채우기 (`"오늘 {city} 기온 {temp}°C"`). 정확·예측가능, 다양성 0.
|
||||
- **Statistical (n-gram, HMM)**: 2010년대 이전. 현재는 거의 사용 X.
|
||||
- **Neural seq2seq (LSTM/Transformer)**: 2014–2019. 요약·번역 SOTA.
|
||||
- **LLM-based (GPT/Claude/Llama 계열)**: 2020+. zero/few-shot, instruction tuning.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### 파이프라인 (전통)
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
content determination → text structuring → sentence aggregation → lexicalization → referring expression generation → linguistic realization. LLM 시대에는 이 단계가 implicit.
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
### 평가 지표
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
- **BLEU** — n-gram overlap. 번역에서 유래.
|
||||
- **ROUGE** — recall 기반. 요약 표준.
|
||||
- **METEOR** — synonym/stem 고려.
|
||||
- **BERTScore** — embedding cosine. semantic.
|
||||
- **BLEURT, COMET** — learned metric.
|
||||
- **G-Eval / LLM-as-judge** — LLM이 채점.
|
||||
- **Human eval** — fluency, faithfulness, relevance, factuality.
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
### 응용
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
요약, 번역, 데이터→문장(report generation), 챗봇, 코드 생성, 광고 문안, 시나리오, RAG 답변, 데이터 증강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
## 💻 패턴
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
### Template fallback
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
```python
|
||||
def render_weather(city, temp, cond):
|
||||
return f"{city}의 현재 기온은 {temp}°C, 날씨는 {cond}입니다."
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Hugging Face 생성
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
```python
|
||||
from transformers import AutoTokenizer, AutoModelForCausalLM
|
||||
tok = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B-Instruct")
|
||||
mdl = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.1-8B-Instruct",
|
||||
device_map="auto")
|
||||
ids = tok.apply_chat_template(
|
||||
[{"role":"user","content":"한 문장 요약: ..."}],
|
||||
return_tensors="pt").to(mdl.device)
|
||||
out = mdl.generate(ids, max_new_tokens=128, temperature=0.7, top_p=0.9)
|
||||
print(tok.decode(out[0][ids.shape[-1]:], skip_special_tokens=True))
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Anthropic API (modern default)
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
```python
|
||||
import anthropic
|
||||
client = anthropic.Anthropic()
|
||||
msg = client.messages.create(
|
||||
model="claude-opus-4-7",
|
||||
max_tokens=512,
|
||||
system="간결하고 사실에 기반한 한국어로 답하라.",
|
||||
messages=[{"role":"user","content":"분기 매출표 → 한 문단 요약: ..."}],
|
||||
)
|
||||
print(msg.content[0].text)
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Sampling 제어
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
```python
|
||||
# 결정론적 (사실 답변)
|
||||
generate(temperature=0.0)
|
||||
# 다양성 (창작)
|
||||
generate(temperature=0.9, top_p=0.95)
|
||||
# 반복 억제
|
||||
generate(repetition_penalty=1.1, no_repeat_ngram_size=3)
|
||||
```
|
||||
|
||||
### BLEU/ROUGE 평가
|
||||
|
||||
```python
|
||||
import sacrebleu
|
||||
from rouge_score import rouge_scorer
|
||||
|
||||
bleu = sacrebleu.corpus_bleu(hyps, [refs])
|
||||
print(bleu.score)
|
||||
|
||||
scorer = rouge_scorer.RougeScorer(['rouge1','rougeL'], use_stemmer=True)
|
||||
scores = [scorer.score(r, h) for r, h in zip(refs, hyps)]
|
||||
```
|
||||
|
||||
### BERTScore
|
||||
|
||||
```python
|
||||
from bert_score import score
|
||||
P, R, F1 = score(hyps, refs, lang="ko", rescale_with_baseline=True)
|
||||
print(F1.mean().item())
|
||||
```
|
||||
|
||||
### LLM-as-judge (G-Eval 스타일)
|
||||
|
||||
```python
|
||||
JUDGE = """다음 요약의 사실 정확도를 1-5로 평가하라.
|
||||
원문: {src}
|
||||
요약: {hyp}
|
||||
JSON으로만: {{"score": int, "reason": str}}"""
|
||||
|
||||
def judge(src, hyp):
|
||||
r = client.messages.create(
|
||||
model="claude-opus-4-7", max_tokens=200,
|
||||
messages=[{"role":"user","content":JUDGE.format(src=src, hyp=hyp)}])
|
||||
return json.loads(r.content[0].text)
|
||||
```
|
||||
|
||||
## 결정 기준
|
||||
|
||||
| 상황 | 추천 |
|
||||
|---|---|
|
||||
| 고정 양식·법적 정확성 | Template |
|
||||
| 데이터 → 보고서 (수치 보존) | Template + LLM rewrite |
|
||||
| 일반 자유 텍스트 | LLM (Claude/GPT) |
|
||||
| 비용 민감, on-prem | open-weight LLM (Llama/Qwen) |
|
||||
| 평가 — 번역 | BLEU + COMET |
|
||||
| 평가 — 요약 | ROUGE + BERTScore + LLM-judge |
|
||||
| 평가 — open-ended | **LLM-as-judge + 인간 spot check** |
|
||||
|
||||
기본값: **LLM 호출**, 사실 정확성 위험 시 **template hybrid**.
|
||||
|
||||
## 🔗 Graph
|
||||
|
||||
- 부모: [[Natural-Language-Processing-NLP]] · [[Generative-AI]]
|
||||
- 변형: [[Data-to-Text-Generation]] · [[Abstractive-Summarization]] · [[Machine-Translation]]
|
||||
- 응용: [[Chatbots]] · [[RAG]] · [[Code-Generation]] · [[Report-Generation]]
|
||||
- Adjacent: [[Large-Language-Models]] · [[Prompt-Engineering]] · [[BLEU]] · [[ROUGE]] · [[BERTScore]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
|
||||
**언제**: NLG 작업 자체(요약·번역·rewrite), 평가 자동화(LLM-as-judge), prompt 설계, hallucination 감지 보조.
|
||||
|
||||
**언제 X**: 수치·법률·의료 등 사실 정확성이 절대적인 출력에 LLM 단독 의존. 반드시 template/grounding/검증 layer 추가.
|
||||
|
||||
## ❌ 안티패턴
|
||||
|
||||
- BLEU 단일 지표로 요약·자유생성 평가 → 의미 차이 못 잡음.
|
||||
- temperature=1.0+ 로 사실 응답 생성 → hallucination 폭증.
|
||||
- LLM-as-judge에 같은 모델 사용 (self-preference bias).
|
||||
- Template 없이 수치 그대로 자연어로 → 잘못된 반올림·단위 누락.
|
||||
- 평가셋 누출 (test set이 학습에 들어감) — 평가 무의미.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
|
||||
Verified source: Reiter & Dale *Building NLG Systems*, Hugging Face `transformers` docs, Anthropic/OpenAI API 문서, ACL/EMNLP 평가 논문, BERTScore (Zhang et al. 2020), G-Eval (Liu et al. 2023). 신뢰도 A.
|
||||
|
||||
[[Large-Language-Models]] 와 겹치지만 NLG는 **태스크/평가** 관점, LLM은 **모델/시스템** 관점으로 분리.
|
||||
|
||||
## 🕓 Changelog
|
||||
|
||||
- 2026-05-08 Phase 1 — 초기 stub.
|
||||
- 2026-05-10 Manual cleanup — FULL 재작성. 세대 구분, 평가 6종, 코드 7개(template/HF/Anthropic/sampling/BLEU/BERTScore/judge).
|
||||
|
||||
Reference in New Issue
Block a user