理解 numpy 的转置

Understand numpy's transpose

我有以下python代码

import numpy as np
import itertools as it

ref_list = [0, 1, 2]
p = it.permutations(ref_list)
transpose_list = tuple(p)

#print('transpose_list', transpose_list)

na = nb = nc = 2


A = np.zeros((na,nb,nc))
n = 1
for la in range(na):
    for lb in range(nb):
        for lc in range(nc):
            A[la,lb,lc] = n
            n = n + 1   


factor_list = [(i+1)*0.0 for i in range(6)]
factor_list[0] = 0.1
factor_list[1] = 0.2
factor_list[2] = 0.3
factor_list[3] = 0.4





sum_A = np.zeros((na,nb,nc))
for m, t in enumerate(transpose_list):
    if abs(factor_list[m]) < 1.e-3:
        continue 
    factor_list[m]  * np.transpose(A, transpose_list[m]) 

    print('inter', m, t, factor_list[m], np.transpose(A, transpose_list[m])[0,0,1] )

B = np.transpose(A, (0, 2, 1))
C = np.transpose(A, (1, 2, 0))

for la in range(na):
    for lb in range(nb):
        for lc in range(nc):
            print(la,lb,lc,'A',A[la,lb,lc],'B',B[la,lb,lc],'C',C[la,lb,lc])

结果是

inter 0 (0, 1, 2) 0.1 2.0
inter 1 (0, 2, 1) 0.2 3.0
inter 2 (1, 0, 2) 0.3 2.0
inter 3 (1, 2, 0) 0.4 5.0
0 0 0 A 1.0 B 1.0 C 1.0
0 0 1 A 2.0 B 3.0 C 5.0
0 1 0 A 3.0 B 2.0 C 2.0
0 1 1 A 4.0 B 4.0 C 6.0
1 0 0 A 5.0 B 5.0 C 3.0
1 0 1 A 6.0 B 7.0 C 7.0
1 1 0 A 7.0 B 6.0 C 4.0
1 1 1 A 8.0 B 8.0 C 8.0

我的问题是,为什么 inter 1inter 3 得到 3.0 和 5.0? objective是获取 P(A)[0,0,1].

对于inter 1来说是(0, 2, 1),我在[0,0,1] -> [0,1,0]

上考虑了(0,2,1)

对于inter 3来说是(1, 2, 0),我在[0,0,1] -> [0,1,0]

上考虑了(1,2,0)

所以值应该是一样的。输出不一样(3.05.0)。所以显然我误解了 np.transposenp.transpose内部发生的事情的正确理解是什么?

更具体地说,来自 ,Anand S Kumar 的回答 我试图从 (0, 2, 1)(1, 2, 0) 两个方面思考,都导致

(0,0,0) -> (0,0,0)
(0,0,1) -> (0,1,0)

我猜这与置换的逆有关。但我不确定为什么。

一种更直接的方式让你的 A:

In [29]: A = np.arange(1,9).reshape(2,2,2)
In [30]: A
Out[30]: 
array([[[1, 2],
        [3, 4]],

       [[5, 6],
        [7, 8]]])

转置:

In [31]: B = np.transpose(A, (0, 2, 1))
    ...: C = np.transpose(A, (1, 2, 0))
In [32]: B
Out[32]: 
array([[[1, 3],
        [2, 4]],

       [[5, 7],
        [6, 8]]])
In [33]: C
Out[33]: 
array([[[1, 5],
        [2, 6]],

       [[3, 7],
        [4, 8]]])

其中两个案例:

In [35]: A[0,0,1], B[0,1,0],C[0,1,0]
Out[35]: (2, 2, 2)
In [36]: A[1,0,0], B[1,0,0], C[0,0,1]
Out[36]: (5, 5, 5)

只需交换最后两个索引即可轻松匹配 AB。将第 1 和第 3 换成 C 很诱人,但这是错误的。当第一个移动到最后时,其他的不改变顺序移动:

In [38]: for la in range(na):
    ...:     for lb in range(nb):
    ...:         for lc in range(nc):
    ...:             print(la,lb,lc,'A',A[la,lb,lc],'B',B[la,lc,lb],'C',C[lb,lc,la])

0 0 0 A 1 B 1 C 1
0 0 1 A 2 B 2 C 2
0 1 0 A 3 B 3 C 3
0 1 1 A 4 B 4 C 4
1 0 0 A 5 B 5 C 5
1 0 1 A 6 B 6 C 6
1 1 0 A 7 B 7 C 7
1 1 1 A 8 B 8 C 8