gpt4 book ai didi

Python:tf-idf-cosine:查找文档相似度

转载 作者:IT老高 更新时间:2023-10-28 21:31:24 25 4
gpt4 key购买 nike

我正在学习 Part 1 上提供的教程& Part 2 .不幸的是,作者没有时间在最后一节中使用余弦相似度来实际找到两个文档之间的距离。在 stackoverflow 的以下链接的帮助下,我按照文章中的示例进行了操作。 ,包括上面链接中提到的代码(只是为了让生活更轻松)

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from nltk.corpus import stopwords
import numpy as np
import numpy.linalg as LA

train_set = ["The sky is blue.", "The sun is bright."] # Documents
test_set = ["The sun in the sky is bright."] # Query
stopWords = stopwords.words('english')

vectorizer = CountVectorizer(stop_words = stopWords)
#print vectorizer
transformer = TfidfTransformer()
#print transformer

trainVectorizerArray = vectorizer.fit_transform(train_set).toarray()
testVectorizerArray = vectorizer.transform(test_set).toarray()
print 'Fit Vectorizer to train set', trainVectorizerArray
print 'Transform Vectorizer to test set', testVectorizerArray

transformer.fit(trainVectorizerArray)
print
print transformer.transform(trainVectorizerArray).toarray()

transformer.fit(testVectorizerArray)
print
tfidf = transformer.transform(testVectorizerArray)
print tfidf.todense()

由于上述代码,我有以下矩阵

Fit Vectorizer to train set [[1 0 1 0]
[0 1 0 1]]
Transform Vectorizer to test set [[0 1 1 1]]

[[ 0.70710678 0. 0.70710678 0. ]
[ 0. 0.70710678 0. 0.70710678]]

[[ 0. 0.57735027 0.57735027 0.57735027]]

我不确定如何使用此输出来计算余弦相似度,我知道如何针对两个长度相似的向量实现余弦相似度,但在这里我不确定如何识别这两个向量。

最佳答案

首先,如果您想提取计数特征并应用 TF-IDF 归一化和逐行欧几里得归一化,您可以使用 TfidfVectorizer 在一个操作中完成:

>>> from sklearn.feature_extraction.text import TfidfVectorizer
>>> from sklearn.datasets import fetch_20newsgroups
>>> twenty = fetch_20newsgroups()

>>> tfidf = TfidfVectorizer().fit_transform(twenty.data)
>>> tfidf
<11314x130088 sparse matrix of type '<type 'numpy.float64'>'
with 1787553 stored elements in Compressed Sparse Row format>

现在要找到一个文档(例如数据集中的第一个)和所有其他文档的余弦距离,您只需要计算第一个向量与所有其他向量的点积,因为 tfidf 向量已经是行-标准化。

正如 Chris Clark 在评论和 here 中所解释的那样余弦相似度不考虑向量的大小。行归一化的大小为 1,因此线性核足以计算相似度值。

scipy 稀疏矩阵 API 有点奇怪(不如密集的 N 维 numpy 数组灵活)。要获得第一个向量,您需要按行对矩阵进行切片以获得具有单行的子矩阵:

>>> tfidf[0:1]
<1x130088 sparse matrix of type '<type 'numpy.float64'>'
with 89 stored elements in Compressed Sparse Row format>

scikit-learn 已经提供了成对指标(机器学习术语中的内核),适用于向量集合的密集和稀疏表示。在这种情况下,我们需要一个点积,也称为线性核:

>>> from sklearn.metrics.pairwise import linear_kernel
>>> cosine_similarities = linear_kernel(tfidf[0:1], tfidf).flatten()
>>> cosine_similarities
array([ 1. , 0.04405952, 0.11016969, ..., 0.04433602,
0.04457106, 0.03293218])

因此要找到前 5 个相关文档,我们可以使用 argsort 和一些负数组切片(大多数相关文档具有最高的余弦相似度值,因此位于排序索引数组的末尾):

>>> related_docs_indices = cosine_similarities.argsort()[:-5:-1]
>>> related_docs_indices
array([ 0, 958, 10576, 3277])
>>> cosine_similarities[related_docs_indices]
array([ 1. , 0.54967926, 0.32902194, 0.2825788 ])

第一个结果是完整性检查:我们发现查询文档是最相似的文档,余弦相似度得分为 1,其文本如下:

>>> print twenty.data[0]
From: lerxst@wam.umd.edu (where's my thing)
Subject: WHAT car is this!?
Nntp-Posting-Host: rac3.wam.umd.edu
Organization: University of Maryland, College Park
Lines: 15

I was wondering if anyone out there could enlighten me on this car I saw
the other day. It was a 2-door sports car, looked to be from the late 60s/
early 70s. It was called a Bricklin. The doors were really small. In addition,
the front bumper was separate from the rest of the body. This is
all I know. If anyone can tellme a model name, engine specs, years
of production, where this car is made, history, or whatever info you
have on this funky looking car, please e-mail.

Thanks,
- IL
---- brought to you by your neighborhood Lerxst ----

第二个最相似的文档是引用原始消息的回复,因此有许多常用词:

>>> print twenty.data[958]
From: rseymour@reed.edu (Robert Seymour)
Subject: Re: WHAT car is this!?
Article-I.D.: reed.1993Apr21.032905.29286
Reply-To: rseymour@reed.edu
Organization: Reed College, Portland, OR
Lines: 26

In article <1993Apr20.174246.14375@wam.umd.edu> lerxst@wam.umd.edu (where's my
thing) writes:
>
> I was wondering if anyone out there could enlighten me on this car I saw
> the other day. It was a 2-door sports car, looked to be from the late 60s/
> early 70s. It was called a Bricklin. The doors were really small. In
addition,
> the front bumper was separate from the rest of the body. This is
> all I know. If anyone can tellme a model name, engine specs, years
> of production, where this car is made, history, or whatever info you
> have on this funky looking car, please e-mail.

Bricklins were manufactured in the 70s with engines from Ford. They are rather
odd looking with the encased front bumper. There aren't a lot of them around,
but Hemmings (Motor News) ususally has ten or so listed. Basically, they are a
performance Ford with new styling slapped on top.

> ---- brought to you by your neighborhood Lerxst ----

Rush fan?

--
Robert Seymour rseymour@reed.edu
Physics and Philosophy, Reed College (NeXTmail accepted)
Artificial Life Project Reed College
Reed Solar Energy Project (SolTrain) Portland, OR

关于Python:tf-idf-cosine:查找文档相似度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12118720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com