分析理解 scipy.sparse.csr_matrix 中的 indptr & indices & data

indptr = [0 2 5 7]

稀疏矩阵的行数:row = len(indptr) - 1 = 4 - 1 = 3

第0行非零元素个数:2 - 0 = 2;位置分别在index = 1,3;数值分别为1,2

第1行非零元素个数:5 - 2 = 3;位置分别在index = 0,1,3;数值分别为1,1,2

第2行非零元素个数:7 - 5 = 2;位置分别在index = 0,2;数值分别为2,5

indices = [1 3 0 1 3 0 2]

稀疏矩阵的默认列数:col = max(indices) + 1 = 3 + 1 = 4

data = [1 2 1 1 2 2 5]

生成的稀疏矩阵为:

[[0 1 0 2]
 [1 1 0 2]
 [2 0 5 0]]

若要指定稀疏矩阵的大小,row必须为3,col >= 4,多出的位置补0

如3*6:

[[0 1 0 2 0 0]
 [1 1 0 2 0 0]
 [2 0 5 0 0 0]]

# -------------------------------------------------------------------------------
# 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

 

你可能感兴趣的:(Python精修,scipy.sparse,csr_matrix,indptr,indices,data)