107

我正在关注第 1部分和第 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]]

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

4

6 回答 6

186

首先,如果您想提取计数特征并应用 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 在评论中所解释的,这里的余弦相似度没有考虑向量的大小。行归一化的大小为 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
于 2012-08-26T08:45:15.370 回答
24

在@excray 评论的帮助下,我设法找出答案,我们需要做的实际上是编写一个简单的 for 循环来遍历代表训练数据和测试数据的两个数组。

首先实现一个简单的 lambda 函数来保存余弦计算公式:

cosine_function = lambda a, b : round(np.inner(a, b)/(LA.norm(a)*LA.norm(b)), 3)

然后只需编写一个简单的 for 循环来迭代 to 向量,逻辑是针对每个“对于 trainVectorizerArray 中的每个向量,您必须找到与 testVectorizerArray 中的向量的余弦相似度。”

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
cx = lambda a, b : round(np.inner(a, b)/(LA.norm(a)*LA.norm(b)), 3)

for vector in trainVectorizerArray:
    print vector
    for testV in testVectorizerArray:
        print testV
        cosine = cx(vector, testV)
        print cosine

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]]
[1 0 1 0]
[0 1 1 1]
0.408
[0 1 0 1]
[0 1 1 1]
0.816

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

[[ 0.          0.57735027  0.57735027  0.57735027]]
于 2012-08-25T19:27:53.153 回答
20

我知道它是一个旧帖子。但我尝试了http://scikit-learn.sourceforge.net/stable/包。这是我查找余弦相似度的代码。问题是你将如何计算这个包的余弦相似度,这是我的代码

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import TfidfVectorizer

f = open("/root/Myfolder/scoringDocuments/doc1")
doc1 = str.decode(f.read(), "UTF-8", "ignore")
f = open("/root/Myfolder/scoringDocuments/doc2")
doc2 = str.decode(f.read(), "UTF-8", "ignore")
f = open("/root/Myfolder/scoringDocuments/doc3")
doc3 = str.decode(f.read(), "UTF-8", "ignore")

train_set = ["president of India",doc1, doc2, doc3]

tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix_train = tfidf_vectorizer.fit_transform(train_set)  #finds the tfidf score with normalization
print "cosine scores ==> ",cosine_similarity(tfidf_matrix_train[0:1], tfidf_matrix_train)  #here the first element of tfidf_matrix_train is matched with other three elements

这里假设查询是 train_set 的第一个元素,而 doc1、doc2 和 doc3 是我想借助余弦相似度对文档进行排名。然后我可以使用这段代码。

问题中提供的教程也非常有用。这是它的所有部分 part-I , part-II , part-III

输出如下:

[[ 1.          0.07102631  0.02731343  0.06348799]]

这里 1 表示查询与自身匹配,其他三个是查询与相应文档匹配的分数。

于 2013-09-20T10:48:00.077 回答
17

让我再给你一个我写的教程。它回答了你的问题,但也解释了我们为什么要做一些事情。我也试着让它简洁。

所以你有一个list_of_documents只是一个字符串数组,另一个document只是一个字符串。您需要从list_of_documents最相似的文档中找到此类文档document

让我们将它们组合在一起:documents = list_of_documents + [document]

让我们从依赖关系开始。很清楚为什么我们使用它们中的每一个。

from nltk.corpus import stopwords
import string
from nltk.tokenize import wordpunct_tokenize as tokenize
from nltk.stem.porter import PorterStemmer
from sklearn.feature_extraction.text import TfidfVectorizer
from scipy.spatial.distance import cosine

可以使用的一种方法是词袋方法,我们将文档中的每个词独立于其他词,然后将它们全部放在一个大袋子中。从一个角度来看,它丢失了很多信息(比如单词是如何连接的),但从另一个角度来看,它使模型变得简单。

在英语和任何其他人类语言中,有很多“无用”的词,如“a”、“the”、“in”,它们很常见,以至于它们没有太多意义。它们被称为停用词,最好删除它们。人们可以注意到的另一件事是,“分析”、“分析器”、“分析”等词非常相似。它们有一个共同的词根,并且都可以转换为一个单词。这个过程称为词干提取,存在不同的词干分析器,它们在速度、攻击性等方面有所不同。因此,我们将每个文档转换为没有停用词的词干列表。我们也丢弃了所有的标点符号。

