TF-IDF와 코사인 유사성을 사용하여 텍스트 문서 간의 유사성을 계산하는 방법은 무엇입니까?

Mary-Kate Olsen
풀어 주다: 2024-10-23 06:47:02
원래의
372명이 탐색했습니다.

How to Calculate Similarity Between Text Documents Using TF-IDF and Cosine Similarity?

텍스트 문서 유사성을 계산하는 방법

쌍별 유사성 계산

두 텍스트 문서 간의 유사성을 결정하는 가장 일반적인 방법은 두 텍스트 문서를 다음으로 변환하는 것입니다. TF-IDF(Term Frequency-Inverse Document Frequency) 벡터를 사용한 다음 코사인 유사성을 사용하여 비교합니다. 이 접근 방식은 정보 검색에 대한 교과서에서 다루며 "정보 검색 소개"에 자세히 설명되어 있습니다.

Gensim 및 scikit-learn과 같은 Python 라이브러리는 TF-IDF 변환 및 코사인 유사성 계산 구현을 제공합니다. scikit-learn을 사용하면 다음 코드 조각이 코사인 유사성 계산을 수행합니다.

<code class="python">from sklearn.feature_extraction.text import TfidfVectorizer

# Extract documents from text files
documents = [open(f).read() for f in text_files]

# Create a TF-IDF vectorizer
tfidf = TfidfVectorizer().fit_transform(documents)

# Calculate pairwise cosine similarity
pairwise_similarity = tfidf * tfidf.T</code>
로그인 후 복사

또는 일반 텍스트 문서의 경우:

<code class="python">corpus = ["I'd like an apple", 
           "An apple a day keeps the doctor away", 
           "Never compare an apple to an orange", 
           "I prefer scikit-learn to Orange", 
           "The scikit-learn docs are Orange and Blue"]                                                                                                                                                                                                   

# Create a TF-IDF vectorizer with minimum frequency and exclusion of stop words
vect = TfidfVectorizer(min_df=1, stop_words="english")                                                                                                                                                                                                   

# Apply TF-IDF transformation
tfidf = vect.fit_transform(corpus)                                                                                                                                                                                                                       

# Calculate pairwise cosine similarity
pairwise_similarity = tfidf * tfidf.T </code>
로그인 후 복사

결과 해석

pairwise_similarity는 각 행과 열이 말뭉치의 문서를 나타내는 희소 행렬입니다. 희소 행렬을 NumPy 배열로 변환하면 각 셀이 해당하는 두 문서 간의 유사성을 나타냄을 알 수 있습니다.

예를 들어 "The scikit-learn docs are Orange and Blue"와 가장 유사한 문서를 확인하려면 다음을 찾으세요. np.fill_diagonal()을 사용하여 대각선(자기 유사성을 나타냄)을 마스킹한 후 해당 행에 np.nanargmax를 적용합니다.

<code class="python">import numpy as np

arr = pairwise_similarity.toarray()     
np.fill_diagonal(arr, np.nan)                                                                                                                                                                                                                            

input_doc = "The scikit-learn docs are Orange and Blue"                                                                                                                                                                                                  
input_idx = corpus.index(input_doc)                                                                                                                                                                                                                      
result_idx = np.nanargmax(arr[input_idx])                                                                                                                                                                                                                
print(corpus[result_idx])</code>
로그인 후 복사

대규모 데이터 세트의 경우 희소 행렬은 메모리를 절약합니다. 또는 pairwise_similarity.shape를 사용하여 자기 유사성을 가리고 argmax()를 직접 사용하는 것을 고려해 보세요.

<code class="python">n, _ = pairwise_similarity.shape                                                                                                                                                                                                                         
pairwise_similarity[np.arange(n), np.arange(n)] = -1.0
pairwise_similarity[input_idx].argmax()  </code>
로그인 후 복사

위 내용은 TF-IDF와 코사인 유사성을 사용하여 텍스트 문서 간의 유사성을 계산하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!