搜索
首页后端开发Python教程如何使用 TF-IDF 和余弦相似度测量文本相似度?

How to Measure Text Similarity using TF-IDF and Cosine Similarity?

使用 TF-IDF 和余弦相似度测量文本相似度

确定两个文本文档之间的相似度是文本挖掘和信息中的一项关键任务检索。一种流行的方法是利用 TF-IDF(术语频率-逆文档频率)余弦相似度

TF-IDF 分配权重根据文档中每个单词在该文档中的出现频率及其在整个文档语料库中的稀有性来对文档中的每个单词进行分类。具有相似单词模式的文档将共享更高的 TF-IDF 向量。

余弦相似度 测量两个向量之间的角度,提供 0(无相似性)和 1(完全相似)之间的值。在我们的例子中,两个文档的 TF-IDF 向量形成了这些向量,余弦相似度量化了它们的角度。

Python 实现

在 Python 中,使用scikit-learnGensim 包,计算成对相似度很简单:

<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", "..."]
vect = TfidfVectorizer(min_df=1, stop_words="english")
tfidf = vect.fit_transform(corpus)
pairwise_similarity = tfidf * tfidf.T</code>

解释结果

pairwise_similarity 是一个稀疏矩阵,表示每个文档对之间的相似度。要查找与特定文档最相似的文档,请屏蔽文档与其自身的相似性(将其设置为 NaN),并使用 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])
similar_doc = corpus[result_idx]</code>

其他注意事项

对于大型语料库和词汇表,使用稀疏矩阵比转换为 NumPy 数组更高效。

通过调整 TfidfVectorizer 中的参数,例如最小文档的 min_df频率,可以自定义 TF-IDF 计算以满足特定要求。

其他资源

  • [信息检索简介](http://infolab .stanford.edu/~backrub/classes/2002/cs276/handouts/04-tfidf.pdf)
  • [使用 Gensim 计算成对相似性](https://stackoverflow.com/questions/23752770/computing-与 gensim 的成对相似性)

以上是如何使用 TF-IDF 和余弦相似度测量文本相似度?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Python:深入研究汇编和解释Python:深入研究汇编和解释May 12, 2025 am 12:14 AM

pythonisehybridmodelofcompilationand interpretation:1)thepythoninterspretercompilesourcececodeintoplatform- interpententbybytecode.2)thepytythonvirtualmachine(pvm)thenexecuteCutestestestesteSteSteSteSteSteSthisByTecode,BelancingEaseofuseWithPerformance。

Python是一种解释或编译语言,为什么重要?Python是一种解释或编译语言,为什么重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允许fordingfordforderynamictynamictymictymictymictyandrapiddefupment,尽管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

对于python中的循环时循环与循环:解释了关键差异对于python中的循环时循环与循环:解释了关键差异May 12, 2025 am 12:08 AM

在您的知识之际,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations则youneedtoloopuntilaconditionismet

循环时:实用指南循环时:实用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

Python:它是真正的解释吗?揭穿神话Python:它是真正的解释吗?揭穿神话May 12, 2025 am 12:05 AM

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

您可以使用Python中的循环加入列表吗?您可以使用Python中的循环加入列表吗?May 10, 2025 am 12:14 AM

是的,YouCanconCatenatElistsusingAloopInpyThon.1)使用eparateLoopsForeachListToAppendIteMstoaresultList.2)useanestedlooptoiterateOverMultipliplipliplipliplipliplipliplipliplipliplistforamoreConciseApprace.3)

condenate列表python:使用,扩展()等condenate列表python:使用,扩展()等May 10, 2025 am 12:12 AM

ThemostefficientmethodsforconcatenatinglistsinPythonare:1)theextend()methodforin-placemodification,2)itertools.chain()formemoryefficiencywithlargedatasets.Theextend()methodmodifiestheoriginallist,makingitmemory-efficientbutrequirescautionifpreserving

Python循环:示例和最佳实践Python循环:示例和最佳实践May 10, 2025 am 12:05 AM

pythonboopsincludeforandwhileloops,with forloopsidealforequencessand and whileloopsforcondition repetition.bestpracticesinvolve:1)使用listComprehensionsforshensionsforsimpletranspletransformations,2)obseringEnumerateForIndex-valuepairs,3)optingftingftingfortermornemoremoremoremore

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境