porter = PorterStemmer()
stop_words = set(stopwords.words('english'))

modified_arr = [[porter.stem(i.lower()) for i in tokenize(d.translate(None, string.punctuation)) if i.lower() not in stop_words] for d in documents]

那么这个词袋将如何帮助我们呢?假设我们有 3 个袋子[a, b, c][a, c, a][b, c, d]。我们可以将它们转换为基础中的向量 [a, b, c, d]。所以我们最终得到向量[1, 1, 1, 0][2, 0, 1, 0][0, 1, 1, 1]。我们的文档也是如此(只有向量会更长)。现在我们看到我们删除了很多单词并删除了其他单词以减少向量的维度。这里有一个有趣的观察。较长的文档将比较短的文档具有更多的正元素,这就是规范化向量的好处。这称为词频 TF,人们还使用了有关该词在其他文档中使用频率的附加信息——逆文档频率 IDF。我们一起有一个度量TF-IDF,它有几种风格. 这可以通过 sklearn 中的一行来实现 :-)

modified_doc = [' '.join(i) for i in modified_arr] # this is only to convert our list of lists to list of strings that vectorizer uses.
tf_idf = TfidfVectorizer().fit_transform(modified_doc)

实际上矢量化器允许做很多事情,比如删除停用词和小写。我在单独的步骤中完成了它们,只是因为 sklearn 没有非英语停用词,但 nltk 有。

所以我们计算了所有的向量。最后一步是找到与最后一个最相似的一个。有多种方法可以实现这一点,其中之一是欧几里得距离,由于这里讨论的原因,它并不是那么大。另一种方法是余弦相似度。我们迭代所有文档并计算文档与最后一个文档之间的余弦相似度:

l = len(documents) - 1
for i in xrange(l):
    minimum = (1, None)
    minimum = min((cosine(tf_idf[i].todense(), tf_idf[l + 1].todense()), i), minimum)
print minimum

现在 minimum 将拥有有关最佳文档及其分数的信息。

于 2015-09-09T07:40:58.790 回答
14

这应该可以帮助你。

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity  

tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix = tfidf_vectorizer.fit_transform(train_set)
print tfidf_matrix
cosine = cosine_similarity(tfidf_matrix[length-1], tfidf_matrix)
print cosine

输出将是:

[[ 0.34949812  0.81649658  1.        ]]
于 2014-04-04T18:29:28.053 回答
4

这是一个将您的测试数据与训练数据进行比较的函数,其中 Tf-Idf 转换器与训练数据相匹配。优点是您可以快速旋转或分组以找到 n 个最接近的元素,并且计算是按矩阵向下的。

def create_tokenizer_score(new_series, train_series, tokenizer):
    """
    return the tf idf score of each possible pairs of documents
    Args:
        new_series (pd.Series): new data (To compare against train data)
        train_series (pd.Series): train data (To fit the tf-idf transformer)
    Returns:
        pd.DataFrame
    """

    train_tfidf = tokenizer.fit_transform(train_series)
    new_tfidf = tokenizer.transform(new_series)
    X = pd.DataFrame(cosine_similarity(new_tfidf, train_tfidf), columns=train_series.index)
    X['ix_new'] = new_series.index
    score = pd.melt(
        X,
        id_vars='ix_new',
        var_name='ix_train',
        value_name='score'
    )
    return score

train_set = pd.Series(["The sky is blue.", "The sun is bright."])
test_set = pd.Series(["The sun in the sky is bright."])
tokenizer = TfidfVectorizer() # initiate here your own tokenizer (TfidfVectorizer, CountVectorizer, with stopwords...)
score = create_tokenizer_score(train_series=train_set, new_series=test_set, tokenizer=tokenizer)
score

   ix_new   ix_train    score
0   0       0       0.617034
1   0       1       0.862012
于 2018-09-10T17:05:43.787 回答