如何使用 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(術語頻率-逆文檔頻率)向量,然後使用餘弦相似度來比較它們。此方法在資訊檢索教科書中有所介紹,並在「資訊檢索簡介」中詳細介紹。

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學習者快速成長!