Python - csr_matrix 的数据结构

标签 python numpy scipy scikit-learn

我正在研究 TFIDF。我使用过tfidf_vectorizer.fit_transform。它返回一个csr_matrix,但我无法理解结果的结构。

  • 数据输入:

documents = ( "The sky is blue", "The sun is bright", "The sun in the sky is bright", "We can see the shining sun, the bright sun" )

  • 声明:
tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix = tfidf_vectorizer.fit_transform(documents)
print(tfidf_matrix)
  • 结果:

(0, 9) 0.34399327143
(0, 7) 0.519713848879
(0, 4) 0.420753151645
(0, 0) 0.659191117868
(1, 9) 0.426858009784
(1, 4) 0.522108621994
(1, 8) 0.522108621994
(1, 1) 0.522108621994
(2, 9) 0.526261040111
(2, 7) 0.397544332095
(2, 4) 0.32184639876
(2, 8) 0.32184639876
(2, 1) 0.32184639876
(2, 3) 0.504234576856
(3, 9) 0.390963088213
(3, 8) 0.47820398015
(3, 1) 0.239101990075
(3, 10) 0.374599471224
(3, 2) 0.374599471224
(3, 5) 0.374599471224
(3, 6) 0.374599471224

tfidf_matrix 是一个 csr_matrix。所以我找到了这个,但没有与结果相同的结构:scipy.sparse.csr_matrix

(0, 9) 0.34399327143 的值结构是什么?

最佳答案

您看到的只是调用print(my_csr_mat)时使用的字符串表示。它列出了(在您的情况下)矩阵中的所有非零。 (可能会有大量非零的截断输出)。

由于这是一个稀疏矩阵,因此它具有 2 维。

(0, 9) 0.34399327143

表示:矩阵元素@位置[0,9]为0.34399327143。

小演示:

import numpy as np
from scipy.sparse import csr_matrix

matrix_dense = np.arange(20).reshape(4,5)
zero_out = np.random.choice((0,1), size=(4,5), p=(0.7, 0.3))
matrix_dense_mod = matrix_dense * zero_out

print(matrix_dense_mod)

sparse_mat = csr_matrix(matrix_dense_mod)

print(sparse_mat)

输出:

[[ 0  0  2  0  4]
 [ 0  6  0  8  0]
 [ 0 11  0 13 14]
 [15  0  0 18 19]]
  (0, 2)        2
  (0, 4)        4
  (1, 1)        6
  (1, 3)        8
  (2, 1)        11
  (2, 3)        13
  (2, 4)        14
  (3, 0)        15
  (3, 3)        18
  (3, 4)        19

我不确定你的意思所以我发现了这一点,但没有与结果相同的结构,但要注意:scipy.sparse 文档中的大多数示例都有打印调用中的 my_mat.toarray() 意味着它正在从稀疏矩阵构建一个密集数组,该矩阵具有不同的字符串表示样式

关于Python - csr_matrix 的数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45678491/

相关文章:

python - 我在 train_score 中遇到错误,有人可以解决吗?

python - 将字母数字值转换为日期

python - 使用 Python/NumPy 对数组中的项目进行排名,无需对数组进行两次排序

python - 数据集的傅立叶平滑

python插值需要很长时间

scipy - 理解 scipy.stats.chisquare

python - Django 模拟补丁无法正常工作

python - 当代码在 Linux 上运行良好时 Windows 上的编码错误

python - 如何从通过 JavaScript 加载的页面的 XHR 请求中自动检索请求 URL(对于 python)

python - 如何使用 numpy.void 类型