Skip to content

NLP 치트시트

텍스트 분석을 위한 자연어 처리(NLP) 기법과 도구입니다.

01

시작하기

NLTK와 spaCy 설치

NLTK는 교육과 연구에 좋고, spaCy는 프로덕션 준비가 되어 있고 빠릅니다. spaCy 모델은 토큰화된 텍스트, POS 태그, 의존 구문 등이 담긴 Doc 객체를 반환합니다. 언어 모델은 'python -m spacy download <model>'로 설치하며, en_core_web_sm은 작은 영어 모델입니다.

nlp
# install NLTK and spaCy
pip install nltk spacy
python -m spacy download en_core_web_sm

import nltk
import spacy

# download NLTK data
nltk.download('punkt')
nltk.download('stopwords')

# load a spaCy model
nlp = spacy.load("en_core_web_sm")
doc = nlp("Apple is looking at buying a U.K. startup.")
for token in doc:
    print(token.text, token.pos_, token.dep_)

spaCy 파이프라인 기본

spaCy의 파이프라인은 모듈형입니다. 토크나이저가 항상 먼저 실행되고, 그다음 tagger, parser, ner 같은 선택 컴포넌트가 실행됩니다. 쓰지 않는 컴포넌트를 끄면 크게 빨라집니다(예: 임베딩에는 tok2vec만 필요). 배치에는 nlp.pipe()를 쓰세요. 루프에서 nlp()를 호출하는 것보다 훨씬 빠릅니다.

nlp
import spacy

# blank pipeline (no pretrained components)
nlp_blank = spacy.blank("en")

# full pipeline: tokenizer -> tagger -> parser -> ner -> ...
nlp = spacy.load("en_core_web_sm")
print(nlp.pipe_names)   # ['tok2vec', 'tagger', 'parser', 'ner', ...]

# disable components you don't need (faster)
nlp_fast = spacy.load("en_core_web_sm", disable=["parser", "ner"])

# process many texts efficiently
docs = list(nlp.pipe(["Hello world.", "SpaCy is fast."]))
# stream from file with nlp.pipe(texts, batch_size=1000)

NLTK 코퍼스와 데이터

NLTK는 많은 고전 코퍼스의 래퍼를 제공합니다. Gutenberg(책), Brown(분류된 텍스트), Reuters(뉴스), WordNet(어휘소). 다운로드는 일회성이고 캐시됩니다. 튜토리얼과 벤치마크에 유용하지만 프로덕션에서는 Hugging Face 'datasets'의 현대적 데이터셋을 선호하세요.

nlp
import nltk

# one-time downloads (cached in ~/nltk_data)
nltk.download('gutenberg')     # Project Gutenberg books
nltk.download('reuters')       # Reuters news corpus
nltk.download('brown')         # Brown corpus (categorized)
nltk.download('wordnet')       # lexical database
nltk.download('averaged_perceptron_tagger')

from nltk.corpus import gutenberg, brown

# first sentences of Moby Dick
print(gutenberg.sents('melville-moby_dick.txt')[0][:8])

# Brown corpus categories
print(brown.categories())      # ['news', 'editorial', 'reviews', ...]
news_words = brown.words(categories='news')

첫 NLP 스크립트 (텍스트 통계)

텍스트를 훑어 보는 빠른 방법: 토큰 수, 문장 수, 고유 표제어, (불용어 제거 후) 내용어 빈도. spaCy Doc은 이터러블이며 doc.sents로 문장을 노출합니다. collections의 Counter가 가장 단순한 빈도 도구입니다.

nlp
import spacy

nlp = spacy.load("en_core_web_sm")
text = "The quick brown fox jumps over the lazy dog. The dog barks."
doc = nlp(text)

# basic stats
print("Tokens:", len(doc))
print("Sentences:", len(list(doc.sents)))
print("Unique words:", len({t.lemma_.lower() for t in doc if t.is_alpha}))

# word frequency
from collections import Counter
words = [t.text.lower() for t in doc if not t.is_stop and t.is_alpha]
print(Counter(words).most_common(5))

텍스트 파일 읽기와 정제

실제 텍스트는 지저분합니다. 인코딩 불일치, HTML, 스마트 쿼트, 대시. 항상 명시적 utf-8로 읽고, 토큰화 전에 공백을 정규화하고 HTML을 제거하세요. 소문자화는 정보를 잃습니다(US vs us). bag-of-words 스타일 작업에만 하고 NER이나 POS 태깅에는 하지 마세요.

nlp
import re
from pathlib import Path

# read with proper encoding
raw = Path("doc.txt").read_text(encoding="utf-8")

# normalize whitespace
text = re.sub(r"\s+", " ", raw).strip()

# remove HTML tags
text = re.sub(r"<[^>]+>", " ", text)

# fix curly quotes / dashes to ASCII
text = text.replace("\u2019", "'").replace("\u201c", '"')
text = text.replace("\u2013", "-").replace("\u2014", "-")

# lowercase only if case-insensitive task
clean = text.lower()
02

토큰화

NLTK 단어/문장 토큰화

