1

我有一个数组 Ai 的 numpy 数组,我希望每个外部乘积 (np.outer(Ai[i],Ai[j])) 与缩放乘数相加以产生 H。我可以逐步完成并制作它们然后 tensordot它们带有比例因子矩阵。我认为事情可以大大简化,但还没有找到一种通用/有效的方法来为 ND 做到这一点。如何更容易地生成 Arr2D 和 H?注意:Arr2D 可以是 64 个二维数组,而不是 8x8 二维数组。

Ai = np.random.random((8,101))
Arr2D = np.zeros((Ai.shape[0], Ai.shape[0], Ai.shape[1], Ai.shape[1]))
Arr2D[:,:,:,:] = np.asarray([ np.outer(Ai[i], Ai[j]) for i in range(Ai.shape[0]) 
    for j in range(Ai.shape[0]) ]).reshape(Ai.shape[0],Ai.shape[0],Ai[0].size,Ai[0].size)
arr = np.random.random( (Ai.shape[0] * Ai.shape[0]) )
arr2D = arr.reshape(Ai.shape[0], Ai.shape[0])
H = np.tensordot(Arr2D, arr2D, axes=([0,1],[0,1]))
4

1 回答 1

1

良好的设置杠杆einsum

np.einsum('ij,kl,ik->jl',Ai,Ai,arr2D,optimize=True)

计时 -

In [71]: # Setup inputs
    ...: Ai = np.random.random((8,101))
    ...: arr = np.random.random( (Ai.shape[0] * Ai.shape[0]) )
    ...: arr2D = arr.reshape(Ai.shape[0], Ai.shape[0])

In [74]: %%timeit # Original soln
    ...: Arr2D = np.zeros((Ai.shape[0], Ai.shape[0], Ai.shape[1], Ai.shape[1]))
    ...: Arr2D[:,:,:,:] = np.asarray([ np.outer(Ai[i], Ai[j]) for i in range(Ai.shape[0]) 
    ...:     for j in range(Ai.shape[0]) ]).reshape(Ai.shape[0],Ai.shape[0],Ai[0].size,Ai[0].size)
    ...: H = np.tensordot(Arr2D, arr2D, axes=([0,1],[0,1]))
100 loops, best of 3: 4.5 ms per loop

In [75]: %timeit np.einsum('ij,kl,ik->jl',Ai,Ai,arr2D,optimize=True)
10000 loops, best of 3: 146 µs per loop

30x+那里加速!

于 2018-09-16T05:51:55.360 回答