如何使用numpy的einsum来获取子阵列的点积?

时间:2021-12-31 21:25:13

I have an array with 3 axes:

我有一个3轴阵列:

a = [[[1,2,3], [4,5,6], [7,8,9]], 
     [[9,8,7], [6,5,4], [3,2,1]],
     [[1,1,1], [2,2,2], [3,3,3]]]

And I'd like to use einsum to non-iteratively take the dot product of each vector in 'a' with a matrix:

而且我想使用einsum非迭代地将'a'中每个向量的点积与矩阵:

m = [[a, b, c],
     [d, e, f],
     [g, h, i]]

like this

product = [[dot(m,a[1,1,:]), dot(m,a[1,2,:]), dot(m,a[1,3,:])],
           [dot(m,a[2,1,:]), dot(m,a[2,2,:]), dot(m,a[2,3,:])],
           [dot(m,a[3,1,:]), dot(m,a[3,2,:]), dot(m,a[3,3,:])]]

to get an array with the same shape as the initial array 'a'. I've been trying to use einsum, but I just can't get it to work.

获得一个与初始数组'a'形状相同的数组。我一直在尝试使用einsum,但我无法让它工作。

1 个解决方案

#1


This should do the trick, assuming you are 'dotting' the last dimension of m with the last of a:

这应该可以解决这个问题,假设你用m的最后一个维度“点击”m的最后一个维度:

np.einsum('ij,klj->ikl',m,a)

#1


This should do the trick, assuming you are 'dotting' the last dimension of m with the last of a:

这应该可以解决这个问题,假设你用m的最后一个维度“点击”m的最后一个维度:

np.einsum('ij,klj->ikl',m,a)