NLTK의 punkt 토크나이저는 'Mr.' 같은 약어를 다루는 학습된 모델로 문장을 나눕니다. word_tokenize는 축약형을 분리하는 Treebank 관례를 씁니다('don't' -> 'do' + "n't"). 다운스트림 모델의 학습 방식과 맞는 토크나이저를 고르세요. 어긋난 토큰화는 조용히 성능을 해칩니다.

nlp
from nltk.tokenize import word_tokenize, sent_tokenize

text = "Hello there! How are you? I'm fine, thanks."

# sentence split (handles abbreviations)
sents = sent_tokenize(text)
# ['Hello there!', 'How are you?', "I'm fine, thanks."]

# word split (handles contractions, punctuation)
tokens = word_tokenize(text)
# ['Hello', 'there', '!', 'How', 'are', 'you', '?',
#  'I', "'m", 'fine', ',', 'thanks', '.']

# treebank tokenizer: 'don't' -> ['do', "n't"]
from nltk.tokenize import TreebankWordTokenizer
print(TreebankWordTokenizer().tokenize("don't stop"))

spaCy 토큰화

spaCy의 토크나이저는 비파괴적입니다. 토큰과 원본 텍스트의 정렬을 절대 잃지 않습니다(tok.idx가 문자 오프셋을 줌). NER과 하이라이트에서 중요합니다. 커스텀 infix/exception 규칙으로 파이프라인 전체를 다시 쓰지 않고 분할을 조정할 수 있습니다.

nlp
import spacy

nlp = spacy.load("en_core_web_sm")
doc = nlp("Let's go to N.Y.C. on 03/14/2023 for $5.50!")

# tokens keep their position in the original text
for tok in doc:
    print(f"{tok.text!r:12} start={tok.idx} end={tok.idx + len(tok.text)}")

# spans: contiguous slices of the Doc
span = doc[2:5]   # 'go to N.Y.C.'
print(span.text)

# spaCy never loses alignment to the original string
print(doc.text == "".join(t.text_with_ws for t in doc))  # True

Regex 토크나이저

정규식 토크나이저는 빠르고 결정적입니다. 텍스트 형식을 통제할 때 좋습니다. \w+는 문장부호와 단어로 된 숫자를 버리니 작업과 신중히 짝짓세요. WhitespaceTokenizer가 가장 저렴한 분할이지만 문장부호가 단어에 붙어 남아 보통 2차 정제가 필요합니다.

nlp
from nltk.tokenize import RegexpTokenizer

# words only (drop punctuation)
tok = RegexpTokenizer(r"\w+")
print(tok.tokenize("Hello, world! 123"))   # ['Hello', 'world', '123']

# keep contractions: \w+|'\w+
tok2 = RegexpTokenizer(r"\w+|'\w+")
print(tok2.tokenize("don't stop"))          # ['do', "n't", 'stop']

# whitespace tokenizer (keeps punctuation attached)
from nltk.tokenize import WhitespaceTokenizer
print(WhitespaceTokenizer().tokenize("Hi! Bye."))   # ['Hi!', 'Bye.']

서브워드 토큰화 (BPE / WordPiece)

서브워드 토크나이저(BPE, WordPiece, Unigram, SentencePiece)는 희귀 단어를 흔한 조각으로 나눠 어휘 크기와 커버리지의 균형을 잡습니다. 현대 트랜스포머의 표준입니다. BERT는 WordPiece, GPT-2는 BPE, T5는 SentencePiece를 씁니다. 대상 도메인에 맞추려 자기 코퍼스로 학습하세요.

nlp
from tokenizers import Tokenizer
from tokenizers.models import BPE
from tokenizers.trainers import BpeTrainer
from tokenizers.pre_tokenizers import Whitespace

# train a Byte-Pair-Encoding tokenizer
tokenizer = Tokenizer(BPE(unk_token="[UNK]"))
tokenizer.pre_tokenizer = Whitespace()
trainer = BpeTrainer(
    special_tokens=["[UNK]", "[PAD]", "[CLS]", "[SEP]"],
    vocab_size=8000,
)
tokenizer.train(files=["corpus.txt"], trainer=trainer)

enc = tokenizer.encode("Tokenization is fun.")
print(enc.tokens)        # ['Tok', 'eni', 'zer', ...]
print(enc.ids)           # [34, 912, ...]

커스텀 spaCy 토크나이저 규칙

기본 토크나이저가 잘못 다루는 도메인 용어(URL, 해시태그, 약품명)에는 add_special_case를 쓰세요. infix/prefix/suffix 패턴을 수정하면 전역 분할 동작이 바뀌므로 샘플 집합으로 테스트하세요. 전체 재작성보다 special case를 선호하세요. 파이프라인 나머지와 깔끔히 조합됩니다.

nlp
import spacy
from spacy.tokenizer import Tokenizer
from spacy.util import compile_infix_regex, compile_prefix_regex

nlp = spacy.load("en_core_web_sm")

# add a special-case rule
specials = {"gimme": [{ORTH: "gim"}, {ORTH: "me"}]}
for text, pattern in specials.items():
    nlp.tokenizer.add_special_case(text, pattern)

print([t.text for t in nlp("gimme that")])   # ['gim', 'me', 'that']

# customize infixes (e.g. split on hyphens)
infixes = compile_infix_regex([r"-"])
nlp.tokenizer.infix_finditer = infixes.finditer
print([t.text for t in nlp("state-of-the-art")])

트랜스포머 토크나이저 (Hugging Face)

모델에는 항상 정확히 짝이 되는 토크나이저를 쓰세요. 어긋난 어휘는 조용히 모든 것을 깨뜨립니다. AutoTokenizer.from_pretrained가 올바른 클래스(BertTokenizer, GPT2Tokenizer 등)를 자동 선택합니다. bert-base-uncased는 소문자화하고 [CLS]/[SEP]를 추가하며, cased 변형은 대소문자를 보존합니다. 긴 입력의 오류를 피하려 truncation/max_length를 설정하세요.

nlp
from transformers import AutoTokenizer

# load the tokenizer matching a pretrained model
tok = AutoTokenizer.from_pretrained("bert-base-uncased")

enc = tok("Tokenization with BERT.", return_tensors="pt")
print(enc.keys())         # dict_keys(['input_ids', 'token_type_ids', 'attention_mask'])
print(enc["input_ids"])   # tensor([[101, 19204, 3989, 102]])
print(tok.convert_ids_to_tokens(enc["input_ids"][0]))
# ['[CLS]', 'tokenization', 'with', 'bert', '.', '[SEP]']

# handle long inputs with sliding window
print(tok("Very long text", truncation=True, max_length=512))
03

POS 태깅

NLTK POS 태깅

기본 퍼셉트론 태거는 Penn Treebank 태그집합을 씁니다(NN=명사, VB=동사, JJ=형용사, PRP=대명사...). 문맥에 민감합니다. 'permit'의 동사(VB) vs 명사(NN)는 주변 단어로 중의성이 해소됩니다. POS 태그는 NER, 청킹, 규칙 기반 추출을 개선하는 저렴한 피처입니다.

nlp
import nltk
from nltk.tokenize import word_tokenize

nltk.download('averaged_perceptron_tagger_eng')

tokens = word_tokenize("They refuse to permit us to obtain the permit.")
tags = nltk.pos_tag(tokens)
# [('They', 'PRP'), ('refuse', 'VBP'), ('to', 'TO'),
#  ('permit', 'VB'), ..., ('permit', 'NN'), ('.', '.')]

# note: the two 'permit' tokens get different tags (VB verb vs NN noun)
for word, tag in tags:
    print(f"{word:10} {tag}")

spaCy POS와 형태론

spaCy는 대략적 Universal POS(pos_, 언어 무관)와 세밀한 Treebank 태그(tag_)를 모두 줍니다. morph 객체가 시제, 수, 인칭 같은 형태소 피처를 담습니다. 범언어 작업에는 Universal 태그가 최선이고, 영어 전용 규칙에는 Treebank 태그가 더 많은 정보를 담습니다.

nlp
import spacy
nlp = spacy.load("en_core_web_sm")

doc = nlp("The children were playing happily.")
for tok in doc:
    print(f"{tok.text:12} POS={tok.pos_:6} TAG={tok.tag_:5} "
          f"lemma={tok.lemma_:10} morph={tok.morph}")

# tok.pos_  -> coarse Universal POS (NOUN, VERB, ADJ, ...)
# tok.tag_  -> fine-grained Treebank tag (NN, VBD, JJ, ...)
# tok.morph -> morphological features (Tense=Past, Number=Plur, ...)

Universal POS 태그

Universal POS 태그(Universal Dependencies 출신)는 모든 언어에서 같은 17개 레이블을 써서 다국어 파이프라인에 귀중합니다. NER에서는 PROPN(고유명사) vs NOUN이 중요합니다. POS 비율 세기(어휘 밀도 = NOUN+VERB+ADJ / 전체)는 간단한 텍스트 스타일 피처입니다.

nlp
# Universal Dependencies tagset (17 tags, same across languages)
# ADJ   - adjective       | ADP   - adposition (prep/post)
# ADV   - adverb          | AUX   - auxiliary (is, has)
# CCONJ - coordinating conj | DET  - determiner (the, a)
# INTJ  - interjection    | NOUN  - noun
# NUM   - numeral         | PART  - particle ('s, not)
# PRON  - pronoun         | PROPN - proper noun
# PUNCT - punctuation     | SCONJ - subordinating conj
# SYM   - symbol          | VERB  - verb
# X     - other

import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("She quickly ran to the store.")
nouns = [t.text for t in doc if t.pos_ in ("NOUN", "PROPN")]
verbs = [t.text for t in doc if t.pos_ == "VERB"]

태깅된 코퍼스 읽기

태깅된 코퍼스는 태거 학습/평가와 언어학적 분석에 금같은 자료입니다. Brown은 풍부한 태그집합을 씁니다(제목에 -TL, 인용에 -NC 같은 접미사). Brown 카테고리(뉴스 vs 소설) 간 태그 분포를 비교하면 품사 사용의 문체적 차이가 드러납니다.

nlp
import nltk
from nltk.corpus import brown, treebank

# Brown: each word pre-tagged
sent = brown.tagged_sents(categories='news')[0]
print(sent)   # [('The', 'AT'), ('Fulton', 'NP-TL'), ...]

# Penn Treebank ( Wall Street Journal)
for s in treebank.tagged_sents()[:1]:
    print(s)

# count tag distribution
from collections import Counter
tags = [tag for w, tag in brown.tagged_words(categories='news')]
print(Counter(tags).most_common(5))

규칙 기반과 룩업 태깅

작거나 도메인 특화 데이터에는 backoff 사슬을 가진 단순 태거가 놀랍게 잘 동작합니다. 가장 특화된 태거를 먼저 시도하고, 모르는 단어는 더 넓은 태거로 폴백합니다. UnigramTagger는 단어별 최빈 태그를 학습하고, DefaultTagger('NN')는 보지 못한 단어를 처리하며, RegexTagger는 숫자, 날짜, 대문자 패턴을 잡습니다.

nlp
from nltk.tag import UnigramTagger, DefaultTagger
from nltk.corpus import brown

# fallback: tag everything as NN
default = DefaultTagger('NN')

# unigram: most-likely tag per word (from training data)
train = brown.tagged_sents(categories='news')[:3000]
uni = UnigramTagger(train, backoff=default)

# backoff chain: unigram -> default
test = brown.tagged_sents(categories='news')[3000:3100]
print(f"Accuracy: {uni.evaluate(test):.3f}")

# regex tagger for patterns
from nltk.tag import RegexpTagger
regex = RegexpTagger([(r'^-?[0-9]+(\.[0-9]+)?$', 'CD')], backoff=default)
04

개체명 인식 (NER)

spaCy NER

spaCy의 사전학습 NER은 ORG, PERSON, GPE(지정학), DATE, MONEY 등을 인식합니다. doc.ents는 토크나이저와 정렬된 스팬입니다. displacy.render/serve가 보기 좋은 HTML 시각화를 줍니다. 일반 뉴스 텍스트 정확도는 좋지만 전문 도메인(의료, 법률)은 파인튜닝이 필요합니다.

nlp
import spacy
nlp = spacy.load("en_core_web_sm")

doc = nlp("Apple is buying a U.K. startup for $1 billion in New York.")

for ent in doc.ents:
    print(f"{ent.text:20} {ent.label_:10} {spacy.explain(ent.label_)}")
# Apple              ORG        Companies, agencies, institutions
# U.K.               GPE        Countries, cities, states
# $1 billion         MONEY      Monetary values
# New York           GPE        Countries, cities, states

# visualize
from spacy import displacy
displacy.serve(doc, style="ent")  # opens a browser

NLTK NE 청킹

NLTK의 ne_chunk는 POS 태깅을 문법 기반 청커와 결합합니다. 출력은 PERSON, ORGANIZATION, GPE 등으로 레이블된 개체명이 서브트리인 트리입니다. spaCy보다 느리고 정확도가 낮지만 청킹 개념 학습과 규칙 기반 확장에 유용합니다.

nlp
import nltk
from nltk.tokenize import word_tokenize, sent_tokenize

text = "Barack Obama was born in Hawaii and led the USA."
sents = sent_tokenize(text)

for s in sents:
    tokens = word_tokenize(s)
    tags = nltk.pos_tag(tokens)
    # ne_chunk returns a nested tree of named entities
    tree = nltk.ne_chunk(tags)
    print(tree)
    # (S
    #   (PERSON Barack/NNP Obama/NNP)
    #   was/VBD born/VBN in/IN
    #   (GPE Hawaii/NNP) ...)

# extract just the named entities
for node in tree:
    if hasattr(node, 'label'):
        name = " ".join(w for w, t in node)
        print(node.label(), name)

엔티티 타입과 레이블

spaCy의 영어 NER은 OntoNotes 레이블 집합을 씁니다. 인물, 조직, 장소, 날짜, 금액, 수량의 넓은 커버리지입니다. spacy.explain(label)로 사람이 읽는 설명을 얻으세요. 더 세밀한 타입(예: CEO와 COMPANY 구분)에는 커스텀 모델 학습이나 외부 지식 베이스가 필요합니다.

nlp
import spacy
nlp = spacy.load("en_core_web_sm")

# list all labels the model knows
for label in nlp.get_pipe("ner").labels:
    print(f"{label:12} {spacy.explain(label)}")
# PERSON       People, including fictional
# NORP         Nationalities or religious/political groups
# FAC          Buildings, airports, highways
# ORG          Companies, agencies, institutions
# GPE          Countries, cities, states
# LOC          Non-GPE locations: mountain ranges, bodies of water
# PRODUCT      Vehicles, food, clothing (not services)
# EVENT        Battles, wars, sports events
# DATE         Absolute or relative dates
# TIME         Times smaller than a day
# MONEY        Monetary values
# QUANTITY     Measurements (weight, distance)
# ORDINAL      First, second, ...
# CARDINAL     Numerals that are not dates or amounts

커스텀 NER 모델 학습

사전학습 레이블이 도메인에 맞지 않으면 NER을 파인튜닝하세요. 학습 데이터는 문자 오프셋으로 (text, {entities: [(start, end, label)]}) 형태로 제공합니다. spaCy는 정확한 스팬이 필요합니다. 기존 피처를 활용하려 blank 대신 en_core_web_sm에서 시작하세요. 엔티티 타입당 30~50개 사례가 합리적 최소치이며 use_eval로 조기 종료를 씁니다.

nlp
import spacy
from spacy.training import Example

# start from a blank model (or fine-tune a pretrained one)
nlp = spacy.blank("en")
ner = nlp.add_pipe("ner")
ner.add_label("DRUG")

# training data: text + character offsets of entities
TRAIN = [
    ("Take aspirin daily.", {"entities": [(5, 11, "DRUG")]}),
    ("Ibuprofen reduces fever.", {"entities": [(0, 9, "DRUG")]}),
]

optimizer = nlp.initialize()
for epoch in range(30):
    for text, ann in TRAIN:
        doc = nlp.make_doc(text)
        nlp.update([Example.from_dict(doc, ann)], sgd=optimizer)

# save and use
nlp.to_disk("custom_ner")
doc = nlp("Give metformin 500mg.")
print([(e.text, e.label_) for e in doc.ents])  # [('metformin', 'DRUG')]

엔티티 링킹과 위키피케이션

NER은 언급을 찾고, 엔티티 링킹은 이를 지식 베이스 항목으로 중의성을 해소합니다('Apple'이 어느 것? 회사 vs 과일). 완전한 링킹에는 KB 후보 생성기와 중의성 해소기가 필요합니다. spaCy의 내장 EntityLinker는 KB를 직접 만들어야 하고, 프로덕션에서는 REL, mGENRE 또는 상용 API(Google KG, Bing Entity Search)를 고려하세요.

nlp
# Entity linking maps a mention to a unique ID in a knowledge base
# (e.g. "Apple" -> Apple Inc. the company, not the fruit)

import spacy
nlp = spacy.load("en_core_web_sm")

# spaCy's EntityLinker requires a knowledge base (KB).
# Building one from Wikipedia/Wikidata is involved; in practice use:

# Option 1: spaCy + Wikipedia-based KB (spacy-entity-linker)
# pip install spacy-entity-linker
# from spacy_entity_linker import EntityLinker
# linker = EntityLinker()
# nlp.add_pipe("entityLinker", last=True)

# Option 2: a dedicated library
# import entitylinking  # or use a Wikidata API directly

# Example query via Wikidata SPARQL
import requests
url = "https://www.wikidata.org/w/api.php"
params = {"action": "wbsearchentities", "search": "Apple",
          "language": "en", "format": "json"}
print(requests.get(url, params=params).json())
05

스테밍과 표제어 추출

Porter Stemmer

PorterStemmer는 고정된 접미사 제거 규칙 시퀀스를 적용합니다. 빠르고 결정적이지만 비단어를 만들고('easili', 'studi') 문맥을 무시합니다. 'ran'은 벗길 접미사가 없어 'ran'으로 남습니다. 어간 일관성이 정확성보다 중요한 검색엔진과 토픽 모델에 적합합니다.

nlp
from nltk.stem import PorterStemmer

stemmer = PorterStemmer()
for w in ["running", "runs", "ran", "easily", "fairness", "studies"]:
    print(f"{w:10} -> {stemmer.stem(w)}")
# running    -> run
# runs       -> run
# ran        -> ran        (Porter doesn't handle irregulars)
# easily     -> easili     (sometimes ugly)
# fairness   -> fair
# studies    -> studi

# fast, rule-based, deterministic
print([stemmer.stem(t) for t in "the cats are running".split()])

Snowball Stemmer

SnowballStemmer는 현대화된 Porter('English' 버전)이며 15개 이상의 다른 언어를 더합니다. 약간 더 정확하고 비영어 텍스트를 별도 설정 없이 지원합니다. 사전 없이 다국어 스테밍이 필요하면 Snowball이 실용적 기본값이고, 더 높은 품질이면 표제어 추출기로 전환하세요.

nlp
from nltk.stem import SnowballStemmer

# Snowball = improved Porter, supports many languages
print(SnowballStemmer.languages)
# ['arabic', 'danish', 'dutch', 'english', 'finnish', 'french',
#  'german', 'hungarian', 'italian', 'norwegian', 'porter',
#  'portuguese', 'romanian', 'russian', 'spanish', 'swedish']

en = SnowballStemmer("english")
print(en.stem("running"), en.stem("fairly"), en.stem("studies"))
# run fair studi

# compare two languages
fr = SnowballStemmer("french")
print(fr.stem("mangerons"))   # mang

WordNet Lemmatizer

표제어 추출은 WordNet을 찾아 실제 사전 단어를 반환합니다('better' -> 'good', 'mice' -> 'mouse'). 중의성 해소에 POS가 필요합니다('running'은 명사 vs 동사). 다운스트림 피처(BoW, TF-IDF)가 정형 형태의 이득을 보면 POS 태깅 오버헤드는 가치가 있습니다. 사전 조회 때문에 스테밍보다 느립니다.

nlp
import nltk
from nltk.stem import WordNetLemmatizer
nltk.download('wordnet')

lem = WordNetLemmatizer()

# without POS, defaults to NOUN
print(lem.lemmatize("running"))            # running (treated as noun)
print(lem.lemmatize("running", pos='v'))   # run      (verb)
print(lem.lemmatize("better", pos='a'))    # good     (adjective)
print(lem.lemmatize("mice"))               # mouse    (irregular plural)

# pipeline: tokenize -> POS tag -> lemmatize with correct POS
from nltk.tokenize import word_tokenize
from nltk import pos_tag
words = word_tokenize("The cats were running quickly.")
treebank_to_wordnet = {'N': 'n', 'V': 'v', 'J': 'a', 'R': 'r'}
for w, t in pos_tag(words):
    wn_pos = treebank_to_wordnet.get(t[0], 'n')
    print(w, '->', lem.lemmatize(w, pos=wn_pos))

spaCy 표제어 추출

spaCy는 파이프라인 안에서 표제어 추출을 합니다. POS를 인식하고 불규칙형을 별도 코드 없이 처리합니다('ate'->'eat', 'were'->'be'). text 대신 lemma_를 쓰면 'cat'/'cats'가 하나의 피처로 합쳐져 어휘 크기가 줄어듭니다. 다국어 모델은 표제어 추출 품질이 들쭉날쭉하니 모델의 정확도 보고서를 확인하세요.

nlp
import spacy
nlp = spacy.load("en_core_web_sm")

doc = nlp("The cats were running faster. I ate two apples.")
for tok in doc:
    if tok.text.lower() != tok.lemma_:
        print(f"{tok.text:10} -> {tok.lemma_}")
# cats       -> cat
# were       -> be
# running    -> run
# faster     -> fast
# ate        -> eat
# apples     -> apple

# context-aware, handles irregulars automatically
# use lemma_ instead of text for bag-of-words features
docs_tokens = [[t.lemma_.lower() for t in nlp(d) if not t.is_stop]
               for d in ["Cats run.", "The cat ran."]]

스테밍 vs 표제어 추출

스테밍은 빠르지만 비단어를 만들고 일부 용도에는 너무 공격적으로 합칩니다. 표제어 추출은 유효한 단어를 반환하고 POS를 존중하지만 사전 조회 비용이 듭니다. bag-of-words 피처에는 둘 다 어휘를 줄이고, 사용자에게 보이는 출력(예: 키워드 목록)에는 항상 표제어 추출을 쓰세요. 대규모 검색에는 스테밍이 실용적 선택입니다.

nlp
import spacy
from nltk.stem import PorterStemmer
nlp = spacy.load("en_core_web_sm")
stem = PorterStemmer()

words = ["studies", "studying", "better", "feet", "running", "happily"]

print(f"{'word':12}{'stem':12}{'lemma':12}")
for w in words:
    lemma = nlp(w)[0].lemma_
    print(f"{w:12}{stem.stem(w):12}{lemma:12}")
# studies     studi       study
# studying    studi       study
# better      better      good      <- lemma handles irregular
# feet        feet        foot
# running     run         run
# happily     happili     happily

# rule of thumb:
#   search/indexing/topic-models -> stemming (fast)
#   interpretation/visualization -> lemmatization (accurate)
06

불용어

NLTK 불용어

NLTK는 언어별 컴팩트한 불용어 목록을 제공합니다(영어 약 180단어). O(1) 조회를 위해 set을 쓰세요. 목록이 소문자이므로 검사 전 항상 소문자화하세요. 필터링은 어휘를 줄이고 정보량 적은 단어를 제거해 토픽 모델과 검색 인덱스에 유용하지만, 감성 분석에는 해롭습니다("not good"의 부정이 사라짐).

nlp
import nltk
from nltk.corpus import stopwords
nltk.download('stopwords')

# 18 languages available
print(stopwords.fileids())
# ['arabic', 'english', 'french', 'german', 'spanish', ...]

en = set(stopwords.words('english'))
print(len(en))                # 179
print("the" in en)            # True
print("python" in en)         # False

# remove from a token list
from nltk.tokenize import word_tokenize
text = "The quick brown fox is very lazy indeed"
tokens = [w for w in word_tokenize(text.lower()) if w.isalpha()]
filtered = [w for w in tokens if w not in en]
print(filtered)   # ['quick', 'brown', 'fox', 'lazy']

spaCy 불용어

spaCy는 토큰별 is_stop을 표시하며 축약형('isn't')도 포함합니다. 기본 목록은 NLTK보다 큽니다(326단어). 깨끗한 내용어 추출을 위해 is_stop을 is_punct, is_alpha와 함께 쓰세요. 목록은 nlp.Defaults.stop_words에 있으며 파이프라인별로 런타임에 편집할 수 있습니다.

nlp
import spacy
nlp = spacy.load("en_core_web_sm")

# access the stopword set
print(len(nlp.Defaults.stop_words))        # 326
print("the" in nlp.Defaults.stop_words)    # True

# tokens expose is_stop directly
doc = nlp("The quick fox isn't lazy")
for tok in doc:
    print(f"{tok.text:8} is_stop={tok.is_stop}")
# The      is_stop=True
# quick    is_stop=False
# isn't    is_stop=True   (contraction included)

# content words only
content = [t.text for t in doc if not t.is_stop and not t.is_punct]

안전한 불용어 제거

무작정 불용어를 제거하면 정보가 파괴됩니다. 부정('not good' -> 'good'), 다단어 엔티티('New York'은 괜찮지만 'out of'가 중요할 수 있음), 질문 구조('What is X?' -> 'X?'). 감성 분석에서는 항상 부정어를 유지하세요. NER에서는 개체 추출 전에 불용어를 절대 제거하지 마세요.

nlp
import spacy
nlp = spacy.load("en_core_web_sm")

def remove_stopwords(text, keep_negations=True):
    doc = nlp(text)
    out = []
    for tok in doc:
        if tok.is_stop or tok.is_punct:
            # keep negations for sentiment tasks
            if keep_negations and tok.lemma_ in ("not", "no", "never"):
                out.append(tok.text)
                continue
            continue
        out.append(tok.text)
    return " ".join(out)

print(remove_stopwords("I do not like green eggs and ham."))
# 'not like green eggs ham .'

# bigrams preserve phrases that stopwords broke:
# 'New York' should NOT lose its inner stopwords...

커스텀 불용어 목록

일반 목록은 도메인 노이즈를 놓칩니다(뉴스의 'reuters', 'inc', 'said'). 코퍼스에서 매우 고빈도·저정보 단어를 채굴해 추가하세요. 반대로 작업이 신경 쓰는 단어(부정어, 태도 감지의 조동사)는 목록에서 빼세요. 수정된 파이프라인을 저장해 커스텀 목록이 모델과 함께 다니게 하세요.

nlp
import spacy
nlp = spacy.load("en_core_web_sm")

# add domain-specific stopwords
domain_stops = {"said", "says", "say", "according", "reuters", "inc", "ltd"}
for w in domain_stops:
    nlp.Defaults.stop_words.add(w)
    # also set the lexeme attribute
    lex = nlp.vocab[w]
    lex.is_stop = True

# remove a word that you DO want to keep
nlp.Defaults.stop_words.discard("not")
nlp.vocab["not"].is_stop = False

# persist by saving the modified model
# nlp.to_disk("my_model_with_stops")

불용어를 유지해야 할 때

딥 모델(BERT, GPT)은 불용어를 포함한 자연 텍스트로 학습됐습니다. 모델이 구문 파악에 기능어에 의존하므로 미리 제거하면 성능이 떨어집니다. 불용어 제거는 얕은 모델의 피처 엔지니어링 트릭입니다. 두 방식 모두 평가해 검증 지표에서 더 높은 쪽을 유지하세요.

nlp
# Stopword removal HELPS:
#   - bag-of-words / TF-IDF (smaller vocab, less noise)
#   - topic modeling (LDA wants content words)
#   - search indexing (precision up, index smaller)

# Stopword removal HURTS:
#   - sentiment analysis ("not good" != "good")
#   - NER / entity extraction (alignment breaks)
#   - syntax parsing (function words are syntactic glue)
#   - transformer models (they were pretrained WITH stopwords)

from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("bert-base-uncased")
# NEVER strip stopwords before feeding BERT — the model
# expects natural text and uses function words syntactically.

# rule: only remove stopwords for shallow features (BoW/TF-IDF),
# and only if you've checked it doesn't hurt your metric.
07

Bag of Words와 벡터화

CountVectorizer 기본

CountVectorizer는 문자열 목록을 희소 문서-단어 행렬로 바꿉니다. fit_transform이 어휘를 학습하고 한 단계에 변환하며, transform은 학습된 어휘를 새 데이터에 재사용합니다(중요. 테스트 데이터에 다시 fit하지 마세요). 행렬은 큰 어휘를 효율적으로 다루려고 희소입니다. 기본 토큰 패턴 \b\w\w+\b는 한 글자 토큰을 버립니다.

nlp
from sklearn.feature_extraction.text import CountVectorizer

docs = ["The cat sat on the mat.", "The dog sat on the log."]

# default: lowercase, word tokenizer (\b\w\w+\b), unigrams
vec = CountVectorizer()
X = vec.fit_transform(docs)
print(X.shape)            # (2, 6)  -> 2 docs, 6 unique words
print(vec.get_feature_names_out())
# ['cat' 'dog' 'log' 'mat' 'on' 'sat' 'the']

print(X.toarray())
# [[1 0 0 1 1 1 2]   'the' appears twice in doc 0
#  [0 1 1 0 1 1 2]]

# transform new text with the fitted vocabulary
new = vec.transform(["The cat and the dog."])

N-gram

N-gram은 유니그램이 잃는 지역 단어 순서를 잡습니다('not good' vs 'good'). 바이그램은 어휘를 크게 늘리므로(이차적으로) min_df(희귀 제거)나 max_features(상위 K 제한)와 결합하세요. 트라이그램은 bag-of-words에서 드물게 이득이며 더 긴 문맥은 임베딩으로 전환하세요.

nlp
from sklearn.feature_extraction.text import CountVectorizer

docs = ["I love this movie", "I hate this movie"]

# unigrams + bigrams
vec = CountVectorizer(ngram_range=(1, 2))
X = vec.fit_transform(docs)
print(vec.get_feature_names_out())
# ['hate', 'hate this', 'love', 'love this', 'movie',
#  'this', 'this movie']

# bigrams capture phrases like "not good", "New York"
# but explode the vocabulary -> pair with min_df / max_features
vec2 = CountVectorizer(ngram_range=(2, 2), min_df=2)
# (2,2) = bigrams only; min_df=2 keeps bigrams seen >= 2 times

HashingVectorizer

HashingVectorizer는 상태 없이 각 토큰을 컬럼 인덱스로 해싱하므로 저장할 어휘가 없습니다. 스트리밍이나 메모리 제한 환경에 좋습니다. 절충점: 컬럼이 어떤 단어를 나타내는지 검사할 수 없고 충돌이 피처를 합칩니다. 선형 모델에서 카운트를 상쇄하는 부호 반전을 피하려 alternate_sign=False로 설정하세요.

nlp
from sklearn.feature_extraction.text import HashingVectorizer

# stateless: no vocabulary kept, uses feature hashing
vec = HashingVectorizer(n_features=2**18, alternate_sign=False)
X = vec.transform(["doc one", "doc two"])
print(X.shape)   # (2, 262144)

# pros: no memory for vocabulary, streamable, fit_transform = transform
# cons: hashes are not interpretable, possible collisions,
#       no inverse_transform (can't map feature -> word)

# use for: very large / streaming corpora where you don't need
# to know which word a column corresponds to

어휘 제어

min_df와 max_df가 가장 유용한 노브입니다. 각각 희귀 오타와 코퍼스 전체 불용어를 제거해 행렬을 줄이고 노이즈를 낮춥니다. max_features가 메모리를 위해 어휘를 제한합니다. 커스텀 token_pattern이 길이나 문자 클래스로 필터합니다. 실행 간 컬럼을 안정적으로 유지해야 한다면 고정 어휘가 편리합니다.

nlp
from sklearn.feature_extraction.text import CountVectorizer

docs = ["a a a b b c rareword commontoken"] * 5

vec = CountVectorizer(
    min_df=2,          # ignore terms in <2 docs
    max_df=0.9,        # ignore terms in >90% of docs (corpus-specific stops)
    max_features=1000, # keep only top-1000 by frequency
    stop_words='english',
    token_pattern=r"\b[a-z]{2,}\b",  # only 2+ letter words
)
X = vec.fit_transform(docs)
print(vec.get_feature_names_out())

# fix a custom vocabulary (only these words are counted)
vec_fixed = CountVectorizer(vocabulary=["cat", "dog", "fish"])
print(vec_fixed.get_feature_names_out())

희소 행렬 연산

문서-단어 행렬은 희소합니다(대부분 0). 메모리 폭발을 피하려 희소 상태를 유지하세요(100k×50k 밀집 float64 행렬은 40GB가 필요). .sum(axis=0), .multiply(), 희소 객체에 대한 슬라이싱을 쓰세요. .toarray()는 작은 슬라이스에만 호출합니다. CSR 형식은 행 슬라이싱에 최적이며 컬럼 슬라이싱에는 CSC로 변환하세요.

nlp
from sklearn.feature_extraction.text import CountVectorizer
import numpy as np
from scipy.sparse import csr_matrix

docs = ["the cat sat", "the dog ran", "the cat ran"]
vec = CountVectorizer()
X = vec.fit_transform(docs)   # CSR sparse matrix

print(type(X))                # <class 'scipy.sparse.csr_matrix'>
print(X.shape, X.nnz)         # (3, 5) 9 non-zero entries

# NEVER call .toarray() on huge matrices — they explode in memory.
# operate on sparse directly:
col_sums = np.asarray(X.sum(axis=0)).ravel()   # document frequency
print(dict(zip(vec.get_feature_names_out(), col_sums)))

# find docs containing a word
word_idx = vec.vocabulary_["cat"]
rows_with_cat = X[:, word_idx].nonzero()[0]
print("docs with 'cat':", rows_with_cat)   # [0, 2]
08

TF-IDF

TfidfVectorizer 기본

TF-IDF는 많은 문서에 나오는 단어(판별력 낮음)의 가중치를 낮추고 희귀·정보성 단어의 가중치를 높입니다. TfidfVectorizer는 CountVectorizer + TfidfTransformer를 결합하고 행을 L2 정규화해 문서 길이가 지배하지 않게 합니다. 선형 모델의 텍스트 분류 기본 피처입니다.

nlp
from sklearn.feature_extraction.text import TfidfVectorizer

docs = ["the cat sat on the mat",
        "the dog sat on the log",
        "cats and dogs are pets"]

vec = TfidfVectorizer()        # default: L2-normalized rows
X = vec.fit_transform(docs)
print(vec.get_feature_names_out())

# tf-idf = term_freq * log(N / df) * (variations exist)
# down-weights words common across all docs ('the', 'sat')
print(X.toarray().round(3))

# each row is L2-normalized to length 1
import numpy as np
print(np.linalg.norm(X.toarray(), axis=1))   # [1. 1. 1.]

TfidfTransformer와 수식

smooth_idf가 보지 못한 용어의 0 나눗셈을 피하려 +1을 더합니다. sublinear_tf는 원시 카운트를 1+log(count)로 바꿔 문서 내 매우 빈번한 단어의 영향력을 제한합니다. 용어가 수십 번 반복될 수 있는 긴 문서에 유용합니다. norm='l2'가 표준이며 원시 크기를 원하면 None을 쓰세요.

nlp
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.pipeline import Pipeline

# equivalent to TfidfVectorizer but in two steps
pipe = Pipeline([
    ("counts", CountVectorizer()),
    ("tfidf", TfidfTransformer(
        norm='l2',
        use_idf=True,
        smooth_idf=True,        # idf = ln((1+N)/(1+df)) + 1  (avoids div-by-zero)
        sublinear_tf=False,     # if True: tf = 1 + log(count)
    )),
])

# sublinear_tf compresses high counts:
#   count 5 -> tf 5 (linear) vs tf 1+log(5)≈2.6 (sublinear)
# useful when a word repeating 100x isn't 100x more important
pipe2 = Pipeline([
    ("counts", CountVectorizer()),
    ("tfidf", TfidfTransformer(sublinear_tf=True)),
])

TF-IDF 가중치 해석

문서별 상위 TF-IDF 피처는 그 문서의 독특한 내용 요약입니다. 모든 문서에 나오는 단어는 idf≈1(낮은 가중치)이고 한 문서에만 나오는 단어가 최고 idf를 받습니다. vec.idf_를 검사하면 학습된 전역 가중치를 볼 수 있습니다. 분류기 학습 전의 훌륭한 정상성 검사입니다.

nlp
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np

docs = ["machine learning models", "deep learning networks",
        "natural language processing"]

vec = TfidfVectorizer()
X = vec.fit_transform(docs)
names = vec.get_feature_names_out()

# top features per document
for i, doc in enumerate(docs):
    row = X[i].toarray().ravel()
    top = np.argsort(row)[::-1][:3]
    print(f"doc {i}: {[(names[j], round(row[j], 3)) for j in top]}")
# doc 0: [('machine', 0.58), ('models', 0.58), ('learning', 0.41)]
# doc 1: [('deep', 0.5), ('networks', 0.5), ...]
# doc 2: [('natural', 0.41), ('processing', 0.41), ('language', 0.41)]

# inspect the learned idf weights
idf = dict(zip(names, vec.idf_))
print(sorted(idf.items(), key=lambda x: x[1])[:3])   # lowest idf = most common

N-gram과 불용어를 곁들인 TF-IDF

TF-IDF를 바이그램과 짝지으면 유니그램이 잃는 부정('not good')이 보존됩니다. stop_words='english' + min_df가 어휘를 줄입니다. 이 TfidfVectorizer + LinearSVC/LogisticRegression 조합은 놀랍도록 강한 기저선입니다. BERT로 이기려면 레이블된 데이터가 충분해야 합니다.

nlp
from sklearn.feature_extraction.text import TfidfVectorizer

docs = ["not good at all", "very good indeed", "not bad actually"]

vec = TfidfVectorizer(
    stop_words='english',
    ngram_range=(1, 2),        # unigrams + bigrams
    min_df=1,
    sublinear_tf=True,
    max_features=5000,
)
X = vec.fit_transform(docs)
print(vec.get_feature_names_out())
# bigrams like 'not good', 'not bad' preserve negation

# this combination is a strong baseline for text classification
# with LogisticRegression or LinearSVC

유사도와 검색을 위한 TF-IDF

TF-IDF 벡터 위의 코사인 유사도는 고전적 키워드 검색 기저선입니다. 쿼리와 문서가 벡터가 되고 코사인 각도로 순위가 매겨집니다. 학습 데이터 없이 동작하지만 공유 어휘만 매칭합니다. 의미상 유사하지만 어휘가 다른 텍스트('ML' vs 'machine learning')는 매칭되지 않습니다. 의미 검색에는 임베딩(sentence-transformers)을 쓰세요.

nlp
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

corpus = [
    "Machine learning is fun",
    "Python is great for ML",
    "I love cooking pasta",
]
query = ["learning machine"]

vec = TfidfVectorizer()
X = vec.fit_transform(corpus)
q = vec.transform(query)

# cosine similarity between query and each doc
sims = cosine_similarity(q, X).ravel()
for doc, score in sorted(zip(corpus, sims), key=lambda x: -x[1]):
    print(f"{score:.3f}  {doc}")
# 0.580  Machine learning is fun
# 0.000  I love cooking pasta

# this is essentially a tiny search engine
09

단어 임베딩 (Word2Vec / GloVe / FastText)

gensim Word2Vec

Word2Vec은 문맥을 예측하거나(skip-gram) 문맥으로 단어를 예측하며(CBOW) 밀집 벡터를 학습합니다. skip-gram(sg=1)은 작은 데이터와 희귀 단어에서 더 잘 동작하고, CBOW는 더 빠릅니다. min_count가 희귀 단어를 걸러냅니다. 진짜 모델은 수백만 토큰이 필요하므로 대부분의 애플리케이션은 위키백과로 학습하거나 사전학습 벡터를 사용하세요.

nlp
from gensim.models import Word2Vec
from gensim.utils import simple_preprocess

sentences = [
    "the cat sat on the mat".split(),
    "the dog sat on the log".split(),
    "cats and dogs are pets".split(),
]
# simple_preprocess lowercases and tokenizes
sents = [simple_preprocess(" ".join(s)) for s in sentences]

model = Word2Vec(
    sentences=sents,
    vector_size=100,    # embedding dimension
    window=5,           # context window size
    min_count=1,        # ignore words with freq < min_count
    workers=4,
    sg=1,               # 1 = skip-gram, 0 = CBOW
    epochs=10,
)

print(model.wv["cat"].shape)            # (100,)
print(model.wv.most_similar("cat", topn=3))

커스텀 임베딩 학습

제너레이터(SentenceIterator)를 써서 코퍼스가 디스크에서 스트리밍되게 하세요. gensim은 스트리밍용으로 만들어져 전부를 RAM에 담지 않습니다. min_count=5가 오타와 희귀 단어를 제거하고, negative=10은 skip-gram의 표준입니다. 데이터가 더 오면 저장 후 학습을 재개하세요. 배포 전 유추와 유사도 작업으로 평가하세요.

nlp
from gensim.models import Word2Vec
from gensim.utils import simple_preprocess
from pathlib import Path

# read a large corpus line by line (don't load all into memory)
class SentenceIterator:
    def __init__(self, path):
        self.path = Path(path)
    def __iter__(self):
        for line in self.path.open(encoding="utf-8"):
            yield simple_preprocess(line)

sentences = SentenceIterator("corpus.txt")

model = Word2Vec(
    sentences,
    vector_size=200,
    window=8,
    min_count=5,         # drop very rare words
    workers=8,
    epochs=5,
    negative=10,         # negative samples per positive (skip-gram)
)
model.save("w2v.model")

# resume training later
# model = Word2Vec.load("w2v.model")
# model.train(more_sentences, total_examples=len(more), epochs=5)

유사도와 유추

Word2vec은 유추 관계를 포착하는 것으로 유명합니다(king - man + woman ≈ queen). 비슷한 문맥이 비슷한 벡터를 만들기 때문입니다. similarity는 [-1, 1]의 코사인을 반환하고, doesnt_match는 재미있는 이상값 탐지기입니다. 사전학습 Google News 벡터는 300만 단어를 커버하지만 3GB입니다. GloVe나 fastText가 더 실용적인 때가 많습니다.

nlp
from gensim.models import KeyedVectors

# load pretrained Google News vectors (3GB, 3M words)
# Download: https://code.google.com/archive/p/word2vec/
model = KeyedVectors.load_word2vec_format("GoogleNews-vectors-negative300.bin",
                                          binary=True)

# similarity
print(model.similarity("cat", "dog"))        # ~0.86
print(model.similarity("cat", "car"))        # ~0.28

# analogy: king - man + woman = queen
print(model.most_similar(positive=["king", "woman"],
                         negative=["man"], topn=1))
# [('queen', 0.71)]

# odd one out
print(model.doesnt_match("cat dog car horse".split()))   # 'car'

# which word doesn't fit
print(model.most_similar("python", topn=5))

FastText

FastText는 문자 n-gram(서브워드) 벡터를 학습하도록 Word2Vec을 확장해 보지 못한 단어도 임베딩할 수 있습니다('cat'+'ing'에서 'catting'). 형태론적으로 풍부한 언어와 오타에 크게 도움이 됩니다. 서브워드 조회 때문에 Word2Vec보다 약간 느리지만 대부분의 실제 텍스트에서 OOV 처리가 가치가 있습니다.

nlp
from gensim.models import FastText

sentences = [
    "the cat sat on the mat".split(),
    "dogs and cats are friends".split(),
]

# FastText learns subword (character n-gram) embeddings
model = FastText(
    sentences,
    vector_size=100,
    window=5,
    min_count=1,
    min_n=3,            # min char n-gram
    max_n=6,            # max char n-gram
    epochs=10,
)

# KEY advantage: handles out-of-vocabulary words
print("catting" in model.wv)            # False (not seen in training)
print(model.wv["catting"].shape)        # (100,)  -> still gets a vector!
# vector is averaged from subword n-grams of 'catting'

print(model.wv.most_similar("cat", topn=3))

GloVe 벡터 로드

GloVe(Global Vectors)는 예측이 아니라 공기어 카운트로 학습되며 Word2Vec과 비교 가능한 벡터를 만듭니다. Stanford는 6B 토큰으로 학습한 50/100/200/300차원 버전을 제공합니다. Word2Vec API를 재사용하려 gensim 형식으로 변환하세요. 300d 벡터는 메모리 약 1.5GB를 예상하세요.

nlp
# GloVe: pretrained on Wikipedia+Gigaword
# Download: https://nlp.stanford.edu/projects/glove/
# Files: glove.6B.50d.txt, glove.6B.100d.txt, glove.6B.200d.txt, glove.6B.300d.txt

from gensim.scripts.glove2word2vec import glove2word2vec
from gensim.models import KeyedVectors

# convert GloVe format to word2vec format (one-time)
glove2word2vec("glove.6B.100d.txt", "glove.6B.100d.w2v.txt")

# load
glove = KeyedVectors.load_word2vec_format("glove.6B.100d.w2v.txt")
print(glove["king"].shape)        # (100,)
print(glove.most_similar("king", topn=3))

# fast alternative: load directly into a dict
import numpy as np
def load_glove(path, dim=100):
    embeddings = {}
    with open(path, encoding="utf-8") as f:
        for line in f:
            parts = line.split()
            embeddings[parts[0]] = np.asarray(parts[1:], dtype="float32")
    return embeddings

t-SNE로 임베딩 시각화

t-SNE는 고차원 벡터를 시각화용 2D로 투영합니다. 그림에서 가까운 점은 임베딩 공간에서 비슷합니다. 점 수에 따라 perplexity를 5~50 사이로 두세요. 주의: t-SNE는 전역 거리를 왜곡하므로 측정이 아니라 탐색에 쓰세요. UMAP이 t-SNE보다 구조를 더 잘 보존할 때가 많습니다.

nlp
import numpy as np
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
from gensim.models import KeyedVectors

model = KeyedVectors.load_word2vec_format("glove.6B.100d.w2v.txt")

# pick a small set of related words
words = ["king", "queen", "man", "woman", "paris", "france",
         "london", "england", "dog", "cat", "horse", "cow"]
vectors = np.array([model[w] for w in words])

# reduce 100d -> 2d with t-SNE
tsne = TSNE(n_components=2, random_state=42, perplexity=5)
coords = tsne.fit_transform(vectors)

plt.figure(figsize=(8, 6))
for w, (x, y) in zip(words, coords):
    plt.scatter(x, y)
    plt.annotate(w, (x, y), xytext=(5, 5), textcoords="offset points")
plt.savefig("embeddings_tsne.png", dpi=120)
plt.show()
10

문맥적 임베딩 (BERT)

Hugging Face Transformers 기본

AutoTokenizer/AutoModel은 Hub의 모델 이름에서 올바른 클래스를 자동 선택합니다. BERT, RoBERTa, DistilBERT 중 무엇인지 알 필요가 없습니다. last_hidden_state는 토큰당 768차원 벡터이고, pooler_output은 [CLS] 표현입니다. 문장 임베딩에는 [CLS]만으로는 부족할 때가 많으니 sentence-transformer를 쓰세요.

nlp
from transformers import AutoTokenizer, AutoModel
import torch

# load any pretrained model by name from the Hub
model_name = "bert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModel.from_pretrained(model_name)

inputs = tokenizer("Hello, BERT!", return_tensors="pt")
print(inputs.keys())   # input_ids, token_type_ids, attention_mask

with torch.no_grad():
    outputs = model(**inputs)

# last hidden state: (batch, seq_len, hidden_size)
print(outputs.last_hidden_state.shape)   # torch.Size([1, 6, 768])

# pooled output: [CLS] token passed through a linear+tanh
print(outputs.pooler_output.shape)        # torch.Size([1, 768])

BERT 토큰 임베딩

BERT의 정의적 특징: 'bank'의 벡터가 'river bank'와 'bank account'에서 다릅니다. 어텐션이 문맥을 반영하기 때문입니다. 이것이 Word2Vec/GloVe의 가장 큰 약점인 다의어 문제를 해결합니다. 각 토큰의 벡터는 전체 시퀀스로부터 만들어진 문맥화된 768차원 표현입니다.

nlp
from transformers import AutoTokenizer, AutoModel
import torch

tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
model = AutoModel.from_pretrained("bert-base-uncased")

# contextual: 'bank' embeds differently in river vs money context
texts = ["I sat by the river bank.", "I deposited cash at the bank."]
for t in texts:
    inputs = tokenizer(t, return_tensors="pt")
    with torch.no_grad():
        out = model(**inputs)
    # find the index of 'bank'
    idx = (inputs["input_ids"][0] == tokenizer.convert_tokens_to_ids("bank")).nonzero()[0]
    vec = out.last_hidden_state[0, idx[0]]
    print(f"{t[:25]:25} bank-vec[:3] = {vec[:3].tolist()}")

# the two 'bank' vectors DIFFER -> this is the whole point of BERT
# (static embeddings like Word2Vec would give the same vector both times)

Sentence Transformers

일반 BERT의 [CLS]는 부실한 문장 임베딩입니다(유사도 점수가 불신뢰). sentence-transformers는 대조 손실로 모델을 파인튜닝해 코사인 유사도가 의미적 근접성을 반영하게 합니다. all-MiniLM-L6-v2가 기본 선택입니다. 384차원, 빠르고 훨씬 큰 모델과 경쟁합니다. 의미 검색, 클러스터링, 중복 제거에 이상적입니다.

nlp
# pip install sentence-transformers
from sentence_transformers import SentenceTransformer, util

# models tuned to produce good sentence-level embeddings
model = SentenceTransformer("all-MiniLM-L6-v2")   # 384d, fast & strong

sentences = [
    "The cat sits on the mat.",
    "A feline is resting on a rug.",
    "Machine learning is fascinating.",
]
emb = model.encode(sentences, convert_to_tensor=True, normalize_embeddings=True)

# semantic similarity via cosine
print(util.cos_sim(emb, emb).round(3))
# [[1.    0.678 0.089]
#  [0.678 1.    0.107]
#  [0.089 0.107 1.   ]]

# semantic search: rank corpus by similarity to a query
query = model.encode("where is the cat?", convert_to_tensor=True)
hits = util.semantic_search(query, emb)[0]
print(hits)   # ranks 'cat sits on the mat' highest

Pooled vs 토큰 임베딩

레이어마다 다른 정보를 인코딩합니다. 하위 레이어는 구문적, 상위 레이어는 의미적입니다. [CLS]는 (파인튜닝된) 분류에 동작하지만 평균 풀링이 일반적으로 더 나은 공짜 문장 벡터입니다. 마지막 4개 레이어를 연결하는 것이 원조 BERT 피처 추출 레시피이며 NER 같은 토큰 수준 작업에서 여전히 잘 동작합니다.

nlp
from transformers import AutoTokenizer, AutoModel
import torch

tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
model = AutoModel.from_pretrained("bert-base-uncased", output_hidden_states=True)

inputs = tokenizer("I love NLP", return_tensors="pt")
with torch.no_grad():
    out = model(**inputs)

# all 13 layers (embedding + 12 transformer layers)
hidden = out.hidden_states          # tuple of (1, seq, 768), len 13
print(len(hidden), hidden[0].shape)

# common pooling strategies for a sentence vector:
# 1. [CLS] token of the last layer
cls = hidden[-1][:, 0, :]
# 2. mean-pool over tokens (often better than [CLS])
mask = inputs["attention_mask"].unsqueeze(-1).float()
mean = (hidden[-1] * mask).sum(1) / mask.sum(1)
# 3. concat last 4 layers (rich feature, used in early BERT papers)
cat = torch.cat([hidden[-i][:, 0, :] for i in range(1, 5)], dim=-1)
print(cls.shape, mean.shape, cat.shape)   # all (1, 768) except cat (1, 3072)

정적 vs 문맥적 비교

정적 임베딩은 BERT보다 100~300배 작고 빠르지만 단어 의미를 구분하지 못합니다. 문맥이 중요한 작업(감성, NER, QA)에는 문맥적 임베딩이 이깁니다. 순수 단어 수준 유사도, 큰 어휘의 클러스터링, 규모 있는 CPU 실행에는 정적 임베딩이 여전히 경쟁력 있습니다. 작업과 예산에 따라 고르세요.

nlp
import numpy as np
from gensim.models import KeyedVectors
from sentence_transformers import SentenceTransformer

# STATIC (Word2Vec/GloVe): same vector regardless of context
w2v = KeyedVectors.load_word2vec_format("glove.6B.100d.w2v.txt")
v1 = w2v["bank"]
v2 = w2v["bank"]
print("static cosine (always 1.0):", np.dot(v1, v2) / (np.linalg.norm(v1)*np.linalg.norm(v2)))

# CONTEXTUAL (BERT): vector depends on surrounding text
bert = SentenceTransformer("all-MiniLM-L6-v2")
from sklearn.metrics.pairwise import cosine_similarity
e_river = bert.encode("sat by the river bank")
e_money = bert.encode("deposited at the bank")
print("contextual cosine of two sentences:", cosine_similarity([e_river], [e_money])[0, 0].round(3))

# trade-offs:
#   static:   small, fast, fixed vocabulary, OOV-friendly only with FastText
#   contextual: large, slower, handles polysemy, needs GPU for speed
11

텍스트 분류

텍스트를 위한 sklearn Pipeline

이 TfidfVectorizer + LogisticRegression 파이프라인이 텍스트 분류의 정석 기저선입니다. 빠르고 해석 가능하며 딥러닝 없이는 이기기 어렵습니다. Pipeline이 전처리 + 모델을 감싸 예측 시점에 같은 변환이 적용됩니다. class_weight='balanced'가 불균형 클래스에 도움이 됩니다. 정확도만이 아니라 클래스별 정밀도/재현율을 항상 보고하세요.

nlp
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report

# X: list of strings, y: labels
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
                                                    stratify=y, random_state=42)

clf = Pipeline([
    ("tfidf", TfidfVectorizer(ngram_range=(1, 2), min_df=2,
                              sublinear_tf=True, stop_words="english")),
    ("clf", LogisticRegression(max_iter=1000, class_weight="balanced")),
])

clf.fit(X_train, y_train)
print(classification_report(y_test, clf.predict(X_test)))

# predict on new text
print(clf.predict(["this is a great movie"]))   # ['positive']

텍스트를 위한 Naive Bayes

Naive Bayes가 가장 단순한 텍스트 분류기입니다. 빠르고 작은 데이터셋에서 동작하며 'naive'한 단어 독립 가정은 위반되지만 실무에서 여전히 잘 동작합니다. MultinomialNB는 카운트(또는 TF-IDF)를, BernoulliNB는 이진 존재를 받습니다. ComplementNB는 불균형 클래스를 위해 특별히 설계되어 텍스트에서 Multinomial을 이길 때가 많습니다.

nlp
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline

clf = Pipeline([
    ("vec", CountVectorizer()),
    ("clf", MultinomialNB(alpha=1.0)),    # alpha = Laplace smoothing
])
clf.fit(X_train, y_train)

# MultinomialNB assumes word counts -> use CountVectorizer (not TF-IDF)
# alpha=1 (default) adds one to every count -> avoids zero probabilities
# lower alpha (0.1) for less smoothing when you have lots of data

# variants:
#   MultinomialNB - counts/TF-IDF (most common for text)
#   BernoulliNB   - binary features (word present/absent)
#   ComplementNB  - better on imbalanced text classes

텍스트를 위한 Linear SVM

LinearSVC는 얕은 텍스트 분류기 중 자주 최선입니다. 빠르고 희소 친화적이며 TF-IDF 피처에서 정확도가 높습니다. 단점은 네이티브 predict_proba가 없다는 것입니다. 확률 점수가 필요하면(예: 임계값 튜닝) CalibratedClassifierCV로 감싸세요. C는 그리드 탐색으로 튜닝하며 0.1~10 근처가 보통 동작합니다.

nlp
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import LinearSVC
from sklearn.pipeline import Pipeline
from sklearn.calibration import CalibratedClassifierCV

# LinearSVC is much faster than SVC(kernel='linear') on sparse text
clf = Pipeline([
    ("tfidf", TfidfVectorizer(sublinear_tf=True)),
    ("clf", LinearSVC(C=1.0)),     # C = inverse regularization
])

# LinearSVC has no predict_proba by default; wrap if you need probabilities
calibrated = CalibratedClassifierCV(LinearSVC(), cv=3)
clf_prob = Pipeline([("tfidf", TfidfVectorizer()),
                     ("clf", calibrated)])

# tune C: smaller C = more regularization (helps with noisy text)
# LinearSVC is often the strongest shallow text classifier

분류를 위한 BERT 파인튜닝

사전학습 BERT/DistilBERT를 분류 헤드로 파인튜닝하면 수천 개 레이블 예시가 있을 때 최첨단 결과를 냅니다. DistilBERT는 BERT보다 약 40% 작고 빠르며 품질의 약 95%를 유지해 훌륭한 기본값입니다. 낮은 학습률(2e-5)과 2~4 에포크를 쓰세요. 더 많은 에포크는 과적합입니다. Trainer가 배칭, 혼합 정밀도, 로깅을 처리합니다.

nlp
from transformers import (AutoTokenizer, AutoModelForSequenceClassification,
                          TrainingArguments, Trainer)
import torch

model_name = "distilbert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(
    model_name, num_labels=3
)

