# -------------------------------------------------------------------------------
# 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
计算速度有待解决