将numpy数组从一个(二维)复制到另一个(三维)



我试图复制一个数组,说A(2-D)到另一个数组中,说B(3-D),它们具有以下形状

A是m*n阵列,B是m*n*p阵列

我尝试了以下代码,但速度很慢,比如1秒/帧

for r in range (0, h):
    for c in range (0, w):
        x = random.randint(0, 20)
        B[r, c, x] = A[r, c]

我也读过一些关于花式索引的网站,但我仍然不知道如何在我的网站上应用它。

我提出了一个使用数组索引的解决方案。MNP分别是(m,n)索引数组,指定将从A接收数据的B的m*n个元素。

def indexing(A, p):
    m,n = A.shape
    B = np.zeros((m,n,p), dtype=int)
    P = np.random.randint(0, p, (m,n))
    M, N = np.indices(A.shape)
    B[M,N,P] = A
    return B

为了进行比较,原始循环和使用混洗的解决方案

def looping(A, p):
    m, n = A.shape
    B = np.zeros((m,n,p), dtype=int)
    for r in range (m):
        for c in range (n):
            x = np.random.randint(0, p)
            B[r, c, x] = A[r, c]
    return B
def shuffling(A, p):
    m, n = A.shape
    B = np.zeros((m,n,p), dtype=int)
    B[:,:,0] = A
    map(np.random.shuffle, B.reshape(m*n,p))
    return B

对于m,n,p=10001000,20,时间为:

looping:    1.16 s
shuffling: 10 s
indexing:     271 ms

对于小m,n,循环是最快的。我的索引解决方案需要更多的时间来设置,但实际分配很快。混洗解决方案的迭代次数与原来的一样多。


MN阵列不必是满的。它们可以分别是列和行阵列

M = np.arange(m)[:,None]
N = np.arange(n)[None,:]

M,N = np.ogrid[:m,:n]

这节省了一些时间,对于小型测试用例比大型测试用例更是如此。


可重复版本:

def indexing(A, p, B=None):
    m, n = A.shape
    if B is None:
        B = np.zeros((m,n,p), dtype=int)
    for r in range (m):
        for c in range (n):
            x = np.random.randint(0, p)
            B[r, c, x] = A[r, c]
    return B
indexing(A,p,indexing(A,p))

如果AB的第1个2 dim大小不同,则必须更改索引范围。A也不一定是2D阵列:

B[[0,0,2],[1,1,0],[3,4,5]] = [10,11,12]

假设h=m,w=n和x=p,这应该会得到与示例中相同的结果:

B[:,:,0]=A
map(np.random.shuffle, B.reshape(h*w,p))  

另外请注意,我假设NPE在评论中的问题的答案是"是"

最新更新