Skip to main content
 首页 » 编程设计

python之如何有效地对 numpy 中的每个 block 矩阵 block 应用相同的操作

2025年02月15日9oomusou

我有一个大的二维数组,形状如下:

B = [B_0, B_1, B_2, B_n] 

其中B_0, B_1, ..., B_n行数相同,但列数不同,n可能很大。我还有另一个一维数组 idx ,形状为 (n+1,) 和

B_i = B[:, idx[i]:idx[i+1]] 

和idx[-1](idx的最后一个元素)是B的总列数。

我想对每个 B_i 做相同的矩阵运算,例如:

B_i.T()@B_i 

或者用另一个二维数组:

D = [[D_0], [D_1], ..., [D_n]] 

D_0, D_1, ..., D_n 的列数与 B 的行数相同,但行数不同, 和

D_i = D[idx[i]:idx[i+1], :] 

我想计算D_i@B_i。

所以我的问题是如何在 python 中实现它并避免使用 for 循环?

下面是一个例子:

import numpy as np 
from timeit import default_timer as timer 
# Prepare the test data 
n = 1000000 # the number of small matrix  
 
idx = np.zeros(n+1, dtype=np.int) 
idx[1:] = np.random.randint(1, 10, size=n) 
idx = np.cumsum(idx) 
 
B = np.random.rand(3, idx[-1]) 
 
# Computation 
start = timer() 
C = [] 
for i in range(n): 
    B_i = B[:, idx[i]:idx[i+1]] 
    C_i = B_i.T@B_i 
    C.append(C_i) 
end = timer() 
print('Total time:', end - start) 

请您参考如下方法:

如果我添加到您的代码中:

print(B.shape) 
print(idx) 
print([x.shape for x in C]) 
 
Bnn = np.zeros((n, 3, idx[-1])) 
for i in range(n): 
    s = np.s_[idx[i]:idx[i+1]] 
    Bnn[i,:,s] = B[:, s] 
Bnn = Bnn.reshape(3*n,-1) 
Cnn = Bnn.T @ Bnn 
print(Bnn.shape, Cnn.shape) 
print(Cnn.sum(), sum([x.sum() for x in C])) 

并更改n=5,我得到了

2115:~/mypy$ python3 stack46209231.py  
(3, 31)    # B shape 
[ 0  9 17 18 25 31] 
[(9, 9), (8, 8), (1, 1), (7, 7), (6, 6)]  # shapes of C elements 
(15, 31) (31, 31)     # shapes of diagonalized B and C 
197.407879357 197.407879357   # C sums from the 2 routes 

所以我的想法是制作 B 的对角化版本,并用它执行点积。对于应该更快的适度大小的数组,尽管创建 Bnn 的迭代将需要时间,从 Cnn 中提取 block 也是如此。

但是 Bnn 和 Cnn 会变得非常大,并陷入内存交换的泥潭,最终会出现内存错误。


使用 block_diag 函数,将您的 B 转换为稀疏矩阵非常容易:

from scipy import sparse 
 
Blist = [B[:, idx[i]:idx[i+1]] for i in range(n)] 
Bs = sparse.block_diag(Blist, format='bsr') 
print(repr(Bs)) 
Cs = Bs.T@Bs 
print(repr(Cs)) 
print(Cs.sum()) 

和 sample 运行

2158:~/mypy$ python3 stack46209231.py  
(3, 20) 
[ 0  1  5  9 17 20] 
[(1, 1), (4, 4), (4, 4), (8, 8), (3, 3)] 
(15, 20) (20, 20) 
94.4190125992 94.4190125992 
<15x20 sparse matrix of type '<class 'numpy.float64'>' 
    with 60 stored elements (blocksize = 1x1) in Block Sparse Row format> 
<20x20 sparse matrix of type '<class 'numpy.float64'>' 
    with 106 stored elements (blocksize = 1x1) in Block Sparse Row format> 

并且形状和校验和匹配。

对于 n = 10000,Bnn 对我的内存来说太大了。稀疏 Bs 创建速度慢,但矩阵乘法速度快。