scipy.sparse.csr_matrix 中的 indptr & indices & data

在这里插入图片描述

# -------------------------------------------------------------------------------
# Description:  分析理解 scipy.sparse.csr_matrix 中的 indptr & indices & data
# Reference:  https://blog.csdn.net/bymaymay/article/details/81389722
# Author:   Sophia
# Date:   2021/3/28
# -------------------------------------------------------------------------------
import numpy as np
from scipy.sparse import csr_matrix
 
# print(csr_matrix((3, 4), dtype=np.int8).toarray())  # 构建3*4的空矩阵
# [[0 0 0 0]
#  [0 0 0 0]
#  [0 0 0 0]]
 
row = np.array([0, 0, 1, 2, 2, 2])
col = np.array([0, 2, 2, 0, 1, 2])
data = np.array([1, 2, 3, 4, 5, 6])
# print(csr_matrix((data, (row, col)), shape=(3, 3)).toarray())  # 构建稀疏矩阵,满足 a[row[k], col[k]] = data[k]
# [[1 0 2]
#  [0 0 3]
#  [4 5 6]]
 
indptr = np.array([0, 2, 5, 7])
indices = np.array([1, 3, 0, 1, 3, 0, 2])
data = np.array([1, 2, 1, 1, 2, 2, 5])
print(csr_matrix((data, indices, indptr)).toarray())
 
# output:
# [[0 1 0 2]
#  [1 1 0 2]
#  [2 0 5 0]]
 
print(csr_matrix((data, indices, indptr), shape=(3, 6)).toarray())
 
# output:
# [[0 1 0 2 0 0]
#  [1 1 0 2 0 0]
#  [2 0 5 0 0 0]]
 
arr = np.array([[0, 1, 0, 2, 0], [1, 1, 0, 2, 0], [2, 0, 5, 0, 0]])
b = csr_matrix(arr)
print(b.shape)  # (3, 5)
print(b.nnz)  # 非零个数, 7
print(b.data)  # 非零值, [1 2 1 1 2 2 5]
print(b.indices)  # #稀疏矩阵非0元素对应的列索引值所组成数组, [1 3 0 1 3 0 2]
print(b.indptr)  # 第一个元素0,之后每个元素表示稀疏矩阵中每行元素(非零元素)个数累计结果, [0 2 5 7]
print(b.toarray())  # [[0,1,0,2,0],[1,1,0,2,0],[2,0,5,0,0]]
print(b)
# (0, 1)
# 1
# (0, 3)
# 2
# (1, 0)
# 1
# (1, 1)
# 1
# (1, 3)
# 2
# (2, 0)
# 2
# (2, 2)
# 5

See https://blog.csdn.net/m0_37738114/article/details/115279877

根据indptr计算行索引

def Compute_Row_Index(indptr):
    row=len(indptr)-1
    l=indptr[1]-indptr[0]
    z=np.zeros(l)
    a=list(z)#行索引
    for i in range(1,row):
        l=indptr[i+1]-indptr[i]
        z=np.ones(l)
        a=a+list(z*i)
    a=np.array(a,dtype=np.int64)
    return a

计算速度有待解决

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值