CBOW에서 Skip-gram으로 변환할 때 달라진 주요 부분을 전후 비교로 설명해드리겠습니다:
CBOW 코드:
# 2. 문맥 단어와 타겟 단어 설정
context_words = ["this", "is", "a", "comparison"]
target_word = "visual" # 정답 단어
target_idx = vocab.index(target_word)
Skip-gram 코드:
# 2. Skip-gram에서는 중심 단어로 문맥 단어를 예측
center_word = "visual" # 중심 단어
center_idx = vocab.index(center_word)
context_words = ["this", "is", "a", "comparison"] # 예측할 문맥 단어들
context_idxs = torch.tensor([vocab.index(w) for w in context_words])
CBOW 코드:
# 기본 가중치 텐서 (학습 과정에서 업데이트할 값)
weight_data = torch.randn(vocab_size, embedding_dim) * 0.1
Skip-gram 코드:
# 두 가지 가중치 텐서 (Skip-gram은 일반적으로 두 임베딩 행렬을 사용)
# W: 입력 단어 -> 임베딩 (중심 단어)
# W_out: 임베딩 -> 출력 단어 (문맥 단어)
W = torch.randn(vocab_size, embedding_dim) * 0.1
W_out = torch.randn(vocab_size, embedding_dim) * 0.1
CBOW 코드:
# 4. 문맥 벡터 평균 계산 - einops 사용
context_vectors = embeddings[context_idxs]
h = reduce(context_vectors, 'n d -> d', 'mean')
Skip-gram 코드:
# 4. 중심 단어 벡터 구하기
h = center_embeddings[center_idx] # 중심 단어 임베딩
CBOW 코드:
# 7. 손실 계산 (Cross Entropy Loss)
loss = -torch.log(target_prob)
Skip-gram 코드:
# 7. 손실 계산 (모든 문맥 단어에 대한 Cross Entropy Loss의 평균)
# Skip-gram은 여러 문맥 단어에 대한 확률을 계산함
context_probs = probs[context_idxs]
log_context_probs = torch.log(context_probs)
loss = -torch.mean(log_context_probs) # 평균 손실
CBOW 코드:
# 9. 수동으로 파라미터 업데이트 (PyTorch 텐서 직접 업데이트)
with torch.no_grad():
# 원본 weight_data 텐서 업데이트
weight_data -= learning_rate * embeddings.grad
Skip-gram 코드:
# 9. 수동으로 파라미터 업데이트
with torch.no_grad():
# 원본 가중치 텐서 업데이트
W -= learning_rate * center_embeddings.grad
W_out -= learning_rate * context_embeddings.grad
CBOW 코드:
predicted_word = vocab[torch.argmax(probs).item()]
print(f"예측된 단어: {predicted_word}")
print(f"타겟 단어 확률: {target_prob.item():.4f}")
print(f"정답 여부: {predicted_word == target_word}")
Skip-gram 코드:
# 가장 확률이 높은 문맥 단어들 출력
_, top_indices = torch.topk(probs, 4)
predicted_context = [vocab[idx.item()] for idx in top_indices]
print(f"예측된 문맥 단어들: {predicted_context}")
print(f"실제 문맥 단어들: {context_words}")
이러한 변경 사항들이 Skip-gram의 핵심 원리를 구현하는데 필요한 주요 수정 사항입니다.
https://colab.research.google.com/drive/1pDHSzmvWrK623nDr2yUBBY2oH97L0VAm?usp=sharing
CBOW와 Skip-gram 언어 모델의 완성도와 한계를 파악하기 위한 질문들...
데이터 관련 질문
모델 구조 관련 질문
언어적 특성 포착 관련 질문
평가 관련 질문
기술적 한계 파악
근간 기술의 한계
현대적 접근법과의 비교
이러한 질문들을 통해 CBOW와 Skip-gram 언어 모델의 강점과 한계를 종합적으로 평가하고, 현대 언어 모델로의 발전 과정에서 이들의 역사적 위치와 기여를 파악할 수 있을 것입니다. 또한 향후 언어 모델 연구 방향을 가늠하는 데도 도움이 될 것입니다.