python scipy 中稀疏矩阵中的指针

pointers in sparse matrix in python scipy

我正在尝试理解 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] = datasparse 自动将其转换为 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