0

For example,

A = np.arange(24).reshape((2, 3, 4))
print np.einsum('ijk', A)

this is still A with no problem.

But if I do print np.einsum('kij', A) the shape is (3, 4, 2). Shouldn't it be (4, 2, 3)?

The result of print np.einsum('cab', A) shape is (4, 2, 3) with no problem too. Why is print np.einsum('kij', A) not the same?

Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214
Crazymage
  • 114
  • 9

1 Answers1

2

If you specify only a single set of subscripts, these are interpreted as the order of dimensions in the input array with respect to the output, not vice versa.

For example:

import numpy as np

A = np.arange(24).reshape((2, 3, 4))
B = np.einsum('kij', A)

i, j, k = np.indices(B.shape)

print(np.all(B[i, j, k] == A[k, i, j]))
# True

As @hpaulj pointed out in the comments, you can make the correspondence between the input and output dimensions more explicit by specifying both sets of subscripts:

# this is equivalent to np.einsum('kij', A)
print(np.einsum('kij->ijk', A).shape)
# (3, 4, 2)

# this is the behavior you are expecting
print(np.einsum('ijk->kij', A).shape)
# (4, 2, 3)
ali_m
  • 71,714
  • 23
  • 223
  • 298
  • imean when i use 'cab' the result shape is 4,2,3 but when i use 'kij' the result shape is 3,4,2 ,i think both of them should be ,2,3 – Crazymage Oct 20 '15 at 11:25
  • I can't replicate the behaviour you're describing using either numpy v1.9.2, v1.8.2 or v1.6.0. I always get an output shape of `(3, 4, 2)` for both `np.einsum('kij', A)` and `np.einsum('cab', A)`. – ali_m Oct 20 '15 at 15:33
  • Oh, I know now that what I want to do with 'kij' should be done using 'ijk->kij', but I still don't understand what 'kij' do why the result is (3,4,2).. – Crazymage Oct 20 '15 at 23:49
  • Suppose you labelled the dimensions of array `B` with the letters *i,j,k*. The positions of the letters in *k,i,j* then specifies the order in which you have to select the dimensions from array `A` in order to make array `B`. The first letter *i* is in the second position, so first dimension in `B` is the second dimension in `A` (3). The second letter *j* is in the third position, so the second dimension in `B` is the third dimension in `A` (4). The third letter *k* is in the first position, so the final dimension of `B` is the first dimension of `A` (2). Is that clearer? – ali_m Oct 21 '15 at 00:30