# tokenize the dataset
def tokenize(batch):
    return tokenizer(batch["text"], padding="max_length",
                     truncation=True, max_length=128)

train_ds = dataset["train"].map(tokenize, batched=True)
train_ds.set_format("torch", columns=["input_ids", "attention_mask", "label"])

args = TrainingArguments(
    output_dir="./clf",
    num_train_epochs=3,
    per_device_train_batch_size=16,
    learning_rate=2e-5,
    eval_strategy="epoch",
)
trainer = Trainer(model=model, args=args,
                  train_dataset=train_ds, eval_dataset=dataset["test"])
trainer.train()

멀티 레이블 분류

멀티 레이블은 멀티 클래스와 다릅니다. 각 인스턴스가 레이블을 0개, 1개, 또는 여러 개 가질 수 있습니다. OneVsRestClassifier는 레이블마다 이진 분류기를 학습합니다. micro/macro F1을 쓰세요(정확도 아님). 100개 레이블 공간의 정확도는 오도적입니다. BERT에서는 소프트맥스를 레이블별 시그모이드로 바꾸고 BCEWithLogitsLoss를 쓰세요.

nlp
# multi-label: each document can have MULTIPLE tags
# (e.g. a news article is both 'politics' AND 'economy')

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.multiclass import OneVsRestClassifier
from sklearn.pipeline import Pipeline
from sklearn.metrics import f1_score

