numpy.swapaxes如何工作? [英] How does numpy.swapaxes work?
问题描述
我创建了一个示例数组:
I created a sample array:
a = np.arange(18).reshape(9,2)
在打印时,我将其作为输出:
On printing, I get this as output:
[[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]
[ 8 9]
[10 11]
[12 13]
[14 15]
[16 17]]
在执行此重塑操作时:
b = a.reshape(2,3,3).swapaxes(0,2)
我得到:
[[[ 0 9]
[ 3 12]
[ 6 15]]
[[ 1 10]
[ 4 13]
[ 7 16]]
[[ 2 11]
[ 5 14]
[ 8 17]]]
我遇到了这个问题,但是并不能解决我的问题.
I went through this question, but it does not solve my problem.
该文档也没有用.
https://docs.scipy.org/doc/numpy/reference/generation/numpy.swapaxes.html
我需要知道交换的工作方式(x轴,y轴,z轴).进行图解说明将是最有帮助的.
I need to know how the swapping is working(which is x-axis, y-axis, z-axis). A diagrammatic explanation would be most helpful.
推荐答案
从重塑开始
In [322]: a = np.arange(18).reshape(2,3,3)
In [323]: a
Out[323]:
array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]]])
这将显示为2个平面,每个平面为3x3.那部分清楚吗?数组在某一点处成形为(9,2)的事实并不重要.重塑不会改变元素的顺序.
This displays as 2 planes, and each plane is a 3x3. Is that part clear? The fact that the array was shaped (9,2) at one point isn't significant. Reshaping doesn't change the order of elements.
应用swapaxes
.形状现在是(3,3,2). 3个平面,每个平面为3x2.这种特殊的交换与转置相同
Apply the swapaxes
. Shape is now (3,3,2). 3 planes, each is 3x2. This particular swap is the same as a transpose
np.arange(18).reshape(2,3,3).transpose(2,1,0)
中轴不变.仍然有[0,3,6],[9,12,15]等列.
The middle axis is unchanged. There are still columns of [0,3,6], [9,12,15], etc.
使用3种不同尺寸的轴可视化更改可能更容易
It may be easier to visualize the change with 3 different sized axes
In [335]: a=np.arange(2*3*4).reshape(2,3,4)
In [336]: a
Out[336]:
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])
In [337]: a.swapaxes(0,2)
Out[337]:
array([[[ 0, 12],
[ 4, 16],
[ 8, 20]],
[[ 1, 13],
[ 5, 17],
[ 9, 21]],
[[ 2, 14],
[ 6, 18],
[10, 22]],
[[ 3, 15],
[ 7, 19],
[11, 23]]])
请注意当我展平数组时会发生什么情况
Notice what happens when I flatten the array
In [338]: a.swapaxes(0,2).ravel()
Out[338]:
array([ 0, 12, 4, 16, 8, 20, 1, 13, 5, 17, 9, 21, 2, 14, 6, 18, 10,
22, 3, 15, 7, 19, 11, 23])
条款的顺序已经改组.创建时为[0,1,2,3 ...].现在1
是第六项(2x3).
the order of terms has been shuffled. As created it was [0,1,2,3...]. Now the 1
is the 6th term (2x3).
在封面下numpy
实际上是通过更改shape
,strides
和order
来执行交换或转置的,而不更改数据缓冲区(即它是视图).但是,进一步的重塑(包括穿行)迫使其进行复制.但这在现阶段可能比帮助更令人困惑.
Under the covers numpy
actually performs the swap or transpose by changing shape
, strides
and order
, without changing the data buffer (i.e. it's a view). But further reshaping, including raveling, forces it to make a copy. But that might be more confusing than helpful at this stage.
在numpy
中已编号.诸如x,y,z或平面,行,列之类的术语可以帮助您将其映射到可以可视化的结构上,但它们不是内置"的.用文字描述交换或转置非常棘手.
In numpy
axes are numbered. Terms like x,y,z or planes, rows, columns may help you map those on to constructs that you can visualize, but they aren't 'built-in'. Describing the swap or transpose in words is tricky.
这篇关于numpy.swapaxes如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!