二维数组的块状Einsum外部总和

时间:2018-09-13 20:00:36

标签: python numpy numpy-einsum

我尝试搜索答案,但是找不到我需要的东西。抱歉,如果这是一个重复的问题。

假设我有一个二维数组,形状为(n, n*m)。我想做的是此数组对其转置的外部求和,从而得到形状为(n*m, n*m)的数组。例如,假设我有

A = array([[1., 1., 2., 2.],
           [1., 1., 2., 2.]])

我想做一个AA.T的和,这样输出是:

>>> array([[2., 2., 3., 3.],
           [2., 2., 3., 3.],
           [3., 3., 4., 4.],
           [3., 3., 4., 4.]])

请注意,np.add.outer无效,因为它会将输入中的向量散列为向量。我可以通过

获得类似的效果
np.tile(A, (2, 1)) + np.tile(A.T, (1, 2))

,但是当nm相当大(n > 100m > 1000)时,这似乎并不合理。是否可以使用einsum来写这个总和?我似乎无法弄清einsum

2 个答案:

答案 0 :(得分:2)

要利用broadcasting,我们需要将其分解为3D,然后置换轴并添加-

n = A.shape[0]
m = A.shape[1]//n
a = A.reshape(n,m,n) # reshape to 3D
out = (a[None,:,:,:] + a.transpose(1,2,0)[:,:,None,:]).reshape(n*m,-1)

运行示例以进行验证-

In [359]: # Setup input array
     ...: np.random.seed(0)
     ...: n,m = 3,4
     ...: A = np.random.randint(1,10,(n,n*m))

In [360]: # Original soln
     ...: out0 = np.tile(A, (m, 1)) + np.tile(A.T, (1, m))

In [361]: # Posted soln
     ...: n = A.shape[0]
     ...: m = A.shape[1]//n
     ...: a = A.reshape(n,m,n)
     ...: out = (a[None,:,:,:] + a.transpose(1,2,0)[:,:,None,:]).reshape(n*m,-1)

In [362]: np.allclose(out0, out)
Out[362]: True

nm-大的计时-

In [363]: # Setup input array
     ...: np.random.seed(0)
     ...: n,m = 100,100
     ...: A = np.random.randint(1,10,(n,n*m))

In [364]: %timeit np.tile(A, (m, 1)) + np.tile(A.T, (1, m))
1 loop, best of 3: 407 ms per loop

In [365]: %%timeit
     ...: # Posted soln
     ...: n = A.shape[0]
     ...: m = A.shape[1]//n
     ...: a = A.reshape(n,m,n)
     ...: out = (a[None,:,:,:] + a.transpose(1,2,0)[:,:,None,:]).reshape(n*m,-1)
1 loop, best of 3: 219 ms per loop

numexpr

进一步提高了性能

我们可以利用multi-core with numexpr module处理大数据并获得内存效率和性能-

import numexpr as ne

n = A.shape[0]
m = A.shape[1]//n
a = A.reshape(n,m,n)
p1 = a[None,:,:,:]
p2 = a.transpose(1,2,0)[:,:,None,:]
out = ne.evaluate('p1+p2').reshape(n*m,-1)

具有相同的nm大型设置的计时-

In [367]: %%timeit
     ...: # Posted soln
     ...: n = A.shape[0]
     ...: m = A.shape[1]//n
     ...: a = A.reshape(n,m,n)
     ...: p1 = a[None,:,:,:]
     ...: p2 = a.transpose(1,2,0)[:,:,None,:]
     ...: out = ne.evaluate('p1+p2').reshape(n*m,-1)
10 loops, best of 3: 152 ms per loop

答案 1 :(得分:0)

一种方法是

(A.reshape(-1,*A.shape).T+A)[:,0,:]

我认为n>100m>1000会占用大量内存。

但与

不同
np.add.outer(A,A)[:,0,:].reshape(4,-1)