Python scipy中的csr_matrix详解

1. 示例

1.1代码

from scipy.sparse import csr_matrix
import numpy as np
if __name__ == '__main__':
    indptr = np.array([0,2,3,6])
    indices = np.array([0,2,2,0,1,2])
    data = np.array([1,2,3,4,5,6])
    csr_matrix_0 = csr_matrix((data,indices,indptr),shape=(3,3))
    print(csr_matrix_0.toarray())

1.2输出

[[1 0 2]
[0 0 3]
[4 5 6]]

2.解释

官方的解释其实很详细,只不过需要仔细的去理解。下面是我对官方文档的理解

  • row oriented
    • three NumPy arrays: indices, indptr, data
      • indices is array of column indices.即:indices是列索引
      • data is array of corresponding nonzero values即:data是非零元素组成的数组
      • indptr:
        • indptr points to row starts in indices 即:indptr指向的是每一行中第一个非零元素在indices数组中的索引
        • indptr’s data length is n_row + 1即:indptr这个数组中一共有n_row+1行数据,n_row是稀疏矩阵的行数
        • indptr’s last item = number of values = length of both indices and data即:indptr的最后一个元素是该稀疏矩阵中非零元素的总个数,同样也就是indices和data的长度。
      • nonzero values of the i-th row are data[indptr[i]:indptr[i+1]] with column indices indices[indptr[i]:indptr[i+1]]
        • 即:这句话指明了第i行的非零元素(索引从0起)是data[indptr[i]:indptr[i+1]]。indptr[i]是第i行的第一个非零元素的在indices数组中的索引。第i行第一个非零元素在indices数组中的索引等于第i行第一个非零元素在data数组中的索引。这两个数组是同步的。
        • indptr[i+1]是第i+1行中第一个非零元素在indices数组中的索引,同理第i+1行第一个非零元素在indices数组中的索引等于第i+1行第一个非零元素在data数组中的索引。
        • 因为数组切片中是不包含后者的,所以data[indptr[i]:indptr[i+1]其实就是第i行的非零元素。同理indices[indptr[i]:indptr[i+1]其实就是第i行中所有非零元素的列索引
      • item (i, j) can be accessed as data[indptr[i]+k], where k is position of j in indices[indptr[i]:indptr[i+1]]。**item(i,j)即第i行第j列的元素。只要j在indices[indptr[i]:indptr[i+1]],就说明了item(i,j)是非零元素。indptr[i]是第i行第一个非零元素在data中的索引。那么第i行第j列自然就是data[indptr[i]+k](k是j在indices[indptr[i]:indptr[i+1]]中的索引,所以这就对应了一个相对于indptr[i]的偏移,所以data[indptr[i]+k]即为所求!

个人理解,欢迎留言交流指正!

Ref
https://www.scipy-lectures.org/advanced/scipy_sparse/csr_matrix.html

猜你喜欢

转载自blog.csdn.net/ChenglinBen/article/details/84426942