tensorflow裡面許多針對數組操作的函數,官方文檔又看了沒啥卵用,網上文章直接copy官方文檔而不解釋,只能自己寫個程式測試理解,以3個維度tensor進行理解
tf.transpose()作為數組的轉置函數,原型如下:
def transpose(a, perm=None, name="transpose"): """Transposes `a`. Permutes the dimensions according to `perm`.
a:是傳入的數組
perm:控制轉置的操作,以perm = [0,1,2] 3個維度數組為例, 0--代表的是最外層的一維, 1--代表外向內數第二維, 2--代表最內層的一維,這種perm是預設的值.現在以如下輸入數組來理解這個函數和參數perm
input_x = [ [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ], [ [13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24] ]]
input_x 是一個 2x3x4的一個tensor, 假設perm = [1,0,2], 就是將最外2層轉置,得到tensor應該是 3x2x4的一個張量,將input_x抽象化,不管第3維度
[
[
A,
B,
C
],
[
D,
E,
F,
]
]
變成2x3的tensor,類似於2x3的數組
[
A B C
D E F
]
轉置變成 3x2的數組
[
A D
B E
C F
]
再將A-F換成具體的值,最終得到的張量是
[
[
[ 1 2 3 4]
[13 14 15 16]
]
[
[ 5 6 7 8]
[17 18 19 20]
]
[
[ 9 10 11 12]
[21 22 23 24]
]
]
這就可以看出perm前兩列交換的作用
如果 perm=[0,2,1]說明要交換內層裡面的兩個維度,從原來的2x3x4變成2x4x3的張量,就不抽象化了,結果就是
[
[
[ 1 5 9]
[ 2 6 10]
[ 3 7 11]
[ 4 8 12]
]
[
[13 17 21]
[14 18 22]
[15 19 23]
[16 20 24]
]
]
下面貼出My Code:
import tensorflow as tfinput_x = [ [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ], [ [13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24] ]]result = tf.transpose(input_x, perm=[0, 2, 1])with tf.Session() as sess: print(sess.run(result))
注意,使用print(result)只會列印tensor的name shape dtype資訊
Tensor("transpose:0", shape=(2, 4, 3), dtype=int32)
想要打出數組的形式,使用session
result = tf.transpose(input_x, perm=[0, 2, 1])print(result)with tf.Session() as sess: print(sess.run(result))