Sau*_*abh 4 python machine-learning scipy tf-idf scikit-learn
我正在学习多标签分类,并尝试从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
Run Code Online (Sandbox Code Playgroud)
我想将此sparse.csr.csr_matrix转换为列表列表,以便可以摆脱上述csr_matrix的文档ID,并获得tfidf和vocabularyId对,例如
47:0.104275891915 383:0.084129133023
.
.
.
.
308:0.0285015996586
199:0.0285015996586
Run Code Online (Sandbox Code Playgroud)
有什么方法可以转换为列表列表,或者可以通过其他方式更改格式以获得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
Run Code Online (Sandbox Code Playgroud)
现在将其转换为coo
格式。这已经是我可以指定的random
format参数了。在任何情况下,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)
Run Code Online (Sandbox Code Playgroud)
看起来您想忽略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}
Run Code Online (Sandbox Code Playgroud)
或二维数组中的列:
In [535]: np.column_stack((Mc.col, Mc.data))
Out[535]:
array([[ 1. , 0.28130162],
[ 6. , 0.83078036],
[ 1. , 0.2425034 ],
[ 2. , 0.19093358]])
Run Code Online (Sandbox Code Playgroud)
(也np.array((Mc.col, Mc.data)).T
)
或仅作为数组列表[Mc.col, Mc.data]
或[Mc.col.tolist(), Mc.data.tolist()]
列表列表等。
你能从那里拿走吗?