f8b21af4be
10_Wiki/Topics 대규모 정리: - 오류 캡처/미완성 stub 문서 227개 제거 - 교차폴더 중복 43클러스터 병합 (63파일 → redirect) - 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건 - 카테고리 MOC 6개 신규 생성 - Graph 섹션 미해결 related-keyword 링크 10,058건 제거 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
179 lines
6.0 KiB
Markdown
179 lines
6.0 KiB
Markdown
---
|
||
id: wiki-2026-0508-natural-language-generation-nlg
|
||
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: 0.93
|
||
verification_status: applied
|
||
tags: [nlp, nlg, text-generation, llm, evaluation]
|
||
raw_sources: []
|
||
last_reinforced: 2026-05-10
|
||
github_commit: pending
|
||
tech_stack: [python, transformers, openai, anthropic, sacrebleu]
|
||
---
|
||
|
||
# Natural Language Generation (NLG)
|
||
|
||
## 한 줄 정의
|
||
|
||
구조화된 입력(데이터·표·의도)이나 unstructured prompt에서 **자연어 텍스트를 생성**하는 NLP 하위 분야. 2020년대 LLM 등장 이후 사실상 "프롬프트 → LLM 호출"이 default가 되며, 전통적 template/규칙 기반은 하이브리드 fallback 역할.
|
||
|
||
## 핵심
|
||
|
||
### 세대 구분
|
||
|
||
- **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.
|
||
|
||
### 파이프라인 (전통)
|
||
|
||
content determination → text structuring → sentence aggregation → lexicalization → referring expression generation → linguistic realization. LLM 시대에는 이 단계가 implicit.
|
||
|
||
### 평가 지표
|
||
|
||
- **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.
|
||
|
||
### 응용
|
||
|
||
요약, 번역, 데이터→문장(report generation), 챗봇, 코드 생성, 광고 문안, 시나리오, RAG 답변, 데이터 증강.
|
||
|
||
## 💻 패턴
|
||
|
||
### Template fallback
|
||
|
||
```python
|
||
def render_weather(city, temp, cond):
|
||
return f"{city}의 현재 기온은 {temp}°C, 날씨는 {cond}입니다."
|
||
```
|
||
|
||
### Hugging Face 생성
|
||
|
||
```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))
|
||
```
|
||
|
||
### Anthropic API (modern default)
|
||
|
||
```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)
|
||
```
|
||
|
||
### Sampling 제어
|
||
|
||
```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]]
|
||
- 응용: [[RAG]] · [[Code-Generation]]
|
||
- Adjacent: [[Large-Language-Models]] · [[Prompt_Engineering|Prompt-Engineering]] · [[ROUGE]]
|
||
|
||
## 🤖 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).
|