【问题标题】:Finding k most similar documents查找 k 个最相似的文档
【发布时间】:2016-07-07 15:41:50
【问题描述】:

我有一些文档,我想找到与所选文档最相似的 k 个文档。为了一个可重现的例子,假设 k 是 1,我的文档是这些

documents = ['Two roads diverged in a yellow wood,',
             'And sorry I could not travel both',
             'And be one traveler, long I stood',
             'And looked down one as far as I could',
             'To where it bent in the undergrowth']

然后我想我想做的是下面。 (我使用CountVectorizer 是为了透明和简单,即使以后我想使用 Tf-Idf 和散列矢量化器。)

from sklearn.feature_extraction.text import CountVectorizer
import numpy as np

vectorizer = CountVectorizer(analyzer='word')
ft = vectorizer.fit_transform(documents)
one_doc = documents[1]
one_doc_code = vectorizer.transform([one_doc])
doc_match = np.matrix(ft) * np.matrix(one_doc_code.transpose())

现在doc_match 是一个列向量,其权重表示匹配的接近程度(0 = 不匹配,1 = 完美匹配)。但是为了进行乘法,我(在绝望中,面对逐元素乘法)转换为一个 numpy 矩阵,所以现在我有了这个没有 todense() 成员的 CSR 格式矩阵(所以我可以'不只是看,这不会超出我的小例子)。

我想我现在想要的(但到目前为止还没有弄清楚)是怎么说“doc_match 的前 k 个元素的索引是什么?” (即使 k 不是 1)。

【问题讨论】:

  • doc_match 是否等同于 ft.dot(one_doc_code.T)

标签: python scipy scikit-learn


【解决方案1】:

如果您想要的只是doc_match 中得分最高的索引,您可以这样做:

sorted_indices = np.argsort(doc_match)
doc_match_vals_sorted = doc_match[sorted_indices]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 2012-08-20
    • 2012-03-17
    • 1970-01-01
    • 2019-05-23
    • 1970-01-01
    相关资源
    最近更新 更多