# y is a (n_samples, n_labels) binary matrix, NOT a 1-d array
clf = Pipeline([
    ("tfidf", TfidfVectorizer()),
    ("clf", OneVsRestClassifier(LogisticRegression(max_iter=1000))),
])
clf.fit(X_train, Y_train)         # Y_train: 2D binary array

# predict returns a 2D matrix
pred = clf.predict(X_test)
print(f1_score(Y_test, pred, average="micro"))

# alternatives:
#   MultiLabelBinarizer to convert list-of-labels -> 2D matrix
#   BinaryRelevance / ClassifierChains from scikit-multilearn
#   BERT with sigmoid + BCEWithLogitsLoss (one head per label)

평가 지표

불균형 데이터에서 정확도는 거짓말을 합니다. 99%가 스팸이 아닌 데이터에서 항상 '스팸 아님'을 예측하면 99%를 받습니다. macro F1은 모든 클래스를 동등하게 대우하고(불균형에 최선), micro F1은 다수 클래스가 지배하고, weighted F1은 중간입니다. 배포 전 약한 클래스를 찾으려 클래스별 정밀도/재현율을 항상 보세요.

nlp
from sklearn.metrics import (classification_report, confusion_matrix,
                              f1_score, precision_recall_fscore_support)

y_true = [0, 0, 1, 1, 2, 2]
y_pred = [0, 1, 1, 1, 2, 0]

