tensor product and einsum in numpy

4.8k Views Asked by At

I am trying to understand the einsum function in NumPy. In this documentation, the last example,

>>> a = np.arange(60.).reshape(3,4,5)
>>> b = np.arange(24.).reshape(4,3,2)
>>> np.einsum('ijk,jil->kl', a, b)
array([[ 4400.,  4730.],
       [ 4532.,  4874.],
       [ 4664.,  5018.],
       [ 4796.,  5162.],
       [ 4928.,  5306.]])
>>> np.einsum(a, [0,1,2], b, [1,0,3], [2,3])
array([[ 4400.,  4730.],
       [ 4532.,  4874.],
       [ 4664.,  5018.],
       [ 4796.,  5162.],
       [ 4928.,  5306.]])
>>> np.tensordot(a,b, axes=([1,0],[0,1]))
array([[ 4400.,  4730.],
       [ 4532.,  4874.],
       [ 4664.,  5018.],
       [ 4796.,  5162.],
       [ 4928.,  5306.]])

I don't understand what's going on with this np.einsum('ijk,jil->kl', a, b) function. Can someone express it in a more explicit way, something like $$\sum_{???}a_{ijk}b_{ijk}$$? I'm not familiar with tensor product so that also contributes to my struggle here.

I'm learning this to solve this problem of mine.

1

There are 1 best solutions below

3
On

The result is a new array c, with $$ c_{kl} = \sum_{i,j} a_{ijk} b_{jil} . $$