首页 > 解决方案 > 从稀疏到稠密再到稀疏的转换在构造稀疏矩阵后再次降低密度

问题描述

我正在使用 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 函数构造了矩阵,但我的问题是是否有一种方法可以在不先转换为密集矩阵的情况下获得较小的稀疏矩阵,例如,如果我最终想要模拟一个非常大的域。

标签: pythonmatrixscipysparse-matrix

解决方案


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>

推荐阅读