# per-class precision / recall / F1
print(classification_report(y_true, y_pred, digits=3))

# F1 averaging strategies (multi-class):
#   macro  : average F1 over classes (treats all classes equally)
#   micro  : aggregate then compute (dominated by majority class)
#   weighted: average weighted by class support
print("macro F1:", f1_score(y_true, y_pred, average="macro"))
print("micro F1:", f1_score(y_true, y_pred, average="micro"))

# confusion matrix
print(confusion_matrix(y_true, y_pred))

# ROC-AUC needs probabilities; for multi-class use roc_auc_score with multi_class='ovr'
12

감성 분석

VADER (어휘 기반)

VADER는 규칙 기반이며 학습 데이터가 필요 없습니다. 소셜 미디어에 완벽합니다(이모티콘, 대문자, 'kinda', '!' 처리). compound가 권장되는 일차원 점수입니다. 풍자와 문맥 의존 감성에 약합니다. VADER는 영어 전용이므로 다른 언어는 트랜스포머 모델을 쓰거나 먼저 번역하세요.

nlp
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
nltk.download('vader_lexicon')

sia = SentimentIntensityAnalyzer()

for text in ["I love this!", "This is terrible :(",
             "It's okay, not great."]:
    scores = sia.polarity_scores(text)
    print(f"{text:25} {scores}")
# {'neg': 0.0, 'neu': 0.308, 'pos': 0.692, 'compound': 0.636}
# {'neg': 0.679, 'neu': 0.321, 'pos': 0.0, 'compound': -0.476}
# {'neg': 0.323, 'neu': 0.677, 'pos': 0.0, 'compound': -0.226}

# compound: normalized score in [-1, 1]
# common thresholds: >0.05 positive, <-0.05 negative, else neutral

TextBlob 감성

TextBlob은 Pattern 기반 어휘를 감싸 한 번의 호출로 극성과 주관성을 모두 줍니다. 주관성은 사실적 텍스트와 의견 텍스트를 걸러내는 데 편리합니다. TextBlob은 소셜 미디어에서 VADER보다 약하지만(이모티콘 처리 없음) 더 단순합니다. 둘 다 기저선이며 레이블 데이터가 있으면 파인튜닝된 트랜스포머가 이깁니다.

nlp
from textblob import TextBlob   # pip install textblob

for text in ["I love NLP.", "This is the worst experience.",
             "The movie was okay."]:
    blob = TextBlob(text)
    print(f"{text:30} polarity={blob.sentiment.polarity:.2f} "
          f"subjectivity={blob.sentiment.subjectivity:.2f}")
# I love NLP.                    polarity=0.50 subjectivity=0.60
# This is the worst experience.  polarity=-0.60 subjectivity=0.75
# The movie was okay.            polarity=0.00 subjectivity=0.00

# polarity:     [-1, 1]  negative to positive
# subjectivity: [0, 1]   objective (fact) to subjective (opinion)

# also gives noun phrases, translation, etc.
print(blob.noun_phrases)

트랜스포머 기반 감성

Hub의 사전학습 감성 모델은 학습 데이터 0으로 프로덕션 품질 결과를 냅니다. zero-shot 파이프라인은 빠른 프로토타이핑의 마법입니다. 임의의 후보 레이블을 넘기면 NLI로 순위를 매깁니다. zero-shot은 파인튜닝 모델보다 덜 정확하지만 레이블을 모르거나 자주 바뀔 때 귀중합니다.

nlp
from transformers import pipeline

# zero-shot: pick any labels you want, no fine-tuning
clf = pipeline("sentiment-analysis",
               model="distilbert-base-uncased-finetuned-sst-2-english")
print(clf(["I love this product!", "Worst purchase ever."]))
# [{'label': 'POSITIVE', 'score': 0.9998}, {'label': 'POSITIVE'...}]

# zero-shot classification: works on ANY label set
zero = pipeline("zero-shot-classification",
                model="facebook/bart-large-mnli")
print(zero("The battery lasts only an hour.",
           candidate_labels=["positive", "negative", "neutral"]))
# {'labels': ['negative', 'neutral', 'positive'], 'scores': [0.95, ...]}

파인튜닝된 감성 모델

자기 레이블 데이터로 파인튜닝하면 어떤 기성 감성 모델보다 낫습니다. 레이블 정의가 다르기 때문입니다(5점 vs 3클래스 vs 관점 기반). 작은 학습률(2e-5), 2~4 에포크를 쓰고 과적합을 위해 검증 손실을 지켜 보세요. 'evaluate' 라이브러리가 표준 지표를 묶어 줍니다. 모델은 trainer.save_model()로 저장합니다.

nlp
from transformers import (AutoTokenizer, AutoModelForSequenceClassification,
                          Trainer, TrainingArguments)
import evaluate

model_name = "distilbert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=2)

def tokenize(batch):
    return tokenizer(batch["text"], truncation=True, padding="max_length")

train_ds = dataset["train"].map(tokenize, batched=True)
train_ds = train_ds.rename_column("label", "labels")
train_ds.set_format("torch")

accuracy = evaluate.load("accuracy")

def compute_metrics(eval_pred):
    logits, labels = eval_pred
    preds = logits.argmax(axis=-1)
    return accuracy.compute(predictions=preds, references=labels)

args = TrainingArguments("sentiment", num_train_epochs=3,
                         per_device_train_batch_size=16,
                         eval_strategy="epoch", learning_rate=2e-5)
trainer = Trainer(model=model, args=args, train_dataset=train_ds,
                  eval_dataset=dataset["test"], compute_metrics=compute_metrics)
trainer.train()

관점 기반 감성

관점 기반 감성 분석(ABSA)은 리뷰를 관점별 의견으로 분해합니다. 제품 피드백에는 단일 문서 수준 점수보다 훨씬 유용합니다. 빠른 프로토타입에는 NLI zero-shot이 동작하고, 프로덕션에는 시퀀스 쌍 분류기(관점, 텍스트) -> 감성을 파인튜닝하거나 pyabsa 같은 전용 라이브러리를 쓰세요. 구조화된 프롬프트를 쓴 LLM도 경쟁력 있습니다.

nlp
# Aspect-based sentiment: sentiment TOWARD a specific aspect
# "The food was great but the service was slow."
#   food -> positive, service -> negative

from transformers import pipeline

# approach 1: zero-shot on each aspect
zero = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
text = "The food was great but the service was slow."
for aspect in ["food", "service"]:
    result = zero(text, candidate_labels=["positive", "negative", "neutral"])
    print(f"{aspect}: {result['labels'][0]} ({result['scores'][0]:.2f})")

# approach 2: pyabsa library (specialized for ABSA)
# pip install pyabsa
# from pyabsa import AspectTermExtraction as ATE
# analyzer = ATE.AspectExtractor('english', auto_device=True)
# print(analyzer.predict(text))

# approach 3: prompt an LLM with aspect + text -> label
13

토픽 모델링

gensim으로 LDA

LDA(Latent Dirichlet Allocation)는 각 문서를 토픽의 혼합으로, 각 토픽을 단어 위의 분포로 모델링합니다. gensim의 LdaModel이 표준 구현입니다. 전처리가 중요합니다. 학습 전에 불용어 제거, 표제어 추출, 극단값(매우 흔한/희귀 단어) 필터링을 하세요. num_topics가 핵심 하이퍼파라미터이며 선택에는 coherence를 쓰세요.

nlp
from gensim.corpora import Dictionary
from gensim.models import LdaModel

docs = [["cat", "dog", "pet"],
        ["dog", "bark", "pet"],
        ["python", "code", "program"],
        ["code", "bug", "python"]]

dictionary = Dictionary(docs)
corpus = [dictionary.doc2bow(d) for d in docs]   # bag-of-words

lda = LdaModel(
    corpus=corpus,
    id2word=dictionary,
    num_topics=2,
    passes=10,             # iterations over the corpus
    random_state=42,
    alpha="auto",          # document-topic prior
    eta="auto",            # topic-word prior
)

# top words per topic
for topic_id, words in lda.print_topics(num_words=4):
    print(f"Topic {topic_id}: {words}")

sklearn으로 LDA

sklearn의 LDA는 CountVectorizer 파이프라인과 통합되지만 큰 코퍼스에서 gensim보다 느리고 메모리를 더 씁니다. 스트리밍에는 learning_method='online'을 쓰세요. components_가 토픽-단어 분포를, transform(X)가 문서-토픽 분포를 줍니다. LDA는 초기화에 민감하므로 재현성을 위해 random_state를 설정하세요.

nlp
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.decomposition import LatentDirichletAllocation

docs = ["cat dog pet", "dog bark pet", "python code program", "code bug python"]
vec = CountVectorizer(max_df=0.9, min_df=2, stop_words="english")
X = vec.fit_transform(docs)

lda = LatentDirichletAllocation(
    n_components=3,
    learning_method="batch",   # 'online' for large corpora
    max_iter=20,
    random_state=42,
)
lda.fit(X)

# top words per topic
words = vec.get_feature_names_out()
for i, topic in enumerate(lda.components_):
    top = [words[j] for j in topic.argsort()[:-6:-1]]
    print(f"Topic {i}: {top}")

NMF (비음수 행렬 분해)

NMF는 TF-IDF 행렬을 비음수 W(문서-토픽)와 H(토픽-단어)로 분해합니다. LDA보다 빠르고 LDA의 확률적 가정을 하지 않아 짧은 텍스트에서 더 일관된 토픽을 내는 경우가 많습니다. LDA는 카운트 데이터가 필요하지만(TF-IDF는 생성 가정을 깬다) NMF는 TF-IDF로 동작하며 오히려 이득을 봅니다.

nlp
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import NMF

docs = ["machine learning models", "deep learning networks",
        "natural language processing", "cooking recipes food"]

vec = TfidfVectorizer(max_features=1000, stop_words="english")
X = vec.fit_transform(docs)

nmf = NMF(n_components=2, random_state=42, l1_ratio=0.5, alpha_W=0.1)
W = nmf.fit_transform(X)   # document-topic
H = nmf.components_         # topic-word

words = vec.get_feature_names_out()
for i, topic in enumerate(H):
    print(f"Topic {i}: {[words[j] for j in topic.argsort()[:-6:-1]]}")
# NMF works with TF-IDF (LDA needs counts); topics are often cleaner
# on short documents

Coherence와 K 선택

Coherence는 각 토픽의 상위 단어가 얼마나 의미상 관련되는지 측정하며 높을수록 좋습니다. c_v가 가장 신뢰할 만한 지표입니다. coherence vs k 그래프에서 '엘보'나 정점을 찾으세요. 정답 K는 없으므로 토픽을 수동으로도 검사하세요. 두 토픽이 거의 중복이면 K를 줄이고, 일반어('get', 'make')만 있는 토픽은 K가 너무 큰 신호입니다.

nlp
from gensim.models import CoherenceModel, LdaModel
from gensim.corpora import Dictionary

# compare LDA models with different numbers of topics
dictionary = Dictionary(docs)
corpus = [dictionary.doc2bow(d) for d in docs]

scores = []
for k in range(2, 11):
    lda = LdaModel(corpus=corpus, id2word=dictionary,
                   num_topics=k, passes=10, random_state=42)
    cm = CoherenceModel(model=lda, texts=docs,
                        dictionary=dictionary, coherence="c_v")
    score = cm.get_coherence()
    scores.append((k, score))
    print(f"k={k}: coherence={score:.3f}")

# pick the k with highest coherence (or where scores plateau)
# c_v in [0,1]; >0.5 is usually interpretable

pyLDAvis 시각화

pyLDAvis는 사실상 표준 토픽 모델 시각화입니다. 각 버블이 토픽이며 크기는 중요도, 위치는 다른 토픽과의 거리입니다(겹침 = 유사한 토픽). 오른쪽 패널은 람다 슬라이더와 함께 토픽별 가장 관련 높은 단어를 보여 주며, 람다가 낮을수록 단순 빈도보다 독특한 단어가 드러납니다. 이해관계자에게 토픽을 설명하기 좋습니다.

nlp
# pip install pyldavis
import pyLDAvis
import pyLDAvis.gensim_models as gensimvis

# (assuming lda, corpus, dictionary from above)
vis = gensimvis.prepare(lda, corpus, dictionary)

# save as standalone HTML
pyLDAvis.save_html(vis, "lda_vis.html")
# open in a browser: bubbles = topics, sized by prevalence,
# positioned by inter-topic distance (PCoA on topic-word distances)

#pyLDAvis.enable_notebook()   # inline in Jupyter
#vis

# lambda slider: 1 = pure relevance by frequency,
# 0.6 = lift (rare-but-distinctive words rise)

BERTopic (신경망 토픽 모델링)

BERTopic은 현대적 신경망 파이프라인입니다. 문장 임베딩(기본 = 트랜스포머) -> 차원 축소용 UMAP -> 클러스터링용 HDBSCAN -> 토픽 표현용 c-TF-IDF. num_topics가 필요 없고(HDBSCAN이 찾음) 짧은 텍스트를 LDA보다 훨씬 잘 다룹니다. LDA보다 느리지만 더 일관된 토픽을 내며 도메인에 맞게 임베딩 모델을 조정하세요.

nlp
# pip install bertopic
from bertopic import BERTopic
from sklearn.datasets import fetch_20newsgroups

docs = fetch_20newsgroups(subset="all")["data"][:1000]

# BERTopic: embeddings -> dimensionality reduction -> clustering
topic_model = BERTopic(
    language="english",
    calculate_probabilities=True,
    verbose=True,
)
topics, probs = topic_model.fit_transform(docs)

print(topic_model.get_topic_info().head())
print(topic_model.get_topic(0))   # top words for topic 0

# visualize
# topic_model.visualize_topics()
# topic_model.visualize_barchart()

# BERTopic finds the number of topics automatically (via HDBSCAN clusters)
14

텍스트 생성

N-gram 언어 모델

n-gram 언어 모델은 각 단어가 이전 n-1 단어 뒤에 얼마나 자주 오는지 세고, 그 분포에서 샘플링해 다음 단어를 예측합니다. 바이그램은 단순하지만 문맥이 짧고, 트라이그램/4-gram은 일관성을 개선하지만 데이터가 더 필요합니다. 스무딩(add-k, Kneser-Ney)이 보지 못한 문맥을 처리합니다. 자동완성과 단순 텍스트 생성의 유용한 기저선입니다.

nlp
import nltk
from nltk.util import ngrams
from collections import defaultdict, Counter

text = "the cat sat on the mat the dog sat on the log".split()
n = 2   # bigram model

# count bigram occurrences
model = defaultdict(Counter)
for w1, w2 in ngrams(text, n):
    model[w1][w2] += 1

# convert counts to probabilities
for w1 in model:
    total = sum(model[w1].values())
    for w2 in model[w1]:
        model[w1][w2] /= total

# generate next word given a context
import random
context = ("the",)
candidates = model[context[0]]
print(candidates)   # Counter({'cat': 0.25, 'dog': 0.25, 'mat': 0.25, 'log': 0.25})
print(random.choices(list(candidates), weights=candidates.values())[0])

마르코프 체인 텍스트 생성기

마르코프 체인이 가장 단순한 생성 모델입니다. 상태 = 마지막 N개 단어, 다음 단어는 관찰된 전이에서 샘플링. 지역 스타일(흔한 구문)은 잡지만 장거리 일관성이 없어 출력이 몇 단어 뒤 표류합니다. 차수를 올리면 일관성이 개선되지만 데이터가 기하급수적으로 더 필요합니다. 스타일화된 패러디에는 재미있지만 프로덕션 생성용은 아닙니다.

nlp
import random
from collections import defaultdict

def build_chain(text, order=2):
    chain = defaultdict(list)
    words = text.split()
    for i in range(len(words) - order):
        state = tuple(words[i:i + order])
        chain[state].append(words[i + order])
    return chain

