서브워드 토큰화를 통해 텍스트를 처리한 이후, 기계 학습 모델은 이를 수치 데이터로 변환해 학습한다.
이 과정을 임베딩(Embedding)이라고 하며, NLP 모델 성능의 핵심적인 요소로 작용한다.
Word2Vec은 단어를 고차원 벡터로 변환하는 기법으로, CBOW와 Skip-Gram 두 가지 모델이 있다.
단어: "강아지", "고양이"
유사도: cos(강아지, 고양이) ≈ 0.8
from gensim.models import Word2Vec
sentences = [["I", "love", "cats"], ["I", "love", "dogs"]]
model = Word2Vec(sentences, vector_size=100, window=5, min_count=1, workers=4)
vector = model.wv['cats']
print(vector)
GloVe는 단어의 동시 등장 행렬을 학습하여 전역적인 문맥 정보를 반영한다.
단어: "왕", "여왕", "남자", "여자"
벡터 연산: 왕 - 남자 + 여자 ≈ 여왕
from gensim.models import KeyedVectors
model = KeyedVectors.load_word2vec_format('glove.6B.100d.txt', binary=False)
vector = model['king']
print(vector)
FastText는 단어를 서브워드 단위로 분해하여 벡터를 학습한다.
단어: "unbelievable"
서브워드: ["un", "##bel", "##ievable"]
from gensim.models import FastText
sentences = [["I", "love", "coding"], ["coding", "is", "fun"]]
model = FastText(sentences, vector_size=100, window=5, min_count=1, workers=4)
vector = model.wv['coding']
print(vector)
Contextual Embeddings는 단어가 문맥에 따라 다른 벡터로 표현되는 기법이다.
대표적으로 BERT, GPT와 같은 트랜스포머 기반 모델에서 사용된다.
문장 1: "I saw a bat flying in the sky."
문장 2: "I used a bat to play baseball."
벡터: "bat"의 두 문맥에서 서로 다른 벡터로 표현.
from transformers import AutoTokenizer, AutoModel
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
model = AutoModel.from_pretrained("bert-base-uncased")
inputs = tokenizer("I saw a bat flying in the sky.", return_tensors="pt")
outputs = model(**inputs)
vector = outputs.last_hidden_state
print(vector)
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
vectors = model.wv.vectors
pca = PCA(n_components=2)
reduced_vectors = pca.fit_transform(vectors)
plt.scatter(reduced_vectors[:, 0], reduced_vectors[:, 1])
plt.show()
서브워드 토큰화 이후 임베딩은 NLP의 핵심 과정을 구성하며, 텍스트 데이터에서 의미를 학습하는 기초를 제공한다.
다양한 임베딩 기법을 활용하여 텍스트 데이터를 효과적으로 처리하고, 태스크에 맞는 최적의 표현을 선택하는 것이 중요하다.