我试图理解 scipy 中的稀疏矩阵,尤其是 csr_matrix 格式
假设我有以下文本
docs = ['hello world hello', 'goodbye cruel world']
我对它们进行标记,并获取包含标记出现次数的字典列表和包含 token_ids 的字典。
ids_token = {0: 'world', 1: 'hello', 2: 'cruel', 3: 'goodbye'}
token_counts = [{0: 1, 1: 2}, {0: 1, 2: 1, 3: 1}]
如何转换 csr_matrix 中的 token_counts ?
这是我迄今为止尝试过的:
data = [item for sublist in token_counts for item in sublist.values()]
print 'data:', data
indices = [item for sublist in token_counts for item in sublist.keys()]
print 'indices:', indices
indptr = [0] + [len(item) for item in token_counts]
print 'pointers:', indptr
#now I create the matrix
sp_matrix = csr_matrix((data, indices, indptr), dtype=int)
print sp_matrix.toarray()
import pandas as pd
pd.DataFrame(sp_matrix.toarray().transpose(), index = ids_token.values())
结果不是预期的,最后几行为零。
我怀疑问题出在指针 indptr 上,我错过了什么?
感谢任何帮助
已更新 这就是我想要得到的
doc0 doc11
cruel 0 1
goodbye 0 1
hello 2 0
world 1 1
P.S:示例取自scipy documentation
最佳答案
如果您提供样本矩阵将会有所帮助;您想要生产什么。
通常我们不会尝试直接指定 csr
值。 indptr 值尤其有点晦涩难懂。 coo
风格的输入通常更好,(Data_array, (i_array, j_array))
,其中 M[i,j] = data
。 sparse
会自动将其转换为 csr
格式。
dok
格式也很方便。矩阵被存储为字典,元组 (i,j)
是键。
In [151]: data = [item for sublist in token_counts for item in sublist.values()]
In [152]: rows = [item for sublist in token_counts for item in sublist.keys()]
In [153]: cols = [i for i,sublist in enumerate(token_counts) for item in sublist.keys()]
In [155]: M=sparse.csr_matrix((data,(rows,cols)))
In [156]: M
Out[156]:
<4x2 sparse matrix of type '<class 'numpy.int32'>'
with 5 stored elements in Compressed Sparse Row format>
In [157]: M.A
Out[157]:
array([[1, 1],
[2, 0],
[0, 1],
[0, 1]], dtype=int32)
查看 M
的属性,了解如何使用 indptr
格式构造它:
In [158]: M.data
Out[158]: array([1, 1, 2, 1, 1], dtype=int32)
In [159]: M.indices
Out[159]: array([0, 1, 0, 1, 1], dtype=int32)
In [160]: M.indptr
Out[160]: array([0, 2, 3, 4, 5], dtype=int32)
稀疏矩阵的 str
显示枚举非零元素(dok 格式内部看起来像这样)。
In [161]: print(M)
(0, 0) 1
(0, 1) 1
(1, 0) 2
(2, 1) 1
(3, 1) 1
关于python - python scipy中稀疏矩阵中的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33356343/