def generate(chain, length=30, seed=None):
    start = seed or random.choice(list(chain))
    out = list(start)
    state = start
    for _ in range(length):
        nxt = chain.get(state)
        if not nxt:
            break
        word = random.choice(nxt)
        out.append(word)
        state = tuple(out[-len(state):])
    return " ".join(out)

text = "the cat sat on the mat the cat ran the dog barked"
chain = build_chain(text, order=2)
print(generate(chain, length=20))

GPT-2 텍스트 생성

GPT-2(와 후속 모델)는 다음 토큰을 자기회귀적으로 예측해 일관된 문단을 생성합니다. generate() 메서드가 디코딩 전략을 통일합니다. do_sample=True는 확률적 생성(창의적), False는 greedy/beam(결정적)입니다. 현대적 생성에는 기본 GPT-2보다 명령 튜닝된 모델(GPT-NeoX, Llama, Mistral)을 선호하세요.

nlp
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch

model_name = "gpt2"   # 'gpt2-medium', 'gpt2-large' for bigger
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)

prompt = "In a world where machines could think,"
input_ids = tokenizer.encode(prompt, return_tensors="pt")

# greedy / beam / sampling all live in generate()
output = model.generate(
    input_ids,
    max_new_tokens=80,
    do_sample=True,
    top_k=50,
    top_p=0.95,
    temperature=0.9,
    repetition_penalty=1.2,
    pad_token_id=tokenizer.eos_token_id,
)
print(tokenizer.decode(output[0], skip_special_tokens=True))

디코딩 전략 (temperature / top-k / top-p)

디코딩 전략이 창의성과 일관성을 제어합니다. greedy/beam은 안전하지만 지루합니다. temperature는 소프트맥스 전 로짓을 스케일합니다(<1 날카롭게, >1 평평하게). top-k는 가장 가능성 높은 k개 토큰으로 제한하고, top-p(nucleus)는 확률 p를 커버하는 최소 집합으로 제한해 더 적응적입니다. 흔한 레시피: temperature=0.7, top_p=0.9, repetition_penalty=1.1.

nlp
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch

tokenizer = AutoTokenizer.from_pretrained("gpt2")
model = AutoModelForCausalLM.from_pretrained("gpt2")
input_ids = tokenizer.encode("Once upon a time", return_tensors="pt")

# 1. GREEDY: always pick the argmax token. Deterministic, repetitive.
# 2. BEAM SEARCH: keep top-k sequences; deterministic, more coherent
#    but still bland.
beam = model.generate(input_ids, num_beams=5, max_new_tokens=50)

# 3. TEMPERATURE: sharpen (<1) or flatten (>1) the distribution.
#    temp=0.1 = nearly greedy; temp=1.5 = chaotic
sampler = model.generate(input_ids, do_sample=True, temperature=0.7,
                         top_k=0, max_new_tokens=50)

# 4. TOP-K: sample only from the k most likely tokens (k=50 typical)
topk = model.generate(input_ids, do_sample=True, top_k=50, max_new_tokens=50)

# 5. TOP-P (nucleus): sample from the smallest set whose cumulative
#    probability >= p (p=0.9 typical). Adapts to the distribution shape.
topp = model.generate(input_ids, do_sample=True, top_p=0.9, max_new_tokens=50)

프롬프트 엔지니어링

베이스 모델은 신중한 프롬프트가 필요합니다. 단순 작업은 zero-shot, 패턴 학습은 few-shot(3~5개 예시), 명시적 형식 지시도 필요합니다. 명령 튜닝 모델(InstructGPT, Llama-2-Chat, Mistral-Instruct)은 자연어 지시를 훨씬 잘 따르고 예시가 더 적게 필요합니다. Chain-of-thought('단계별로 생각하세요')는 수학과 논리 추론을 끌어올립니다. 프롬프트를 체계적으로 반복 개선하세요.

nlp
from transformers import pipeline

generator = pipeline("text-generation", model="gpt2")

# zero-shot: just ask
zero = generator("Translate English to French: cheese ->", max_new_tokens=5)

# few-shot: show examples in the prompt, then ask for the next
prompt = """Translate English to French:
cheese -> fromage
bread -> pain
water ->"""
few = generator(prompt, max_new_tokens=3)

# instruction prompt (works best with instruction-tuned models)
instruction = """Summarize the following text in one sentence:
Text: The cat sat on the mat. It was a lazy afternoon...
Summary:"""
summary = generator(instruction, max_new_tokens=30)

# tips:
#   - be specific about format ("Output JSON", "Answer in one word")
#   - provide examples for non-obvious tasks
#   - chain-of-thought: "Let's think step by step."
15

기계 번역

googletrans로 번역

googletrans는 구글 무료 웹 번역 엔드포인트를 감쌉니다. 프로토타이핑은 빠르지만 비공식이고 요율 제한이 있습니다. 프로덕션에는 공식 API(Google Cloud Translation, DeepL, Azure Translator)나 Hugging Face로 MarianMT/NLLB 셀프호스팅을 쓰세요. DeepL이 유럽 언어에서 가장 유창한 번역을 내는 경향이 있습니다.

nlp
# pip install googletrans==4.0.0-rc1
from googletrans import Translator

translator = Translator()

# single sentence
result = translator.translate("Hello, world!", src="en", dest="fr")
print(result.text)        # Bonjour le monde !
print(result.pronunciation)

# batch
results = translator.translate(
    ["Good morning", "Thank you"], src="en", dest="es")
for r in results:
    print(r.text)         # Buenos días / Gracias

# auto-detect source language
detected = translator.translate("Guten Tag")
print(detected.src)       # 'de'

# caveat: googletrans uses the free web API and may rate-limit / break.
# For production, use official Google / DeepL / Azure APIs.

MarianMT (Hugging Face)

MarianMT(Helsinki-NLP opus 모델)는 약 100개 언어 쌍의 무료, 오프라인, 준수 품질 번역을 줍니다. 각 쌍이 별도 모델이므로 필요한 것을 정확히 고르세요. 다국어 번역에는 Meta의 NLLB-200이 단일 모델로 200개 언어를 커버합니다. 품질은 상용 API(Google/DeepL)에 뒤지지만 많은 사용 사례에 충분하고 단일 GPU에서 실행됩니다.

nlp
from transformers import MarianTokenizer, MarianMTModel

# many language pairs available: 'Helsinki-NLP/opus-mt-{src}-{tgt}'
model_name = "Helsinki-NLP/opus-mt-en-fr"
tokenizer = MarianTokenizer.from_pretrained(model_name)
model = MarianMTModel.from_pretrained(model_name)

texts = ["Hello, how are you?", "I love natural language processing."]

batch = tokenizer(texts, return_tensors="pt", padding=True, truncation=True)
generated = model.generate(**batch, max_length=128, num_beams=4)
print(tokenizer.batch_decode(generated, skip_special_tokens=True))
# ['Bonjour, comment allez-vous ?', "J'aime le traitement du langage naturel."]

# Helsinki-NLP shipped hundreds of language pairs; for many-to-many use
# 'facebook/nllb-200-distilled-600M' (200 languages, one model)

BLEU 점수

BLEU는 시스템 출력과 참조 번역의 n-gram 겹침을 비교하며 짧은 출력에 간결성 벌점을 둡니다. 점수는 0~100이며 30+면 합리적, 60+면 고품질입니다. BLEU는 저렴하고 표준이지만 불완전합니다. 동의어와 재배열을 놓칩니다. 항상 여러 참조로 평가하고 사람과의 상관을 위해 chrF나 COMET으로 보완하세요.

nlp
from sacrebleu import corpus_bleu   # pip install sacrebleu

refs = [["The cat is on the mat."]]   # list of reference(s) per sentence
hyp = ["The cat is on the mat."]      # system output

bleu = corpus_bleu(hyp, refs)
print(bleu.score)    # 0-100 (0=worst, 100=perfect match)

# multiple references for one sentence
refs = [["The cat is on the mat.", "There is a cat on the mat."]]
hyp = ["A cat is on the mat."]
print(corpus_bleu(hyp, refs).score)

# BLEU = geometric mean of modified n-gram precision * brevity penalty
#   - precision: how many n-grams in hyp appear in references
#   - brevity penalty: penalizes too-short outputs

# caveats: BLEU ignores semantics, struggles on short sentences,
# correlates only moderately with human judgment

번역을 위한 토큰화

번역 모델은 미지 토큰 없이 모든 유니코드(€, —, 이모지 포함)를 다루는 SentencePiece나 BPE 토크나이저를 씁니다. SentencePiece에서 ▁ 마커가 단어 경계를 나타내며 표면 텍스트 재구성 시 제거하세요. MarianMT/NLLB 모델에 원시 공백 토큰화 텍스트를 절대 넣지 말고, 항상 해당 토크나이저를 거쳐 일치하는 입력 ID를 받으세요.

nlp
from transformers import AutoTokenizer

# translation models often use SentencePiece (BPE/unigram) tokenizers
tok = AutoTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-de")

text = "Don't go there — it's 5€!"
enc = tok(text)
print(tok.convert_ids_to_tokens(enc["input_ids"]))
# ['▁Don', "'", 't', '▁go', '▁there', '▁—', '▁it', "'", 's', '▁5', '€', '!', '</s>']

# the leading '▁' (U+2581) marks a word start in SentencePiece.
# Strip it when reconstructing words:
pieces = [p.replace("▁", " ") for p in tok.convert_ids_to_tokens(enc["input_ids"])]
print("".join(pieces).strip())

# always use the model's own tokenizer, never a generic one —
# vocabulary and subword rules differ across translation models

역번역 (데이터 증강)

역번역은 합성 병렬 데이터를 만듭니다. 단일언어 목표 텍스트를 소스로 번역한 뒤 원래 목표 텍스트와 짝짓습니다. 병렬 코퍼스가 부족할 때 대규모 NMT 시스템(Google, Facebook)을 학습시키는 방법입니다. 역번역 텍스트는 진짜 병렬 데이터보다 노이즈가 있지만 다양성을 더하고 견고성을 높입니다. 특히 저자원 언어 쌍에서.

nlp
from transformers import MarianMTModel, MarianTokenizer

# augment monolingual source data with back-translated paraphrases
src_model_name = "Helsinki-NLP/opus-mt-en-de"   # EN -> DE
bt_model_name = "Helsinki-NLP/opus-mt-de-en"     # DE -> EN (back)

mono_en = ["The weather is nice today.", "I am learning NLP."]

# forward: EN -> DE
fwd_tok = MarianTokenizer.from_pretrained(src_model_name)
fwd_model = MarianMTModel.from_pretrained(src_model_name)
de = fwd_model.generate(**fwd_tok(mono_en, return_tensors="pt", padding=True))

# back: DE -> EN (paraphrase of the original)
bt_tok = MarianTokenizer.from_pretrained(bt_model_name)
bt_model = MarianMTModel.from_pretrained(bt_model_name)
en_bt = bt_model.generate(**bt_tok(
    bt_tok.batch_decode(de, skip_special_tokens=True),
    return_tensors="pt", padding=True))

paraphrases = bt_tok.batch_decode(en_bt, skip_special_tokens=True)
print(paraphrases)   # ~same meaning, different wording
16

Sequence-to-Sequence

인코더-디코더 기본

Seq2Seq는 가변 길이 입력 시퀀스를 가변 길이 출력에 매핑합니다. 번역, 요약, 다른 많은 작업의 기초입니다. RNN의 고전적 인코더-디코더는 전체 입력을 고정 컨텍스트 벡터로 압축하며, 이것이 긴 시퀀스의 병목이 됩니다. 어텐션(다음 섹션)이 정확히 이 문제를 고치려 고안됐습니다.

nlp
# Seq2Seq: an encoder maps the input sequence to a context vector,
# a decoder generates the output sequence from that context.
#
#   input -> [Encoder] -> context -> [Decoder] -> output
#
# Classic architecture (Sutskever et al. 2014):
#   - Encoder: RNN/LSTM/GRU processes input tokens, final hidden state
#     becomes the context vector.
#   - Decoder: another RNN initialized with the context, generates
#     output tokens one at a time.
#
# Used for: translation, summarization, QA, parsing, code generation.

import torch
import torch.nn as nn

class Encoder(nn.Module):
    def __init__(self, vocab_size, emb_dim, hid_dim):
        super().__init__()
        self.emb = nn.Embedding(vocab_size, emb_dim)
        self.rnn = nn.LSTM(emb_dim, hid_dim)
    def forward(self, src):
        embedded = self.emb(src)
        outputs, (hidden, cell) = self.rnn(embedded)
        return hidden, cell   # context

RNN/LSTM Seq2Seq

디코더는 한 번에 한 토큰을 생성하며 자기 이전 출력을 다음 입력으로 넣습니다(자기회귀). 디코더의 은닉 상태는 인코더의 컨텍스트로 초기화합니다. greedy 디코딩(각 단계 argmax)은 단순하지만 루프에 빠질 수 있고, beam search는 상위 k개 가설을 유지합니다. 고정 컨텍스트 벡터는 긴 입력에 애를 먹으며 어텐션이 이를 해결합니다.

nlp
import torch
import torch.nn as nn

class Decoder(nn.Module):
    def __init__(self, vocab_size, emb_dim, hid_dim):
        super().__init__()
        self.emb = nn.Embedding(vocab_size, emb_dim)
        self.rnn = nn.LSTM(emb_dim, hid_dim)
        self.fc = nn.Linear(hid_dim, vocab_size)

    def forward(self, input_token, hidden, cell):
        # input_token: (1,) the previous output token
        emb = self.emb(input_token).unsqueeze(0)   # (1, 1, emb_dim)
        out, (hidden, cell) = self.rnn(emb, (hidden, cell))
        logits = self.fc(out.squeeze(0))            # (1, vocab_size)
        return logits, hidden, cell

# full generation loop (greedy decoding)
def generate(decoder, context_hidden, context_cell, sos_idx, eos_idx, max_len=20):
    hidden, cell = context_hidden, context_cell
    token = torch.tensor([sos_idx])
    output = []
    for _ in range(max_len):
        logits, hidden, cell = decoder(token, hidden, cell)
        token = logits.argmax(dim=-1)
        if token.item() == eos_idx:
            break
        output.append(token.item())
    return output

Teacher Forcing

teacher forcing은 모델의 (흔히 틀린) 예측 대신 참 이전 토큰을 먹여 학습을 극적으로 가속합니다. 순수 teacher forcing은 '노출 편향'을 낳습니다. 추론 시 모델은 학습 중 자기 오류를 본 적이 없기 때문입니다. scheduled sampling(teacher forcing과 자기 예측의 혼합)이 이를 완화하지만 복잡도를 더하며, 현대 트랜스포머는 병렬 teacher forcing 학습에 의존합니다.

nlp
import torch
import torch.nn as nn

# During training, feed the GROUND TRUTH previous token (not the model's
# prediction) as the next input. This is 'teacher forcing'.

def train_step(encoder, decoder, src, trg, criterion, teacher_ratio=0.5):
    # src: (src_len, batch), trg: (trg_len, batch)
    hidden, cell = encoder(src)
    batch_size = src.size(1)
    trg_len = trg.size(0)
    vocab_size = decoder.fc.out_features

    outputs = torch.zeros(trg_len, batch_size, vocab_size)

    input_token = trg[0, :]   # <sos> token
    for t in range(1, trg_len):
        logits, hidden, cell = decoder(input_token, hidden, cell)
        outputs[t] = logits
        # teacher forcing: use real target as next input
        teacher_force = torch.rand(1).item() < teacher_ratio
        input_token = trg[t, :] if teacher_force else logits.argmax(dim=-1)

    return criterion(outputs[1:].reshape(-1, vocab_size),
                     trg[1:].reshape(-1))

어텐션 메커니즘

어텐션은 디코더를 단일 고정 컨텍스트 벡터에서 해방합니다. 각 단계에서 모든 인코더 출력의 가중 평균을 계산해 지금 어떤 소스 단어가 중요한지 학습합니다. 긴 시퀀스 병목을 고치고 품질을 극적으로 높입니다. Bahdanau(덧셈)와 Luong(곱셈)이 두 고전 변형이며 둘 다 트랜스포머 셀프 어텐션의 선구자입니다.

nlp
import torch
import torch.nn as nn
import torch.nn.functional as F

# Bahdanau-style additive attention:
# the decoder looks at ALL encoder outputs (not just the final state)
# and learns which to focus on at each step.

