python - 将 scipy.sparse.csr.csr_matrix 转换为列表列表

标签 python machine-learning scipy scikit-learn tf-idf

我正在学习多标签分类并尝试通过 scikit 学习实现 tfidf 教程。 我正在处理一个文本语料库来计算它的 tf-idf 分数。 为此,我正在使用模块 sklearn.feature_extraction.text。使用 CountVectorizer 和 TfidfTransformer,我现在对每个词汇表进行了语料库矢量化和 tfidf。 问题是我现在有一个稀疏矩阵,例如:

(0, 47) 0.104275891915
(0, 383)    0.084129133023
.
.
.
.
(4, 308)    0.0285015996586
(4, 199)    0.0285015996586

我想将这个 sparse.csr.csr_matrix 转换成一个列表列表,这样我就可以从上面的 csr_matrix 中去掉文档 id 并得到 tfidf 和 vocabularyId 对

47:0.104275891915 383:0.084129133023
.
.
.
.
308:0.0285015996586 
199:0.0285015996586

是否有任何方法可以转换为列表列表或任何其他我可以更改格式以获取 tfidf-vocabularyId 对的方法?

最佳答案

我不知道 tf-idf 期望什么,但我可能会在稀疏端提供帮助。

制作一个稀疏矩阵:

In [526]: M=sparse.random(4,10,.1)
In [527]: M
Out[527]: 
<4x10 sparse matrix of type '<class 'numpy.float64'>'
    with 4 stored elements in COOrdinate format>
In [528]: print(M)
  (3, 1)    0.281301619779
  (2, 6)    0.830780358032
  (1, 1)    0.242503399296
  (2, 2)    0.190933579917

现在将其转换为coo 格式。这已经是这样了(我可以给 random 一个格式参数)。在任何情况下,coo 格式的值都存储在 3 个数组中:

In [529]: Mc=M.tocoo()
In [530]: Mc.data
Out[530]: array([ 0.28130162,  0.83078036,  0.2425034 ,  0.19093358])
In [532]: Mc.row
Out[532]: array([3, 2, 1, 2], dtype=int32)
In [533]: Mc.col
Out[533]: array([1, 6, 1, 2], dtype=int32)

看起来您想忽略 Mc.row,并以某种方式加入其他人。

例如作为字典:

In [534]: {k:v for k,v in zip(Mc.col, Mc.data)}
Out[534]: {1: 0.24250339929583264, 2: 0.19093357991697379, 6: 0.83078035803205375}

或二维数组中的列:

In [535]: np.column_stack((Mc.col, Mc.data))
Out[535]: 
array([[ 1.        ,  0.28130162],
       [ 6.        ,  0.83078036],
       [ 1.        ,  0.2425034 ],
       [ 2.        ,  0.19093358]])

(还有 np.array((Mc.col, Mc.data)).T)

或者只是一个数组列表[Mc.col, Mc.data],或者[Mc.col.tolist(), Mc.data.tolist()]列表列表等

你能从那里拿走它吗?

关于python - 将 scipy.sparse.csr.csr_matrix 转换为列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40694972/

相关文章:

python - win32com Powerpoint 无法处理名称中的空格

python - 使用 itertools 进行枚举条件仅获取某些列表索引(python)

machine-learning - 多维数据集的核函数

opencv - 深度学习 - 如何执行 RANDOM CROP 并且不丢失数据中的任何信息(更改地面实况标签)

python - 如何找到属于非方阵零空间的线性无关向量? (Python)

python - 列表大小不同

python - 如何在 Kivy 中压缩 GridLayout 垂直空间?

python - 如何为 Sagemaker 编写 Tensorflow KMeans Estimator 脚本

python - 从矩阵中有效地减去向量(Scipy)

python - `scipy.optimize.root` 更快的根查找