如何使用 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学习者快速成长!