Numpy Multidimensional (3d) Matrix Multiplication

I get two 3d matrices A (32x3x3) and B (32x3x3), and I want to get a C matrix with a size of 32x3x3. The calculation can be performed using a loop, for example:

a = numpy.random.rand(32, 3, 3)
b = numpy.random.rand(32, 3, 3)
c = numpy.random.rand(32, 3, 3)

for i in range(32):
    c[i] = numpy.dot(a[i], b[i])

I believe that to solve this problem there should be a more effective single-line solution. Can someone help, thanks.

+4
source share
1 answer

You can do this using np.einsum:

In [142]: old = orig(a,b)

In [143]: new = np.einsum('ijk,ikl->ijl', a, b)

In [144]: np.allclose(old, new)
Out[144]: True

einsum , , : (i) (jk,kl->jl)).

+3

Source: https://habr.com/ru/post/1656535/


All Articles