python - Python 中的术语文档矩阵和余弦相似度

标签 python numpy scipy term-document-matrix

我想使用 Python(最好使用 numpyscipy)解决以下情况:

  1. 我要转换为稀疏术语文档矩阵的文档集合。
  2. 提取每个文档的稀疏向量表示(即矩阵中的一行),并使用特定文档子集中的余弦相似度找出前 10 个相似的文档(文档标有类别,我想在同一类别中找到相似的文档).

如何在 Python 中实现这一点?我知道我可以使用 scipy.sparse.coo_matrix 将文档表示为稀疏向量并采用点积来查找余弦相似度,但是如何将整个语料库转换为一个大而稀疏的术语文档矩阵(所以我还可以将它的行提取为 scipy.sparse.coo_matrix 行向量)?

谢谢。

最佳答案

我可以推荐你看看scikit-learn ?这是 Python 社区中一个非常受欢迎的库,具有非常简单且一致的 API。他们还实现了 cosine similarity公制。这是取自 here 的示例如何用 3 行代码做到这一点:

>>> from sklearn.feature_extraction.text import TfidfVectorizer

>>> vect = TfidfVectorizer(min_df=1)
>>> tfidf = vect.fit_transform(["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"])
>>> (tfidf * tfidf.T).A
array([[ 1.        ,  0.25082859,  0.39482963,  0.        ],
       [ 0.25082859,  1.        ,  0.22057609,  0.        ],
       [ 0.39482963,  0.22057609,  1.        ,  0.26264139],
       [ 0.        ,  0.        ,  0.26264139,  1.        ]])

关于python - Python 中的术语文档矩阵和余弦相似度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18113379/

相关文章:

python - 当我在MacOS Catalina中使用launchctl时如何修复 "Operation not permitted"

python - Python 夏令时前一周发出警报

python - 在 python 中组合列表中的第一个元素和同一列表的其他元素

Python:矢量化/广播会提高速度吗?

python - 计算 "distance matrix"

python - .std() & .skew() 用 .rolling 给出错误答案

python - 在 python 中的单个表达式中打印 int 和 string

opencv - 如何从一维子阵列中选择白色像素最少和最大的子阵列?

Python优化问题?

python - 为什么 scipy 的 genfromtxt 将 NaN 值读取为 -1?