python - 从稀疏到稠密再到稀疏的转换在构造稀疏矩阵后再次降低密度
问题描述
我正在使用 scipy 生成一个稀疏的有限差分矩阵,最初从块矩阵构造它,然后编辑对角线以考虑边界条件。生成的稀疏矩阵属于 BSR 类型。我发现,如果我将矩阵转换为密集矩阵,然后使用该scipy.sparse.BSR_matrix
函数返回稀疏矩阵,我会得到一个比以前更稀疏的矩阵。这是我用来生成矩阵的代码:
size = (4,4)
xDiff = np.zeros((size[0]+1,size[0]))
ix,jx = np.indices(xDiff.shape)
xDiff[ix==jx] = 1
xDiff[ix==jx+1] = -1
yDiff = np.zeros((size[1]+1,size[1]))
iy,jy = np.indices(yDiff.shape)
yDiff[iy==jy] = 1
yDiff[iy==jy+1] = -1
Ax = sp.sparse.dia_matrix(-np.matmul(np.transpose(xDiff),xDiff))
Ay = sp.sparse.dia_matrix(-np.matmul(np.transpose(yDiff),yDiff))
lap = sp.sparse.kron(sp.sparse.eye(size[1]),Ax) + sp.sparse.kron(Ay,sp.sparse.eye(size[0]))
#set up boundary conditions
BC_diag = np.array([2]+[1]*(size[0]-2)+[2]+([1]+[0]*(size[0]-2)+[1])*(size[1]-2)+[2]+[1]*(size[0]-2)+[2])
lap += sp.sparse.diags(BC_diag)
如果我检查这个矩阵的稀疏性,我会看到以下内容:
lap
<16x16 sparse matrix of type '<class 'numpy.float64'>'
with 160 stored elements (blocksize = 4x4) in Block Sparse Row format>
但是,如果我将其转换为密集矩阵,然后再转换回相同的稀疏格式,我会看到一个更稀疏的矩阵:
sp.sparse.bsr_matrix(lap.todense())
<16x16 sparse matrix of type '<class 'numpy.float64'>'
with 64 stored elements (blocksize = 1x1) in Block Sparse Row format>
我怀疑发生这种情况的原因是因为我使用 sparse.kron 函数构造了矩阵,但我的问题是是否有一种方法可以在不先转换为密集矩阵的情况下获得较小的稀疏矩阵,例如,如果我最终想要模拟一个非常大的域。
解决方案
BSR
将数据存储在密集块中:
In [167]: lap.data.shape
Out[167]: (10, 4, 4)
在这种情况下,这些块有很多零。
In [168]: lap1 = lap.tocsr()
In [170]: lap1
Out[170]:
<16x16 sparse matrix of type '<class 'numpy.float64'>'
with 160 stored elements in Compressed Sparse Row format>
In [171]: lap1.data
Out[171]:
array([-2., 1., 0., 0., 1., 0., 0., 0., 1., -3., 1., 0., 0.,
1., 0., 0., 0., 1., -3., 1., 0., 0., 1., 0., 0., 0.,
1., -2., 0., 0., 0., 1., 1., 0., 0., 0., -3., 1., 0.,
0., 1., 0., 0., 0., 0., 1., 0., 0., 1., -4., 1., 0.,
...
0., 0., 1., -2.])
就地清理:
In [172]: lap1.eliminate_zeros()
In [173]: lap1
Out[173]:
<16x16 sparse matrix of type '<class 'numpy.float64'>'
with 64 stored elements in Compressed Sparse Row format>
如果我csr
在使用时指定格式kron
:
In [181]: lap2 = sparse.kron(np.eye(size[1]),Ax,format='csr') + sparse.kron(Ay,n
...: p.eye(size[0]), format='csr')
In [182]: lap2
Out[182]:
<16x16 sparse matrix of type '<class 'numpy.float64'>'
with 64 stored elements in Compressed Sparse Row format>
推荐阅读
- asp.net-web-api - Eventbrite APi:获取活动的门票/价格信息
- scipy - 如何编写灵活的多重指数拟合
- java - Spring boot - 从外部类路径加载文件
- java - 在 JTable 中使用自定义 TablecellRenderer
- node.js - NodeJS Express 和 Apache 在同一台服务器上
- aurelia - 直接 URL 在本地有效,但在服务器上无效
- xml - XML - XSLT - for-each 按元素位置排序
- cmake - CMake:如何向已安装的配置添加功能?
- laravel - 视频点击计数 laravel
- gcc - 为什么 gcc 不提供浮点绝对值的 AVX512F 内在函数?