将scipy.sparse.csr.csr_矩阵转换为列表列表

2024-07-05 12:31:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习多标签分类,并尝试从scikit learning中实现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_矩阵转换成一个列表列表,这样我就可以从上面的csr_矩阵中去掉文档id,得到tfidf和vocabularyId对,就像

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

有没有任何方法可以转换成列表列表,或者有任何其他方法可以更改格式以获取tfidf vocabularyId对?


Tags: 方法文本列表tf分类教程矩阵标签
1条回答
网友
1楼 · 发布于 2024-07-05 12:31:14

我不知道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()],等等

你能从那里拿走吗?

相关问题 更多 >