class Attention(nn.Module):
    def __init__(self, hid_dim):
        super().__init__()
        self.attn = nn.Linear(hid_dim * 2, hid_dim)
        self.v = nn.Linear(hid_dim, 1, bias=False)

    def forward(self, hidden, encoder_outputs):
        # hidden: (1, batch, hid), encoder_outputs: (src_len, batch, hid)
        src_len = encoder_outputs.size(0)
        hidden_exp = hidden.repeat(src_len, 1, 1)
        energy = torch.tanh(self.attn(
            torch.cat((hidden_exp, encoder_outputs), dim=2)))
        attention = self.v(energy).squeeze(2)        # (src_len, batch)
        return F.softmax(attention, dim=0)           # weights over src

# context = sum(attention_weights * encoder_outputs)
# then concat context with decoder input embedding

Beam Search

beam search는 k개 후보 시퀀스를 유지하고 가장 유망한 것을 확장해 탐색과 활용의 균형을 잡습니다. 너비 4~8이 전형입니다. beam search는 greedy보다 유창한 출력을 내지만 일반적인 번역을 선호할 수 있으며, length_penalty와 no_repeat_ngram_size가 이를 상쇄합니다. 개방형 생성에는 샘플링이 종종 beam search를 이기고, 번역/요약에는 보통 beam search가 이깁니다.

nlp
# Greedy decoding picks the single most likely token each step.
# Beam search keeps the top-k candidate SEQUENCES, expanding each.

from transformers import AutoTokenizer, AutoModelForSeq2SeqLM

model = AutoModelForSeq2SeqLM.from_pretrained("Helsinki-NLP/opus-mt-en-fr")
tokenizer = AutoTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-fr")

input_ids = tokenizer("Hello, how are you?", return_tensors="pt").input_ids

# beam search: explore k hypotheses in parallel
output = model.generate(
    input_ids,
    num_beams=5,            # beam width
    max_length=50,
    length_penalty=0.6,     # <1 prefers shorter, >1 prefers longer
    early_stopping=True,
)
print(tokenizer.decode(output[0], skip_special_tokens=True))

# trade-off: larger beam = better quality but slower (O(k * steps))
# and a tendency toward generic / shorter outputs (length penalty helps)
17

어텐션과 트랜스포머

셀프 어텐션 직관

셀프 어텐션은 트랜스포머의 핵심입니다. 각 토큰이 (자기 자신 포함) 모든 토큰에 주의를 기울여 쿼리-키 유사도 가중치로 그 값들을 집계합니다. 반복 없이 단일 연산으로 전역 문맥을 얻어 대규모 병렬화를 허용합니다. 1/sqrt(d_k) 스케일링이 소프트맥스 그래디언트를 안정시킵니다. 이 단일 메커니즘이 RNN과 합성곱을 대체합니다.

nlp
# Self-attention lets each token look at every other token in the
# sequence to build a context-aware representation.
#
# For token i:  context_i = sum_j  attention(i, j) * value_j
#
# attention(i, j) = softmax( q_i . k_j / sqrt(d) )
#   q_i = query of token i  (what am I looking for?)
#   k_j = key of token j    (what do I contain?)
#   v_j = value of token j  (what info do I pass on?)
#
# Each token is projected to Q, K, V by learned weight matrices.

import torch
import torch.nn.functional as F
import math

def self_attention(x, W_q, W_k, W_v):
    # x: (seq_len, d_model)
    Q, K, V = x @ W_q, x @ W_k, x @ W_v
    d_k = K.size(-1)
    scores = Q @ K.transpose(-2, -1) / math.sqrt(d_k)
    weights = F.softmax(scores, dim=-1)
    return weights @ V   # (seq_len, d_model)

멀티 헤드 어텐션

멀티 헤드 어텐션은 입력의 서로 다른 투영에 여러 어텐션 레이어를 병렬 실행한 뒤 연결합니다. 각 헤드가 서로 다른 관계(구문, 공지시, 의미...)를 학습합니다. 8~16개 헤더가 전형이며 더 많은 헤드는 용량을 더하지만 수확 체감이 옵니다. mask 파라미터가 인과적(디코더) 및 패딩 마스크가 적용되는 경로입니다.

nlp
import torch
import torch.nn as nn
import math
import torch.nn.functional as F

class MultiHeadAttention(nn.Module):
    def __init__(self, d_model, n_heads):
        super().__init__()
        assert d_model % n_heads == 0
        self.d_k = d_model // n_heads
        self.n_heads = n_heads
        self.q = nn.Linear(d_model, d_model)
        self.k = nn.Linear(d_model, d_model)
        self.v = nn.Linear(d_model, d_model)
        self.out = nn.Linear(d_model, d_model)

    def forward(self, x, mask=None):
        B, L, D = x.shape
        # project to (B, n_heads, L, d_k)
        Q = self.q(x).view(B, L, self.n_heads, self.d_k).transpose(1, 2)
        K = self.k(x).view(B, L, self.n_heads, self.d_k).transpose(1, 2)
        V = self.v(x).view(B, L, self.n_heads, self.d_k).transpose(1, 2)
        scores = (Q @ K.transpose(-2, -1)) / math.sqrt(self.d_k)
        if mask is not None:
            scores = scores.masked_fill(mask == 0, float("-inf"))
        attn = F.softmax(scores, dim=-1)
        ctx = attn @ V                          # (B, h, L, d_k)
        ctx = ctx.transpose(1, 2).contiguous().view(B, L, D)
        return self.out(ctx)

트랜스포머 아키텍처

트랜스포머 블록 = 멀티 헤드 어텐션 + 위치별 피드포워드이며 각각 잔차 연결과 LayerNorm으로 감쌉니다. 잔차가 그래디언트가 깊은 스택을 흐르게 하고, LayerNorm이 학습을 안정시킵니다. 피드포워드(보통 d_model의 4배 폭)에 대부분의 파라미터가 있습니다. 완전한 모델은 6~24개 블록을 쌓습니다. 메모리는 시퀀스 길이의 O(L^2)이며 긴 컨텍스트 과제의 원천입니다.

nlp
# The full Transformer block (Vaswani et al. 2017):
#
#   x -> MultiHeadAttention -> Add & LayerNorm -> FeedForward -> Add & LayerNorm
#   (Add = residual connection: out = x + Sublayer(x))
#
# Encoder: stacks N of these blocks (N=6 in base, 12 in BERT-base).
# Decoder: same but with masked self-attention + cross-attention
#          to the encoder output.
#
# Properties:
#   - no recurrence -> fully parallelizable, trains much faster than RNNs
#   - global receptive field from layer 1
#   - position-agnostic -> needs positional encoding
#   - quadratic memory in seq_len (O(L^2)) due to full attention

import torch.nn as nn

class TransformerBlock(nn.Module):
    def __init__(self, d_model=512, n_heads=8, d_ff=2048, dropout=0.1):
        super().__init__()
        self.attn = nn.MultiheadAttention(d_model, n_heads, dropout=dropout,
                                          batch_first=True)
        self.ff = nn.Sequential(
            nn.Linear(d_model, d_ff), nn.GELU(), nn.Linear(d_ff, d_model))
        self.norm1 = nn.LayerNorm(d_model)
        self.norm2 = nn.LayerNorm(d_model)
        self.drop = nn.Dropout(dropout)

    def forward(self, x, mask=None):
        a, _ = self.attn(x, x, x, attn_mask=mask, need_weights=False)
        x = self.norm1(x + self.drop(a))
        f = self.ff(x)
        x = self.norm2(x + self.drop(f))
        return x

위치 인코딩

어텐션이 입력을 집합으로 취급하므로 트랜스포머는 명시적 위치 신호가 필요합니다. 원조 논문은 고정 사인파를 썼습니다(학습 길이 넘어 외삽). BERT/GPT는 학습된 임베딩을 씁니다(더 단순하고 약간 낫지만 외삽 불가). 현대 LLM은 RoPE(rotary)나 ALiBi를 선호하며 학습에서 본 것보다 긴 컨텍스트로 일반화합니다. 긴 문서 작업에 결정적입니다.

nlp
import torch
import math
import torch.nn as nn

# Self-attention is permutation-invariant, so we ADD positional info
# to the embeddings so the model knows token order.

