Skip to main content
 首页 » 编程设计

python之python scipy中稀疏矩阵中的指针

2024年10月24日12pengyingh

我试图理解 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