Jeff Saremi
Jeff Saremi

Reputation: 3014

Baffled by numpy's transpose

Let's take a very simple case: an array with shape (2,3,4), ignoring the values.

>>> a.shape
(2, 3, 4)

When we transpose it and print the dimensions:

>>> a.transpose([1,2,0]).shape
(3, 4, 2)

So I'm saying: take axis index 2 and make it the first, then take axis index 0 and make it the second and finally take axis index 1 and make it the third. I should get (4,2,3), right?

Well, I thought perhaps I don't understand the logic fully. So I read the documentation and its says:

Use transpose(a, argsort(axes)) to invert the transposition of tensors when using the axes keyword argument.

So I tried

>>> c = np.transpose(a, [1,2,0])
>>> c.shape
(3, 4, 2)
>>> np.transpose(a, np.argsort([1,2,0])).shape
(4, 2, 3)

and got yet a completely different shape!

Could someone please explain this? Thanks.

Upvotes: 1

Views: 202

Answers (2)

hpaulj
hpaulj

Reputation: 231385

In [259]: a = np.zeros((2,3,4))
In [260]: idx = [1,2,0]
In [261]: a.transpose(idx).shape
Out[261]: (3, 4, 2)

What this has done is take a.shape[1] dimension and put it first. a.shape[2] is 2nd, and a.shape[0] third:

In [262]: np.array(a.shape)[idx]
Out[262]: array([3, 4, 2])

transpose without parameter is a complete reversal of the axis order. It's an extension of the familiar 2d transpose (rows become columns, columns become rows):

In [263]: a.transpose().shape
Out[263]: (4, 3, 2)
In [264]: a.transpose(2,1,0).shape
Out[264]: (4, 3, 2)

And the do-nothing transpose:

In [265]: a.transpose(0,1,2).shape
Out[265]: (2, 3, 4)

You have an initial axes order and final one; describing swap can be hard to visualize if you don't regularly work with lists of size 3 or larger.

Some people find it easier to use swapaxes, which changes the order of just axes. rollaxis is yet another way.

I prefer to use transpose since it can do anything the others can; so I just have to develop an intuitive for one tool.


The argsort comment operates this way:

In [278]: a.transpose(idx).transpose(np.argsort(idx)).shape
Out[278]: (2, 3, 4)

That is, apply it to the result of one transpose to get back the original order.

Upvotes: 4

James Liu
James Liu

Reputation: 517

np.argsort([1,2,0]) returns an array like [2,0,1]

So

np.transpose(a, np.argsort([1,2,0])).shape

act like

np.transpose(a, [2,0,1]).shape

not

np.transpose(a, [1,2,0]).shape

Upvotes: 1

Related Questions