如何从较大的稀疏矩阵中有效地生成新矩阵

2024-06-16 14:56:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个大的稀疏对称矩阵,我需要通过取块和来压缩它,从而得到一个新的更小的矩阵。在

例如,对于一个4x4稀疏矩阵a,我想制作一个2x2矩阵B,其中B[I,j]=和(a[I:I+2,j:j+2])。在

目前,我只是逐块重建压缩矩阵,但这很慢。关于如何优化这一点有什么想法吗?在

更新:下面是一个示例代码,它运行良好,但对于50.000x50.000的稀疏矩阵,我想将其压缩为10.000x10.000:

>>> A = (rand(4,4)<0.3)*rand(4,4)
>>> A = scipy.sparse.lil_matrix(A + A.T) # make the matrix symmetric

>>> B = scipy.sparse.lil_matrix((2,2))
>>> for i in range(B.shape[0]):
...     for j in range(B.shape[0]):
...         B[i,j] = A[i:i+2,j:j+2].sum()

Tags: the代码in示例formakerange矩阵
3条回答

对于4x4示例,可以执行以下操作:

In [43]: a = np.arange(16.).reshape((4, 4))
In [44]: a 
Out[44]: 
array([[  0.,   1.,   2.,   3.],
       [  4.,   5.,   6.,   7.],
       [  8.,   9.,  10.,  11.],
       [ 12.,  13.,  14.,  15.]])
In [45]: u = np.array([a[:2, :2], a[:2, 2:], a[2:,:2], a[2:, 2:]])
In [46]: u
Out[46]: 
array([[[  0.,   1.],
        [  4.,   5.]],

       [[  2.,   3.],
        [  6.,   7.]],

       [[  8.,   9.],
        [ 12.,  13.]],

       [[ 10.,  11.],
        [ 14.,  15.]]])

In [47]: u.sum(1).sum(1).reshape(2, 2)
Out[47]: 
array([[ 10.,  18.],
       [ 42.,  50.]])

使用类似于itertools的东西,应该可以自动化并通用u的表达式。在

给定一个大小为N的正方形矩阵和一个拆分大小为d的矩阵(因此矩阵将被划分为N/d*N/d的子矩阵),你能用几次numpy.split来建立这些子矩阵的集合,并将它们相加,然后将它们放在一起吗?在

这应该被视为伪代码而不是有效的实现,但它表达了我的想法:

    def chunk(matrix, size):
        row_wise = []
        for hchunk in np.split(matrix, size):
            row_wise.append(np.split(hchunk, size, 1))
        return row_wise

    def sum_chunks(chunks):
        sum_rows = []
        for row in chunks:
            sum_rows.append([np.sum(col) for col in row])
        return np.array(sum_rows)

或者更紧凑的

^{pr2}$

这样可以得到如下结果:

    In [16]: a
    Out[16]: 
    array([[ 0,  1,  2,  3],
           [ 4,  5,  6,  7],
           [ 8,  9, 10, 11],
           [12, 13, 14, 15]])

    In [17]: chunk.sum_in_place(a, 2)
    Out[17]: 
    array([[10, 18],
           [42, 50]])

首先,lil你总结的矩阵可能真的很糟糕,我会尝试COO或者{}(我不知道哪个更好,但是{}对于这些操作中的许多来说可能天生就比较慢,即使切片也可能慢得多,尽管我没有测试)。(除非您知道例如dia非常适合)

基于COO我可以想象做一些欺骗。由于COOrow和{}数组来给出确切的位置:

matrix = A.tocoo()

new_row = matrix.row // 5
new_col = matrix.col // 5
bin = (matrix.shape[0] // 5) * new_col + new_row
# Now do a little dance because this is sparse,
# and most of the possible bin should not be in new_row/new_col
# also need to group the bins:
unique, bin = np.unique(bin, return_inverse=True)
sum = np.bincount(bin, weights=matrix.data)
new_col = unique // (matrix.shape[0] // 5)
new_row = unique - new_col * (matrix.shape[0] // 5)

result = scipy.sparse.coo_matrix((sum, (new_row, new_col)))

(我不能保证我没有混淆行和列,这只适用于方阵…)

相关问题 更多 >