0

I trying to modify the following code snippet to not use reshape

a = np.random.randn(1, 2, 3, 5)
b = np.random.randn(2, 5, 10)

np.einsum("ijkl,mjl->kim", a, b.reshape(10,2,5))

At first I thought that the reshape is just transposing the operand, but it seems more complicated than that. Is it possible to do this operation without reshaping?

Kevin
  • 3,096
  • 2
  • 8
  • 37
  • You are correct, reshape is different than transpose. In some way, transpose changes the order of data, reshape doesn't. `einsum` can be used as transpose, not as reshape. – Quang Hoang May 04 '21 at 18:55
  • 1
    Reshape from (2,5,10) to (10,2,5) is not the same as `transpose(2,0,1)`. Try that with a small integer array where you can see the change. `einsum` can transpose, and do sums on dimensions). – hpaulj May 04 '21 at 18:55
  • Given those array dimensions, and desire to do sum-of-products on the size 2 and 5 dimension, I'd use `np.einsum('ijkl,jlm->kim', a, b)` resulting in a (3,1,10) array. There's no need to transpose `b` dimensions (or much less "reshape" them). – hpaulj May 04 '21 at 20:16
  • @hpaulj I do want to reduce size 2 and 5 dimension, but they are collapsed into dimension 10 - I think this operation is only possible by fundamentally changing the shape of ```b``` (which I was trying to avoid). If the shape of ```b``` was ```(2,5,2,5)``` I could do ```np.einsum('ijkl,mnjl->kimn', a, b).reshape(3,1,-1)```, but again I *need* to reshape ```b``` somehow to decompose dimension 10 into (2,5) – Kevin May 04 '21 at 20:49
  • On further thought reshaping (2,5,10) to (10,2,5) isn't a problem, since both reshape to/from (2,5,2,5) or even (10,10). (20,5) to (5,20) would be a problem. The default ordering for that last `einsum` is 'ikmn'. It's up to you decide which (2,5) in `b` pair with the (2,5) in `a`. Anyways, don't be afraid of doing separate `reshape` (or even `transpose`) if necessary. Those aren't expensive operations. – hpaulj May 04 '21 at 21:40

0 Answers0