如何衡量文本文檔之間的相似度?

DDD
發布: 2024-10-23 06:55:02
原創
985 人瀏覽過

How to Measure the Similarity Between Text Documents?

確定文本文檔之間的相似度

測量文檔相似度

為了確定NLP 中兩個文本文檔之間的相似度,標準方法是將文件轉換為TF-IDF 向量。然後利用這些向量來計算餘弦相似度,這是資訊檢索系統中常用的一種量測。如需更深入的信息,請參閱線上電子書《資訊檢索簡介》。

Python 中的實作

Python 提供了 Gensim 等函式庫和 scikit-learn 有助於計算 TF-IDF 和餘弦相似度。在scikit-learn 中,計算文件之間的餘弦相似度涉及利用它們的TF-IDF 向量:

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

documents = [open(f).read() for f in text_files]
tfidf = TfidfVectorizer().fit_transform(documents)
pairwise_similarity = tfidf * tfidf.T</code>
登入後複製

可以直接處理純文字文件:

<code class="python">corpus = ["I'd like an apple", "An apple a day keeps the doctor away"]
tfidf = TfidfVectorizer(min_df=1, stop_words="english").fit_transform(corpus)
pairwise_similarity = tfidf * tfidf.T</code>
登入後複製

解釋結果

產生的稀疏矩陣pairwise_similarity是正方形的。要識別與給定文檔最相似的文檔,您可以在屏蔽對角線元素(表示自相似性)後使用 NumPy 的 argmax 函數。

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

arr = pairwise_similarity.toarray()
np.fill_diagonal(arr, np.nan)
input_doc = "Document to compare"
input_idx = corpus.index(input_doc)
result_idx = np.nanargmax(arr[input_idx])
most_similar_doc = corpus[result_idx]</code>
登入後複製

以上是如何衡量文本文檔之間的相似度?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!