将点积应用于 3D 数组中的所有列

Apply dot product to all columns in a 3D array

我有一个 3D 数组,需要在一个方向上进行变换。我有一个矩阵 map_y,其中包含我使用 np.dot 应用的一个方向的变换。是否可以避免下面代码中的嵌套 for 循环?

import numpy as np

nx, ny, nz = 64, 32, 24
nyc = 11

a = np.random.rand(nz, ny, nx)

ac = np.empty((nz, nyc, nx))

map_y = np.random.rand(nyc, ny)

# Can we do this in a single numpy function?
for k in range(nz):
    for i in range(nx):
        ac[k,:,i] = np.dot(map_y, a[k,:,i])

使用np.einsum-

ac = np.einsum('ijk,lj->ilk',a,map_y)

关于问题的一点einsum解释:

轴可以被认为是示意性的,就像这样 -

a      : i      x j x k
map_y  :     l  x j
output : i x l      x k

因此,j 是对齐的,并且还对输出进行了总和缩减,而其余的是 "speard-out",给了我们想要的输出。

有关详细信息,请参阅链接文档。

此外,通过将 np.einsum 中的 optimize 标志设置为 True 来使用 BLAS。