基本原理

bsr,即Block Sparse Row,bsr_array即块稀疏行矩阵,顾名思义就是将稀疏矩阵分割成一个个非0的子块,然后对这些子块进行存储。通过输入维度,可以创建一个空的bsr数组,但bsr格式并不可见,需要通过toarray转为数组,才能一窥全貌。

from scipy.sparse import bsr_array
import numpy as np
import sys
bsr = bsr_array((100, 200), dtype=np.int8)
sys.getsizeof(bsr)      # 48
bsr_arr = bsr.toarray() # 转为数组
sys.getsizeof(bsr_arr)  # 20120

egtsizeof可查看数据占用的内存,其中bsr占用48byte,转为数组之后占据20k,这就是稀疏矩阵存在的价值。

当然,全零的数组就直接叫全零数组得了,直接存个行列数比bsr还省事儿,接下来构造一个矩阵

from numpy.random import randint, rand
tmp = np.zeros([200,200])
for i in range(30):
    x, y = randint(195, size=(2))
    tmp[x:x+5, y:y+5]=rand(5,5)

print(tmp.size)            # 40000
bsr = bsr_array(tmp, blocksize=(5,5))    
print(bsr.data.size)       # 2850
print(bsr.indptr.size)     # 41
print(bsr.indices.size)    # 114
print(tmp.size)

bsr.data是bsr中存放的矩阵块;bsr.indices为这些矩阵块对应的列号数组;bsr.indptr为索引的行分割数组;这些零零碎碎加在一起也只有3005个数,和40k的tmp相比,可以说压缩效率非常高了。

通过data, indptr和indices,可以将bsr复原为矩阵。首先,列号和数据是一一对应的;其次indptr对索引和数据按行分割。在本例中,indptr的值为0, 2, 6, 8…,则data[0:2]存放在第0行,对应的列号为indices[0:2];data[2:6]存放在第1行,对应的列号为indices[2:6],以此类推。

初始化

bsr_array共有5种初始化方案:

  • bsr_array(D) D是一个稀疏数组或2 × D 2\times D2×D数组
  • bsr_array(S) S是另一种稀疏数组
  • bsr_array((M, N),dtype) 创建一个shape为( M , N ) (M, N)(M,N)的空数组,dtype为数据类型
  • bsr_array((data, ij)) ij是坐标数组,可分解为i,j=ij,data是数据数组,设新矩阵为a,则a[i[k], j[k]] = data[k]
  • bsr_array((data, indices, indptr))

前四种方法均有参数blocksize,为块尺寸;后两种方法均有参数shape,为稀疏矩阵的维度。

从原理上来说,通过data, indices, indptr来创建的bsr数组,属于"原生"的bsr数组,其创建规则就是前文提到的复原规则。

内置方法

稀疏数组在计算上并不便捷,所以bsr_array中内置了下列函数,可以高效地完成计算。

函数 expm1, log1p, sqrt, pow, sign
三角函数 sin, tan, arcsin, arctan, deg2rad, rad2deg
双曲函数 sinh, tanh, arcsinh, arctanh
索引 getcol, getrow, nonzero, argmax, argmin, max, min
舍入 ceil, floor, trunc
变换 conj, conjugate, getH
统计 count_nonzero, getnnz, mean, sum
矩阵 diagonal, trace
获取属性 get_shape, getformat
计算比较 multiply, dot, maximum, minimum
转换 asformat, asfptype, astype, toarray, todense
转换 tobsr, tocoo, tocsc, tocsr, todia, todok, tolil
更改维度 set_shape, reshape, resize, transpose
排序 sort_indices, sorted_indices
移除元素 eliminate_zeros, prune, sum_duplicates
其他 copy, check_format, getmaxprint, rint, setdiag
原文地址:https://tinycool.blog.csdn.net/article/details/128799741

相关文章:

  • 2022-12-23
  • 2021-08-11
  • 2022-01-12
猜你喜欢
  • 2021-11-15
  • 2022-12-23
  • 2021-08-20
  • 2021-11-04
  • 2021-07-01
  • 2021-06-23
  • 2021-11-10
相关资源
相似解决方案