[파이썬] 문서 유사도 측정 방법

문서 유사도 측정은 자연어 처리 분야에서 중요한 주제 중 하나입니다. 문서 유사도는 두 개의 문서가 얼마나 유사한지를 측정하는 방법을 의미합니다. 이는 정보 검색, 텍스트 분석, 문서 클러스터링 등 다양한 응용 분야에서 활용됩니다.

Python은 자연어 처리를 위한 강력한 도구를 제공하며, 다양한 문서 유사도 측정 방법을 쉽게 구현할 수 있습니다. 여기서는 Python을 사용하여 가장 널리 사용되는 두 가지 문서 유사도 측정 방법인 코사인 유사도와 유클리디안 거리를 소개하겠습니다.

코사인 유사도 (Cosine Similarity)

코사인 유사도는 두 벡터 간의 각도를 이용하여 문서 유사도를 측정하는 방법입니다. 코사인 유사도는 벡터의 크기에 영향을 받지 않기 때문에 문서의 길이가 다른 경우에도 정확한 결과를 얻을 수 있습니다.

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

# 문서들
documents = [
    "This is the first document.",
    "This document is the second document.",
    "And this is the third one.",
    "Is this the first document?"
]

# 문서 벡터화
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(documents)

# 코사인 유사도 계산
cosine_similarities = cosine_similarity(X, X)

# 결과 출력
for i in range(len(documents)):
    for j in range(len(documents)):
        print(f"Cosine Similarity between document {i+1} and document {j+1}: {cosine_similarities[i][j]}")

위 코드는 sklearn 라이브러리를 사용하여 문서 벡터화와 코사인 유사도를 계산하는 예제입니다. 문서들을 단어로 분리하고 벡터로 표현한 후, cosine_similarity 함수를 사용하여 코사인 유사도를 계산합니다.

유클리디안 거리 (Euclidean Distance)

유클리디안 거리는 두 벡터 간의 거리를 이용하여 문서 유사도를 측정하는 방법입니다. 유클리디안 거리는 각 차원의 차이를 제곱하여 더한 후 제곱근을 취한 값으로 계산됩니다. 유클리디안 거리는 벡터의 크기에 영향을 받기 때문에 문서의 길이가 다른 경우에는 정확한 결과를 얻을 수 없을 수 있습니다.

import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import euclidean_distances

# 문서들
documents = [
    "This is the first document.",
    "This document is the second document.",
    "And this is the third one.",
    "Is this the first document?"
]

# 문서 벡터화
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(documents)

# 유클리디안 거리 계산
euclidean_dists = euclidean_distances(X, X)

# 결과 출력
for i in range(len(documents)):
    for j in range(len(documents)):
        print(f"Euclidean Distance between document {i+1} and document {j+1}: {euclidean_dists[i][j]}")

위 코드는 sklearn 라이브러리를 사용하여 문서 벡터화와 유클리디안 거리를 계산하는 예제입니다. 코사인 유사도와 비슷하게 문서 벡터화를 수행한 후, euclidean_distances 함수를 사용하여 유클리디안 거리를 계산합니다.

결론

문서 유사도 측정은 자연어 처리 분야에서 중요한 주제이며, Python을 사용하여 다양한 방법으로 구현할 수 있습니다. 이 글에서는 코사인 유사도와 유클리디안 거리를 예시로 소개하였지만, 다른 방법들도 있으며 상황에 따라 적절한 방법을 선택해야 합니다. Python과 관련된 라이브러리들을 활용하여 문서 유사도를 측정할 수 있으므로, 자연어 처리 프로젝트에서 이를 활용해보세요!