tf.reshape()與tf.transpose的理解
阿新 • • 發佈:2019-02-18
背景:初次接觸tf.transpose,對其中的維度的理解,甚是困難,作此記錄,以便以後檢視
(1)tf.reshape()的理解
import tensorflow as tf import numpy as np three_dim_data = tf.Variable(np.arange(100).reshape(2,5,10)) three_dim_data_reshape = tf.Variable(tf.reshape(three_dim_data,[10,10])) with tf.Session().as_default() as sess: sess.run(tf.global_variables_initializer()) print(sess.run(three_dim_data)) print(sess.run(three_dim_data_reshape))
three_dim_data輸出結果為:
[[[ 0 1 2 3 4 5 6 7 8 9] [10 11 12 13 14 15 16 17 18 19] [20 21 22 23 24 25 26 27 28 29] [30 31 32 33 34 35 36 37 38 39] [40 41 42 43 44 45 46 47 48 49]] [[50 51 52 53 54 55 56 57 58 59] [60 61 62 63 64 65 66 67 68 69] [70 71 72 73 74 75 76 77 78 79] [80 81 82 83 84 85 86 87 88 89] [90 91 92 93 94 95 96 97 98 99]]]
three_dim_data_reshape的輸出結果為:
[[ 0 1 2 3 4 5 6 7 8 9] [10 11 12 13 14 15 16 17 18 19] [20 21 22 23 24 25 26 27 28 29] [30 31 32 33 34 35 36 37 38 39] [40 41 42 43 44 45 46 47 48 49] [50 51 52 53 54 55 56 57 58 59] [60 61 62 63 64 65 66 67 68 69] [70 71 72 73 74 75 76 77 78 79] [80 81 82 83 84 85 86 87 88 89] [90 91 92 93 94 95 96 97 98 99]]
通過兩種情況的對比,reshape的操作,是將原始資料,先平鋪出來[0-99],然後再按照維度的倒序,進行構建資料。
例如three_dim_data這是按照,先10,5,2這樣的順序構造資料。
three_dim_data_reshape則是先平鋪,再10,10這樣的順序構造資料。
(2)tf.transpose的理解
理解了tf.reshape就很容易理解tf.transpose了
tf.transpose是改變資料的組成結構。功能與tf.reshape類似。
import tensorflow as tf
import numpy as np
three_dim_data = tf.Variable(np.arange(100).reshape(2,5,10))
three_dim_data_transpose = tf.transpose(three_dim_data,[1,0,2])
transpose_shape = three_dim_data_transpose.shape
with tf.Session().as_default() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run(three_dim_data))
print(sess.run(three_dim_data_transpose))
print(transpose_shape)
輸出結果為:
[[[ 0 1 2 3 4 5 6 7 8 9]
[50 51 52 53 54 55 56 57 58 59]]
[[10 11 12 13 14 15 16 17 18 19]
[60 61 62 63 64 65 66 67 68 69]]
[[20 21 22 23 24 25 26 27 28 29]
[70 71 72 73 74 75 76 77 78 79]]
[[30 31 32 33 34 35 36 37 38 39]
[80 81 82 83 84 85 86 87 88 89]]
[[40 41 42 43 44 45 46 47 48 49]
[90 91 92 93 94 95 96 97 98 99]]]
(5, 2, 10)
相當於將(2,5,10)reshape為了(5,2,10)
tf.transpose()中的[1,0,2]只是在交換(2,5,10)維度的的位置而已,交換後,就可以看成reshape了