为什么 indptr 与此 csr 矩阵中的值不匹配?

Why does indptr not match the values in this csr matrix?

我很难理解为什么会出现这种行为。

我有一个 scipy 稀疏 csr 矩阵。前十个元素是:

print my_mat[0:10,]

  (0, 31)       1
  (0, 33)       1
  (1, 36)       1
  (1, 40)       1
  (2, 47)       1
  (2, 48)       1
  (3, 50)       1
  (3, 53)       1
  (4, 58)       1
  (4, 60)       1
  (5, 66)       1
  (5, 68)       1
  (6, 73)       1
  (6, 75)       1
  (7, 77)       1
  (7, 82)       1
  (8, 30)       1
  (8, 32)       1
  (9, 37)       1
  (9, 40)       1

当我调用 indptr 时,我得到:

m1 = my_mat[0:10,]
print m1.indptr
[ 0  2  4  6  8 10 12 14 16 18 20]

为什么 indptr 的值不相等:

0 0 1 1 2 2 3 3 等(my_mat 的第一列,即 this question 的已接受答案所暗示的内容)?我如何访问这些值?

对于 CSR 矩阵,m1.indptr 不包含行索引。相反,对于行 r,值对 start, end = m1.indptr[r:r+2] 给出存储在行 r 中的值的 m1.data 的开始和结束索引。也就是说,m1.data[start:end] 包含行 r 中的非零值。这些值的列在 m1.indices[start:end].

在您的示例中,您有 m1.indptr = [ 0 2 4 6 8 10 12 14 16 18 20]。所以第一行的非零值存储在m1.data[0:2]中,这些值所在的列存储在m1.indices[0:2]中。第二行存储的非零值是m1.data[2:4],它们的列是m1.indices[2:4],等等

如果你想要行索引和列索引,可能最简单的方法是使用nonzero()方法。例如,这是一个 CSR 矩阵:

In [50]: s
Out[50]: 
<5x8 sparse matrix of type '<class 'numpy.int64'>'
    with 4 stored elements in Compressed Sparse Row format>

In [51]: s.A
Out[51]: 
array([[ 0, 10, 40,  0,  0, 20,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0, 30,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0,  0]], dtype=int64)

这里我们使用nonzero()方法获取非零值的行索引和列索引:

In [71]: row, col = s.nonzero()

In [72]: row
Out[72]: array([0, 0, 0, 2], dtype=int32)

In [73]: col
Out[73]: array([1, 2, 5, 3], dtype=int32)

或者,您可以将数组转换为 "COO"(坐标)格式。然后你可以访问 rowcol 属性:

In [52]: c = s.tocoo()

In [53]: c.row
Out[53]: array([0, 0, 0, 2], dtype=int32)

In [54]: c.col
Out[54]: array([1, 2, 5, 3], dtype=int32)