【问题标题】:pointers in sparse matrix in python scipypython scipy中稀疏矩阵中的指针
【发布时间】:2016-01-26 04:15:57
【问题描述】:

我正在尝试理解 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

【问题讨论】:

    标签: python scipy sparse-matrix


    【解决方案1】:

    如果你提供一个样本矩阵会有所帮助;你想生产什么。

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

    【讨论】:

    • 刚刚在维基百科上看到应该使用另一种格式来构建 csr。谢谢指出
    • @user1043144 感谢您提及维基百科。 Sparse matrix 页面确实清晰而彻底地解释了 indptr 在压缩稀疏行 (CSR) 又名压缩行存储 (CRS) 又名耶鲁格式中使用的复杂方式。关于这些东西的 scipy 文档确实令人失望,但我一直假设他们正在定义特定于他们的实现的东西。
    • 通常我们不会直接操作indptr。将其用于乘法等的csr 代码已编译,不适合直接使用。甚至像行求和或索引这样的任务也是通过矩阵乘法执行的。但是有关于直接访问 CSR 行的问题。搜索[scipy] indptr
    猜你喜欢
    • 2023-04-10
    • 1970-01-01
    • 2015-05-08
    • 1970-01-01
    • 2012-05-23
    • 2014-10-11
    • 2017-03-26
    • 2017-03-31
    • 2017-07-21
    相关资源
    最近更新 更多