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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Chenglin_Yu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值