Gensim과 Word2Vec을 활용한 문서 유사도 계산 방법 실습하기

이번 포스트에서는 Gensim과 Word2Vec을 사용하여 문서 간의 유사도를 계산하는 방법을 알아보겠습니다. Word2Vec은 단어의 의미적 유사성을 학습하는 알고리즘으로, Gensim은 Word2Vec을 포함한 다양한 토픽 모델링 및 자연어 처리 작업을 위한 파이썬 라이브러리입니다.

문서 유사도 계산을 위한 데이터 전처리

우선, 문서 유사도를 계산하기 위해 필요한 데이터를 전처리해야 합니다. 예를 들어, 문서들을 토큰화하고 불용어를 제거하는 작업을 수행해야 합니다.

import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize

# 불용어 제거를 위해 nltk의 stopwords를 다운로드 받습니다.
nltk.download('stopwords')

# 불용어와 문서를 토큰화합니다.
stop_words = set(stopwords.words('english'))

def preprocess_document(document):
    # 문서를 소문자로 변환합니다.
    document = document.lower()
    
    # 문장을 토큰화합니다.
    words = word_tokenize(document)
    
    # 불용어를 제거합니다.
    words = [word for word in words if word not in stop_words]
    
    return words

# 예시 문서
document1 = "The cat is sitting on the mat"
document2 = "The dog is running in the park"

# 문서를 전처리합니다.
preprocessed_document1 = preprocess_document(document1)
preprocessed_document2 = preprocess_document(document2)

Word2Vec 모델 학습

전처리된 문서들을 사용하여 Word2Vec 모델을 학습시킬 수 있습니다. Word2Vec은 단어들의 임베딩 벡터를 학습하여 단어 간의 유사도를 계산하는 방법입니다.

from gensim.models import Word2Vec

# Word2Vec 모델을 학습시킵니다.
model = Word2Vec([preprocessed_document1, preprocessed_document2], min_count=1)

# 단어 "cat"과 유사한 단어를 출력합니다.
similar_words = model.wv.most_similar('cat')

print(similar_words)

문서 유사도 계산

학습된 Word2Vec 모델을 사용하여 전처리된 문서들 간의 유사도를 계산할 수 있습니다. 유사도는 단어 벡터들의 코사인 유사도를 계산하여 얻을 수 있습니다.

# 문서 벡터를 계산합니다.
document_vector1 = model.infer_vector(preprocessed_document1)
document_vector2 = model.infer_vector(preprocessed_document2)

# 문서 간의 유사도를 계산합니다.
similarity = model.wv.cosine_similarities(document_vector1, [document_vector2])

print(similarity)

마무리

지금까지 Gensim과 Word2Vec을 사용하여 문서 간의 유사도를 계산하는 방법을 실습해보았습니다. 이를 활용하면 문서 분류, 검색, 추천 시스템 등에서 유용하게 활용할 수 있습니다.

향후 더 복잡한 자연어 처리 작업을 위해서는 학습 데이터의 크기와 품질에 따라 모델의 성능을 높일 수 있는 방법들을 추가로 적용해볼 수 있습니다.

#Gensim #Word2Vec