Block Sparse Row matrix(BSR)
作者:互联网
Block Sparse Row matrix(BSR)
Block Sparse Row matrix(BSR), 块稀疏行矩阵是Scipy科学计算库中的一类稀疏矩阵
官方文档对BSR格式的总结
The Block Compressed Row (BSR) format is very similar to the Compressed Sparse Row (CSR) format. BSR is appropriate for sparse matrices with dense sub matrices like the last example below. Block matrices often arise in vector-valued finite element discretizations. In such cases, BSR is considerably more efficient than CSR and CSC for many sparse arithmetic operations.
块压缩行(BSR)格式与压缩稀疏行(CSR)格式非常相似。 BSR适用于具有密集子矩阵的稀疏矩阵,如下面的最后一个示例。向量值有限元离散化中经常会出现块矩阵。在这种情况下,对于许多稀疏算术运算,BSR比CSR和CSC效率要高得多。
使用方式
- 将密集矩阵或者2维数组变为块稀疏行矩阵类型
import numpy as np
from scipy.spares import bsr_matrix
rng = np.random.default_rng()
x = rng.integers(low=3, high=5, size=(4, 4))
print(x)
# 将密集矩阵变为稀疏矩阵类型
bsr_mat = bsr_matrix(x)
print(type(bsr_mat))
'''
output:
[[4 3 3 4]
[3 3 4 3]
[3 4 4 4]
[3 3 4 3]]
<class 'scipy.sparse.bsr.bsr_matrix'>
'''
- 将其他类型的稀疏矩阵转变为块稀疏行矩阵。
from scipy.sparse import bsr_matrix
from scipy.sparse import csr_matrix
# 创建一个3行4列的空压缩稀疏行矩阵
csr_mat = csr_matrix((3, 4), dtype=np.int8)
# 变为密集矩阵类型输出
print(csr_mat.todense())
print(type(csr_mat))
# 将密集矩阵变为稀疏矩阵类型
bsr_mat = bsr_matrix(csr_mat)
print(type(bsr_mat))
# 等价为csr_mat.tobsr()
print(type(csr_mat.tobsr()))
'''
output:
[[0 0 0 0]
[0 0 0 0]
[0 0 0 0]]
<class 'scipy.sparse.csr.csr_matrix'>
<class 'scipy.sparse.bsr.bsr_matrix'>
<class 'scipy.sparse.bsr.bsr_matrix'>
'''
- 构造一个空的BSR, 形状为元组shape=(M, N), 值类型为dtype, 默认为’d’, 双精度浮点数。
from scipy.sparse import bsr_matrix
(M, N) = (3, 4)
bsr_mat = bsr_matrix((M, N), dtype='d')
print(bsr_mat.todense())
'''
output:
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
'''
- 构造一个BSR, (i,j)分别为对应非空值的行坐标和列坐标。data为i行j列的值。
import numpy as np
from scipy.sparse import bsr_matrix
row = rng.integers(3, size=6)
print(f'row:{row}')
col = np.array([1 if i % 2 == 0 else 0 for i in row])
print(f'col:{col}')
data = rng.integers(10, size=6)
print(f'data:{data}')
bsr_mat = bsr_matrix((data, (row, col)), shape=(3, 3))
print(bsr_mat.todense())
'''
output
row:[2 1 0 0 1 0]
col:[1 0 1 1 0 1]
data:[2 9 0 6 4 0]
[[ 0 6 0]
[13 0 0]
[ 0 2 0]]
'''
- 标准的块稀疏行矩阵。indptr为indices和data列表的索引指针。indices为生成矩阵的每块所在的列, data为生成矩阵对应块的值。
import numpy as np
from scipy.sparse import bsr_matrix
indptr = np.array([0, 1, 2])
'''
indices[indptr[i]:indptr[i+1]]
data[indptr[i]:indptr[i+1]]
'''
indices = np.array([0, 1])
data = np.array([2, 3, 3, 4]).repeat(2).reshape((2, 2, 2))
bsr_mat = bsr_matrix((data, indices, indptr), shape=(4, 4)).toarray()
print(bsr_mat)
'''
output:
[[2 2 0 0]
[3 3 0 0]
[0 0 3 3]
[0 0 4 4]]
'''
标签:matrix,矩阵,bsr,BSR,Sparse,print,mat 来源: https://blog.csdn.net/kounid/article/details/114825564