• 可以使用搜索框,搜索指定的书籍!
  • 终于有Python的书籍了,暂时没人访问😢

如何理解NumPy的transpose方法

Python wanyahai 3个月前 (09-27) 124次浏览 0个评论 扫描二维码

在学习理解 NumPy 的 transpose 方法的时候,在 Stackoverflow 上面发现了一个很好的回答,特地搬运过来原文地址

To transpose an array, NumPy just swaps the shape and stride information for each axis. Here are the strides:

>>> arr = np.arange(16).reshape((2, 2, 4))
>>> arr.strides
(64, 32, 8)

>>> arr.transpose(1, 0, 2).strides
(32, 64, 8)

Notice that the transpose operation swapped the strides for axis 0 and axis 1. The lengths of these axes were also swapped (both lengths are 2 in this example).
No data needs to be copied for this to happen; NumPy can simply change how it looks at the underlying memory to construct the new array.


Visualising strides
The stride value represents the number of bytes that must be travelled in memory in order to reach the next value of an axis of an array.

Now, our 3D array arr looks this (with labelled axes):

This array is stored in a contiguous block of memory; essentially it is one-dimensional. To interpret it as a 3D object, NumPy must jump over a certain constant number of bytes in order to move along one of the three axes:

Since each integer takes up 8 bytes of memory (we’re using the int64 dtype), the stride value for each dimension is 8 times the number of values that we need to jump. For instance, to move along axis 1, four values (32 bytes) are jumped, and to move along axis 0, eight values (64 bytes) need to be jumped.

When we write arr.transpose(1, 0, 2) we are swapping axes 0 and 1. The transposed array looks like this:

All that NumPy needs to do is to swap the stride information for axis 0 and axis 1 (axis 2 is unchanged). Now we must jump further to move along axis 1 than axis 0:

This basic concept works for any permutation of an array’s axes. The actual code that handles the transpose is written in C and can be found here.


本站大部分内容收集于互联网,只做学习和交流使用,版权归原作者所有。本站发布的内容若侵犯到您的权益,请联系本站处理。
喜欢 (1)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址