class SinusoidalPositionalEncoding(nn.Module):
    def __init__(self, d_model, max_len=5000):
        super().__init__()
        pe = torch.zeros(max_len, d_model)
        position = torch.arange(0, max_len).unsqueeze(1).float()
        div_term = torch.exp(
            torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
        pe[:, 0::2] = torch.sin(position * div_term)
        pe[:, 1::2] = torch.cos(position * div_term)
        self.register_buffer("pe", pe.unsqueeze(0))   # (1, max_len, d_model)

    def forward(self, x):
        # x: (batch, seq_len, d_model)
        return x + self.pe[:, :x.size(1)]

# alternatives:
#   - learned positional embeddings (BERT, GPT): nn.Embedding(max_len, d_model)
#   - relative positional encoding (T5, Transformer-XL)
#   - RoPE (Rotary Position Embedding, used in LLaMA) -> handles long context

BERT vs GPT vs T5

BERT(인코더)는 양방향으로 텍스트를 읽어 이해 작업에 최선입니다. GPT(디코더)는 좌→우로 읽어 생성에 최선입니다. T5/BART(인코더-디코더)는 번역과 요약 같은 시퀀스-투-시퀀스 작업에 최선입니다. 현대 decoder-only LLM(LLaMA, Mistral)은 명령 튜닝으로 이해 작업의 격차를 좁히지만, 데이터가 적은 단순 분류에서는 작은 BERT가 여전히 이깁니다.

nlp
# Three Transformer families, three pretraining objectives:
#
# BERT (encoder-only, bidirectional):
#   - Masked Language Modeling (predict [MASK] tokens)
#   - Great for: classification, NER, QA (extractive), embeddings
#   - example: bert-base-uncased, RoBERTa, DistilBERT, DeBERTa
#
# GPT (decoder-only, autoregressive):
#   - Causal Language Modeling (predict next token)
#   - Great for: generation, chat, few-shot, code
#   - example: gpt2, gpt-neo, LLaMA, Mistral, Qwen
#
# T5 (encoder-decoder, text-to-text):
#   - Span corruption (mask spans, predict them)
#   - One model for EVERY task by framing as text->text
#   - example: t5-base, flan-t5, BART (similar, denoising autoencoder)

from transformers import AutoModel
bert = AutoModel.from_pretrained("bert-base-uncased")   # encoder
print(bert.config.model_type)   # bert

# pick the family that matches your task:
#   classification/NER -> encoder (BERT)
#   generation         -> decoder (GPT)
#   translation/summarization -> encoder-decoder (T5/BART)
18

질의 응답 (QA)

BERT로 추출형 QA

추출형 QA는 질의 응답을 스팬 예측으로 바꿉니다. 모델이 컨텍스트에서 시작/끝 토큰 위치를 출력합니다. SQuAD로 파인튜닝된 DistilBERT가 빠르고 정확한 기본값입니다. 답이 문자 그대로 컨텍스트에 나타날 때 가장 잘 동작합니다. 추상적 답(바꿔 말하기, 종합)에는 T5 같은 seq2seq 모델이나 검색을 곁들인 LLM을 쓰세요.

nlp
from transformers import pipeline

# Extractive QA: pick a SPAN of the context as the answer.
qa = pipeline("question-answering",
              model="distilbert-base-cased-distilled-squad")

context = "Transformers were introduced in 2017. The model uses self-attention."
question = "When were transformers introduced?"

result = qa(question=question, context=context)
print(result)
# {'score': 0.97, 'start': 32, 'end': 36, 'answer': '2017'}

# start/end are character offsets into the context —
# you can highlight the answer in the original text:
print(context[:result['start']] + '[' + result['answer'] + ']' + context[result['end']:])

생성형 QA (LLM)

생성형 QA는 자유 형식의 답(스팬 아님)을 만들어 종합, 바꿔 말하기, '모르겠습니다'가 가능합니다. FLAN-T5는 QA 프롬프트를 잘 따르는 작고 무료인 명령 튜닝 모델입니다. 컨텍스트가 제공되지 않는 개방형 질문에는 내부 지식이 있는 매우 큰 LLM이나 최신 사실을 공급하는 검색 증강 생성(RAG)이 필요합니다.

nlp
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch

model_name = "google/flan-t5-base"   # instruction-tuned seq2seq
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSeq2SeqLM.from_pretrained(model_name)

prompt = """context: The Eiffel Tower is located in Paris and was built in 1889.
question: Where is the Eiffel Tower?
answer:"""

input_ids = tokenizer(prompt, return_tensors="pt").input_ids
out = model.generate(input_ids, max_new_tokens=20)
print(tokenizer.decode(out[0], skip_special_tokens=True))
# 'Paris'

# for open-ended QA without a fixed context, use a large LLM
# (Llama-2-Chat, Mistral-Instruct) and prompt with the question directly

검색 증강 생성 (RAG)

RAG는 LLM 답을 검색된 근거에 고정합니다. LLM이 본 적 없는 최신 또는 사설 데이터에 결정적입니다. 절차: 문서 임베딩, 코사인 유사도로 top-k 검색, 프롬프트에 넣기, 모델 생성. 프로덕션에서는 벡터 데이터베이스(FAISS, Chroma, Qdrant)를 쓰고 긴 문서는 청킹하세요. RAG는 환각을 줄이고 출처 인용을 가능하게 합니다.

nlp
# RAG: retrieve relevant documents, then let an LLM answer
# using those documents as context. Combines search + generation.

from sentence_transformers import SentenceTransformer, util

# 1. Build a vector index of your documents
docs = ["Paris is the capital of France.",
        "Python is a programming language.",
        "The Eiffel Tower was built in 1889."]
encoder = SentenceTransformer("all-MiniLM-L6-v2")
doc_emb = encoder.encode(docs, convert_to_tensor=True, normalize_embeddings=True)

# 2. Retrieve top-k for a query
query = encoder.encode("What is the capital of France?",
                       convert_to_tensor=True, normalize_embeddings=True)
hits = util.semantic_search(query, doc_emb, top_k=2)[0]
context = "\n".join(docs[h['corpus_id']] for h in hits)

# 3. Generate answer conditioned on retrieved context
prompt = f"Context:\n{context}\n\nQuestion: What is the capital of France?\nAnswer:"
# -> feed to an LLM; it reads the context and answers 'Paris'
print(prompt)

SQuAD 데이터셋

SQuAD는 THE 추출형 QA 벤치마크이며 모든 QA 모델이 SQuAD F1을 보고합니다. 답은 스팬이므로 모델이 시작/끝 위치를 출력합니다. SQuAD v2는 거절 능력을 시험하려 답 없는 질문을 추가했습니다. 현대 모델은 F1 >90(지표상 초인적)이지만 SQuAD는 단일 홉이고 영어입니다. 더 어려운 경우는 Natural Questions, HotpotQA(멀티 홉), TyDiQA(다국어)를 쓰세요.

nlp
# SQuAD (Stanford Question Answering Dataset):
#   - 100k+ questions on Wikipedia paragraphs
#   - each answer is a SPAN in the paragraph
#   - the standard benchmark for extractive QA
#
# Load with Hugging Face datasets:
from datasets import load_dataset
squad = load_dataset("squad")
print(squad)
# DatasetDict({ train: 87599 rows, validation: 10570 rows })

ex = squad["train"][0]
print(ex.keys())
# dict_keys(['id', 'title', 'context', 'question', 'answers'])
print(ex["question"])      # 'Which NFL team represented the AFC...'
print(ex["answers"]["text"])   # ['Denver Broncos']  (sometimes multiple)

# SQuAD v2 adds unanswerable questions (model must abstain)
squad_v2 = load_dataset("squad_v2")

QA 평가 (F1 / EM)

SQuAD 채점은 비교 전 양쪽 답을 정규화합니다(소문자화, 관사/문장부호/여분 공백 제거). EM은 이진이고, F1은 토큰 수준이라 바꿔 말하기에 더 관대합니다. 둘 다 의미를 무시합니다. 'canine' vs 'dog'는 0점입니다. 추상형 QA에는 의미 지표(BERTScore, BARTScore)나 사람 평가를 쓰세요. 답 없는 질문을 포함한 모든 질문의 평균으로 EM과 F1을 함께 보고하세요.

nlp
# Two standard metrics for extractive QA:
#   Exact Match (EM): 1 if prediction == gold answer exactly, else 0
#   F1: token-level F1 between prediction and gold (after normalization)

import re
from collections import Counter

def normalize(text):
    # SQuAD normalization: lowercase, remove articles/punct/extra space
    text = text.lower()
    text = re.sub(r"\b(a|an|the)\b", " ", text)
    text = " ".join(text.split())
    return re.sub(r"[^\w\s]", "", text)

def f1_score(pred, gold):
    p, g = normalize(pred).split(), normalize(gold).split()
    common = Counter(p) & Counter(g)
    n_common = sum(common.values())
    if n_common == 0:
        return 0.0
    precision = n_common / len(p)
    recall = n_common / len(g)
    return 2 * precision * recall / (precision + recall)

def exact_match(pred, gold):
    return float(normalize(pred) == normalize(gold))

print(f1_score("the cat", "a cat"))      # 1.0 (articles removed)
print(exact_match("Paris.", "paris"))    # 1.0 (case/punct normalized)
19

텍스트 요약

추출형 요약 (TextRank)

TextRank는 문장 유사도 그래프를 만들고 PageRank를 돌려 가장 중심적인(대표적인) 문장을 찾습니다. 추출형 방법은 빠르고 충실하며(환각 없음) 뉴스에 좋습니다. 약점: 바꿔 말하거나 문장 간 정보를 합칠 수 없습니다. 프로덕션 준비 구현에는 sumy, gensim의 summarize, pytextrank를 쓰세요.

nlp
# Extractive: pick the most important SENTENCES from the source
# (no new text generated). TextRank ranks sentences by graph centrality.

import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

def textrank_summary(text, n=3):
    sentences = text.split(". ")   # naive sentence split
    if len(sentences) <= n:
        return text
    # similarity graph: sentence vs sentence
    tfidf = TfidfVectorizer(stop_words="english").fit_transform(sentences)
    sim = cosine_similarity(tfidf)
    np.fill_diagonal(sim, 0)
    # PageRank-style power iteration
    scores = np.ones(len(sentences)) / len(sentences)
    for _ in range(50):
        scores = 0.85 * sim.dot(scores) / sim.sum(axis=0) + 0.15 / len(sentences)
    top = np.argsort(scores)[-n:]
    return ". ".join(sentences[i] for i in sorted(top))

text = "Sentence one. Sentence two is longer. Third sentence here. Fourth."
print(textrank_summary(text, n=2))

gensim Summarize

gensim 4는 summarize 모듈을 제거했으므로 추출형 요약에는 sumy 라이브러리를 쓰세요. sumy는 여러 알고리즘을 제공합니다(TextRank, LexRank, LSA, Luhn). 뉴스에서는 LexRank가 TextRank를 근소히 이깁니다. 모든 추출형 방법은 같은 한계를 공유합니다. 다시 말할 수 없습니다. 더 높은 품질의 요약은 BART나 T5 같은 추상형 모델로 전환하세요.

nlp
from gensim.summarization import summarize  # older gensim
# (removed in gensim 4.x; use 'sumy' or 'pytextrank' instead)

# modern alternative: sumy
# pip install sumy
from sumy.parsers.plaintext import PlaintextParser
from sumy.nlp.tokenizers import Tokenizer
from sumy.summarizers.text_rank import TextRankSummarizer

parser = PlaintextParser.from_string("Your long text here. Multiple "
    "sentences. The summarizer picks the most important ones.",
    Tokenizer("english"))
summarizer = TextRankSummarizer()
for sentence in summarizer(parser.document, sentences_count=2):
    print(sentence)

# sumy also offers: LuhnSummarizer, LsaSummarizer, LexRankSummarizer,
# EdmundsonSummarizer (heuristic-based)

추상형 요약 (BART / T5)

BART-large-CNN이 뉴스용 표준 사전학습 요약기입니다. CNN/DailyMail로 3문장 요약을 만들도록 학습됐습니다. 추상형 요약은 (바꿔 말하고 압축하므로) 추출형보다 읽기 좋지만 소스에 없는 사실을 환각할 수 있으니 자기 도메인에서 항상 검증하세요. Pegasus는 매우 짧은 요약에 튜닝됐고, T5는 멀티태스크이며 유연합니다.

nlp
from transformers import pipeline

# Abstractive: GENERATE a summary (may use words not in the source)
summarizer = pipeline("summarization",
                      model="facebook/bart-large-cnn")

article = """\
Scientists at CERN have announced the discovery of a new subatomic
particle. The finding, published in Nature, confirms a prediction made
decades ago and opens new avenues for research into dark matter. The
team analyzed data from the Large Hadron Collider over three years."""

summary = summarizer(article, max_length=50, min_length=20,
                     do_sample=False, truncation=True)
print(summary[0]["summary_text"])

# alternative models:
#   t5-base / flan-t5-base  (text-to-text, multitask)
#   google/pegasus-xsum     (very short, one-sentence summaries)

ROUGE 평가

ROUGE는 생성 요약과 참조 요약의 n-gram 겹침을 측정합니다. 재현율 지향입니다(참조를 커버했는가?). ROUGE-1과 ROUGE-2 F1이 대표 수치이며, ROUGE-L은 최장 공통 부분 수열로 순서를 반영합니다. BLEU처럼 ROUGE도 의미 등가('canine' vs 'dog')를 놓칩니다. 프로덕션 품질 검사에는 BERTScore나 사람 평가로 보완하세요.

nlp
# ROUGE (Recall-Oriented Understudy for Gisting Evaluation):
# standard metric for summarization. Compares n-gram overlap.

# pip install rouge-score
from rouge_score import rouge_scorer

scorer = rouge_scorer.RougeScorer(["rouge1", "rouge2", "rougeL"],
                                  use_stemmer=True)
reference = "The cat sat on the mat."
hypothesis = "A cat is sitting on a mat."
scores = scorer.score(reference, hypothesis)
print(scores)
# rouge1: unigram overlap, rouge2: bigram, rougeL: longest common subsequence
# each gives (precision, recall, fmeasure)

# tips:
#   - ROUGE-1/ROUGE-2 F1 are the most reported
#   - ROUGE-L captures sentence-level order via LCS
#   - use multiple references for a fairer comparison
#   - ROUGE correlates with human judgment but ignores semantics

긴 문서 요약

표준 BART/T5는 입력을 512~1024 토큰으로 제한합니다. 긴 문서에는 어텐션이 근선형으로 확장되는 긴 컨텍스트 모델(LongT5, Longformer-Encoder-Decoder, BigBird)을 쓰세요. 맵-리듀스 청킹(각 청크 요약 후 요약들의 요약)은 견고한 폴백이며 섹션별 제어를 줍니다. 계층적 요약은 보고서와 회의의 구조를 보존합니다.

nlp
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
import torch

# Problem: most summarizers have a 512/1024-token input limit.
# Long documents (papers, meetings) need special handling.

model_name = "google/long-t5-tglobal-base"   # handles long inputs
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSeq2SeqLM.from_pretrained(model_name)

# option 1: use a long-context model (LongT5, LED, BigBird)
inputs = tokenizer(long_text, return_tensors="pt", truncation=True,
                   max_length=4096)
out = model.generate(**inputs, max_length=256)

# option 2: chunk + summarize + combine (map-reduce)
def chunk_text(text, max_tokens=512):
    # split into overlapping windows, summarize each, then summarize
    # the concatenation of partial summaries
    pass

# option 3: hierarchical attention (summarize sections, then summarize
# section summaries)
20

Hugging Face Transformers

Pipeline API

pipeline()이 가장 쉬운 진입점입니다. 작업을 고르고 모델을 받아 한 줄로 추론합니다. 토큰화, 모델 디스패치, 후처리를 처리합니다. 'model'을 임의 Hub 이름으로 재정의하면 아키텍처를 교체할 수 있습니다. 프로토타이핑에 좋지만 프로덕션에서는 속도를 위해 배칭, 디바이스 배치, 토큰화의 명시적 제어가 필요할 것입니다.

nlp
from transformers import pipeline

# one-line inference for common tasks (downloads a default model)
clf = pipeline("sentiment-analysis")
print(clf("I love transformers!"))

qa = pipeline("question-answering")
print(qa(question="Who built BERT?", context="BERT was built by Google."))

ner = pipeline("ner", aggregation_strategy="simple")
print(ner("Barack Obama was born in Hawaii."))

summarizer = pipeline("summarization")
print(summarizer("Long text...", max_length=50))

generator = pipeline("text-generation", model="gpt2")
print(generator("Once upon a time", max_new_tokens=30))

# tasks available: sentiment-analysis, ner, question-answering,
# summarization, translation, text-generation, zero-shot-classification,
# fill-mask, feature-extraction, text2text-generation, image-classification...

AutoModel과 AutoTokenizer

AutoModel은 기저 인코더를 로드하고(은닉 상태 출력) 작업별 Auto 클래스가 올바른 예측 헤드(분류, NER, QA, 생성)를 더합니다. AutoTokenizer가 짝이 되는 토크나이저를 고릅니다. 파인튜닝이나 커스텀 추론 파이프라인에 사용하세요. 각 'AutoModelFor*'에는 올바른 손실 함수가 내장되어 labels를 forward()에 넘기면 손실을 받습니다.

nlp
from transformers import AutoTokenizer, AutoModel, AutoModelForSequenceClassification
import torch

model_name = "bert-base-uncased"

# Auto* classes pick the right implementation from the model's config
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModel.from_pretrained(model_name)   # base encoder
clf_model = AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=2)

inputs = tokenizer(["Hello", "World"], padding=True, return_tensors="pt")
with torch.no_grad():
    embeddings = model(**inputs).last_hidden_state   # (batch, seq, 768)

# task-specific Auto classes:
#   AutoModelForTokenClassification  (NER)
#   AutoModelForQuestionAnswering   (QA)
#   AutoModelForCausalLM             (GPT-style generation)
#   AutoModelForSeq2SeqLM            (T5/BART translation, summarization)
#   AutoModelForMaskedLM             (BERT-style MLM)

Trainer로 파인튜닝

Trainer가 학습 루프(배칭, 그래디언트 누적, 혼합 정밀도, 평가, 체크포인트)를 처리해 보일러플레이트를 최소화합니다. TrainingArguments로 학습률, 배치 크기, 에포크, 평가/저장 전략을 제어하세요. load_best_model_at_end=True가 최선의 체크포인트를 유지합니다. 완전한 제어(커스텀 손실, 멀티태스크)에는 평범한 PyTorch 루프를 쓸 수 있으며 Trainer는 편의 기능일 뿐 제약이 아닙니다.

nlp
from transformers import (AutoTokenizer, AutoModelForSequenceClassification,
                          TrainingArguments, Trainer)
from datasets import load_dataset
import evaluate

model_name = "bert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=2)

dataset = load_dataset("imdb")

def tokenize(batch):
    return tokenizer(batch["text"], truncation=True, padding="max_length", max_length=256)

train_ds = dataset["train"].map(tokenize, batched=True).rename_column("label", "labels")
train_ds.set_format("torch", columns=["input_ids", "attention_mask", "labels"])

accuracy = evaluate.load("accuracy")
def compute_metrics(eval_pred):
    logits, labels = eval_pred
    return accuracy.compute(predictions=logits.argmax(-1), references=labels)

args = TrainingArguments(
    output_dir="imdb-bert",
    eval_strategy="epoch",
    save_strategy="epoch",
    learning_rate=2e-5,
    per_device_train_batch_size=16,
    num_train_epochs=3,
    load_best_model_at_end=True,
)
trainer = Trainer(model=model, args=args,
                  train_dataset=train_ds,
                  eval_dataset=dataset["test"].map(tokenize, batched=True),
                  compute_metrics=compute_metrics)
trainer.train()

Datasets 라이브러리

datasets는 수천 개 NLP 데이터셋에 통합 API를 줍니다. 스마트 캐싱, 메모리 매핑(거대 데이터에서 OOM 없음), 스트리밍 모드. map(batched=True)가 멀티프로세싱으로 전처리를 병렬 적용합니다. 내장 메서드(filter, shuffle, train_test_split)가 pandas/sklearn을 미러링합니다. Hub는 'evaluate' 라이브러리로 지표도 호스팅합니다.

nlp
from datasets import load_dataset, Dataset

# thousands of datasets, one API, streaming for huge ones
squad = load_dataset("squad", split="train[:1%]")
print(squad.column_names)   # ['id', 'title', 'context', 'question', 'answers']

# map over examples (batched for speed)
def preprocess(batch):
    return tokenizer(batch["context"], truncation=True)
squad = squad.map(preprocess, batched=True)

# filter / shuffle / select
squad = squad.filter(lambda ex: len(ex["context"]) > 100).shuffle(seed=42)

# create your own from a dict or CSV/JSON
ds = Dataset.from_dict({"text": ["a", "b"], "label": [0, 1]})
ds = Dataset.from_csv("data.csv")

# stream a huge dataset without downloading fully
wiki = load_dataset("wikipedia", "20220301.en", streaming=True)
for ex in wiki: break   # first example only

Tokenizers 라이브러리

tokenizers 라이브러리(Rust 코어, Python 바인딩)로 커스텀 BPE/WordPiece/Unigram 토크나이저를 빠르게 학습합니다. 순수 Python의 수 시간 대비 수 분. 노멀라이저가 유니코드를 처리하고(NFD, 소문자화, 악센트 제거) 디코더가 ID에서 표면 텍스트를 재구성합니다. 결과를 PreTrainedTokenizerFast로 감싸 transformers Trainer에 연결하세요. 조용한 정확도 손실을 피하려 모델의 정확한 토큰화를 미러링하세요.

nlp
from tokenizers import Tokenizer
from tokenizers.models import BPE
from tokenizers.trainers import BpeTrainer
from tokenizers.pre_tokenizers import Whitespace, Metaspace
from tokenizers.decoders import Metaspace as MetaspaceDecoder
from tokenizers.normalizers import NFD, Lowercase, StripAccents, Sequence

# build a tokenizer from scratch (fast, Rust-backed)
tokenizer = Tokenizer(BPE(unk_token="[UNK]"))
tokenizer.normalizer = Sequence([NFD(), Lowercase(), StripAccents()])
tokenizer.pre_tokenizer = Whitespace()

trainer = BpeTrainer(vocab_size=30000,
                     special_tokens=["[UNK]", "[PAD]", "[CLS]", "[SEP]", "[MASK]"])
tokenizer.train(files=["corpus.txt"], trainer=trainer)

# encode/decode
enc = tokenizer.encode("Hello, world!")
print(enc.ids, enc.tokens)
print(tokenizer.decode(enc.ids))

# save / load
tokenizer.save("my_tokenizer.json")
tok = Tokenizer.from_file("my_tokenizer.json")

# use with transformers: wrap as PreTrainedTokenizerFast

Model Hub와 공유

Hub가 생태계의 심장입니다. 사전학습 모델, 데이터셋, 데모가 한곳에 있습니다. 파인튜닝 모델은 trainer.push_to_hub()로 밀어 올리면 팀원들(또는 미래의 자신)이 이름으로 로드할 수 있습니다. 학습 데이터, 의도된 용도, 한계를 설명하는 모델 카드를 추가하세요. 좋은 관행이며 책임 있는 AI에 점점 필수 요구됩니다. 비공개 리포에는 토큰이 필요하고 조직 계정으로 공유하세요.

nlp
# The Hugging Face Hub hosts 100k+ models and datasets.
# Browse: https://huggingface.co/models

# load any model by its repo id
from transformers import AutoModel, AutoTokenizer
model = AutoModel.from_pretrained("bert-base-uncased")
# private/org models need an access token:
# AutoModel.from_pretrained("org/private-model", token="hf_xxx")

# share your own fine-tuned model
from huggingface_hub import HfApi
# 1. huggingface-cli login  (one-time, paste a token)
# 2. push from a Trainer:
trainer.push_to_hub("my-imdb-bert")
# 3. or push manually:
# api = HfApi()
# api.create_repo(repo_id="my-imdb-bert", repo_type="model")
# api.upload_folder(folder_path="imdb-bert", repo_id="my-imdb-bert")

# now anyone (or your team) can load it:
# AutoModel.from_pretrained("your-username/my-imdb-bert")

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.