[python] gensim을 활용한 문서 유사도 계산 방법

이번 포스트에서는 Gensim을 사용하여 문서 유사도를 계산하는 방법에 대해 알아보겠습니다. Gensim은 Python의 자연어 처리 라이브러리로, 토픽 모델링 및 자연어처리 작업을 지원합니다.

1. Gensim 설치하기

먼저 Gensim을 설치해야 합니다. 아래의 명령어를 사용하여 Gensim을 설치합니다.

pip install gensim

2. 문서 유사도 계산하기

2.1 필요한 라이브러리 import하기

먼저 필요한 라이브러리를 import 합니다.

from gensim import corpora
from gensim import models
from gensim.similarities import Similarity

2.2 문서를 토큰화하고 벡터화하기

다음으로, 문서를 토큰화하고 벡터화합니다. 여기서는 간단한 예제를 통해 설명하겠습니다.

documents = [
    "This is the first document",
    "This document is the second document",
    "And this is the third one",
    "Is this the first document"
]

# 문서를 토큰화
texts = [[word for word in document.lower().split()] for document in documents]

# 사전 구축
dictionary = corpora.Dictionary(texts)

# 벡터화
corpus = [dictionary.doc2bow(text) for text in texts]

2.3 유사도 계산 모델 생성하기

이제 문서 간의 유사도를 계산할 모델을 생성합니다.

tfidf = models.TfidfModel(corpus)
sims = Similarity('C:/gensim_similarity/',tfidf[corpus], num_features=len(dictionary))

2.4 유사도 계산하기

이제 유사도를 계산할 수 있습니다.

query_doc = "This is the first document"
query_doc_bow = dictionary.doc2bow(query_doc.lower().split())

query_doc_tfidf = tfidf[query_doc_bow]
query_similarity = sims[query_doc_tfidf]

print(query_similarity)

위의 예제 코드를 실행하면 쿼리 문서와 각 원본 문서 간의 유사도가 출력됩니다.

이상으로 Gensim을 사용하여 문서 유사도를 계산하는 방법에 대해 알아보았습니다. Gensim은 다양한 자연어 처리 작업에 유용하게 사용될 수 있는 강력한 라이브러리입니다.

관련 참고 자료: Gensim Documentation