Python 轴置换的多维变换

Python 轴置换的多维变换,python,numpy,transpose,Python,Numpy,Transpose,对于高维数组,transpose将接受轴编号的元组来排列轴(用于额外的思维扭曲): 我试图理解转置((1,0,2)如何生成上述输出。我无法理解置换轴的含义?请用外行术语解释,以及如何生成上述输出 感谢默认转置是反转轴,因此A x B矩阵变成B x A。对于3D,默认转置是A x B x C到C x B x A 在您的示例中,转置(1,0,2),它将A x B x C转置到B x C。这是因为默认的3D转置是(2,1,0),但您有(1,0,2),它只是交换前两个轴 当您进行实验时,如果您使用形状的

对于高维数组,transpose将接受轴编号的元组来排列轴(用于额外的思维扭曲):

我试图理解转置((1,0,2)如何生成上述输出。我无法理解置换轴的含义?请用外行术语解释,以及如何生成上述输出


感谢默认转置是反转轴,因此
A x B
矩阵变成
B x A
。对于3D,默认转置是
A x B x C
C x B x A

在您的示例中,
转置(1,0,2)
,它将
A x B x C
转置到
B x C
。这是因为默认的3D转置是
(2,1,0)
,但您有
(1,0,2)
,它只是交换前两个轴


当您进行实验时,如果您使用形状的示例数组
2x3x4
或其他没有重复项的组合,可能会更清楚。

转置矩阵本质上是切换维度的顺序,例如:
arr.transpose()
在这种情况下等于
arr.transpose((2,1,0))

另一方面,如果您希望手动选择尺寸的顺序,您将通过使用
arr.transpose((0,1,2))
进行转置来保留原始顺序(即,不更改任何内容)

在您的示例中,您将数组的最后一个维度(2)保持不变,例如
[0,1,2,3]
。但是,您切换了前两个维度(0和1),因此
arr[0,0,0:4]
处的元素仍然存在,但是
arr[1,0,0:4]
的内容现在在转置后出现在
arr[0,1,0:4]

In[]: t_arr = arr.transpose((1,0,2))
In[]: arr[0,0,0:4] == t_arr[0,0,0:4]
Out[]: 
array([ True,  True,  True,  True], dtype=bool)

In[]: arr[0,1,0:4] == t_arr[1,0,0:4]   # indices #0,1,0-3 and #1,0,0-3 respectively
Out[]: 
array([ True,  True,  True,  True], dtype=bool)
这也是您在转置多维矩阵时所期望的。轴以某种方式交换,以便元素位于与以前几乎相同的索引处,仅以交换顺序,即:

arr[x,y,z] == arr.transpose()[z,y,x]           # True
arr[x,y,z] == arr.transpose((1,0,2))[y,x,z]    # True (your case)

考虑一个数组及其转置:

arr = np.arange(24).reshape((2, 3, 4))
arrt = arr.transpose((1, 0, 2))
默认情况下,
transpose
只是颠倒维度的顺序。上面的特定transpose命令交换前两个维度,但保留最后一个维度不变。让我们在几个示例中进行验证:

print(arr.shape)
# (2, 3, 4)

print(arrt.shape)
# (3, 2, 4)

# the last dimension is the same in both arrays
print(arr[0, 0, :])
# [0 1 2 3]
print(arrt[0, 0, :])
# [0 1 2 3]

print(arr[:, 0, 0])  # what was before the first dimension
# [ 0 12]
print(arrt[0, :, 0])  # is now the second dimension
# [ 0 12]

# the first two dimensions are swapped - the submatrix is transposed
print(arr[:, :, 0])
# [[ 0  4  8]
#  [12 16 20]]
print(arrt[:, :, 0])
# [[ 0 12]
#  [ 4 16]
#  [ 8 20]]

我猜@JohnZwinck的速度更快,但我会留下它,因为不同的表达方式可能会有用=)谢谢你的澄清。但我不明白行是如何交换的。还有,你所说的指数是什么意思?#0,0,0-3谢谢你的评论,我举了两个例子来说明,我所说的指数是什么意思,以及交换是如何发生的。
print(arr.shape)
# (2, 3, 4)

print(arrt.shape)
# (3, 2, 4)

# the last dimension is the same in both arrays
print(arr[0, 0, :])
# [0 1 2 3]
print(arrt[0, 0, :])
# [0 1 2 3]

print(arr[:, 0, 0])  # what was before the first dimension
# [ 0 12]
print(arrt[0, :, 0])  # is now the second dimension
# [ 0 12]

# the first two dimensions are swapped - the submatrix is transposed
print(arr[:, :, 0])
# [[ 0  4  8]
#  [12 16 20]]
print(arrt[:, :, 0])
# [[ 0 12]
#  [ 4 16]
#  [ 8 20]]