繁体   English   中英

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

PS:示例取自scipy 文档

如果您提供样本矩阵会有所帮助; 你试图生产什么。

通常我们不会尝试直接指定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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM