iNi*_*kkz 6 python numpy scipy sparse-matrix scikit-learn
我想读一个稀疏矩阵.当我使用scikit学习构建ngrams时.它的transform()在稀疏矩阵中给出输出.我想在不执行todense()的情况下读取该矩阵.
码:
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
document = ['john guy','nice guy']
vectorizer = CountVectorizer(ngram_range=(1, 2))
X = vectorizer.fit_transform(document)
transformer = vectorizer.transform(document)
print transformer
Run Code Online (Sandbox Code Playgroud)
输出:
(0, 0) 1
(0, 1) 1
(0, 2) 1
(1, 0) 1
(1, 3) 1
(1, 4) 1
Run Code Online (Sandbox Code Playgroud)
如何读取此输出以获取其值.我需要在(0,0),(0,1)等处的值并保存到列表中.
hpa*_*ulj 11
此transform
方法的文档说它返回稀疏矩阵,但未指定类型.不同的类型允许您以不同的方式访问数据,但很容易将数据转换为另一种.您的打印显示是str
稀疏矩阵的典型值.
可以生成等效矩阵:
from scipy import sparse
i=[0,0,0,1,1,1]
j=[0,1,2,0,3,4]
A=sparse.csr_matrix((np.ones_like(j),(i,j)))
print(A)
Run Code Online (Sandbox Code Playgroud)
生产:
(0, 0) 1
(0, 1) 1
(0, 2) 1
(1, 0) 1
(1, 3) 1
(1, 4) 1
Run Code Online (Sandbox Code Playgroud)
甲csr
类型可以被索引等的致密的基质:
In [32]: A[0,0]
Out[32]: 1
In [33]: A[0,3]
Out[33]: 0
Run Code Online (Sandbox Code Playgroud)
在内部,该csr
矩阵将其数据存储在data
,indices
,indptr
,可方便地进行计算,但有点模糊.将其转换为coo
格式以获取看起来像您输入的数据:
In [34]: A.tocoo().row
Out[34]: array([0, 0, 0, 1, 1, 1], dtype=int32)
In [35]: A.tocoo().col
Out[35]: array([0, 1, 2, 0, 3, 4], dtype=int32)
Run Code Online (Sandbox Code Playgroud)
或者您可以将其转换为dok
类型,并像字典一样访问该数据:
A.todok().keys()
# dict_keys([(0, 1), (0, 0), (1, 3), (1, 0), (0, 2), (1, 4)])
A.todok().items()
Run Code Online (Sandbox Code Playgroud)
产生:(这里是Python3)
dict_items([((0, 1), 1),
((0, 0), 1),
((1, 3), 1),
((1, 0), 1),
((0, 2), 1),
((1, 4), 1)])
Run Code Online (Sandbox Code Playgroud)
的lil
格式存储的数据作为2所列出清单,一个与数据(在本例中为1),而另一个与所述行索引.
或者你是以其他方式"读取"数据的?
归档时间: |
|
查看次数: |
16032 次 |
最近记录: |