tf.reshape()与tf.transpose的理解

背景:初次接触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了

猜你喜欢

转载自blog.csdn.net/qq_21735341/article/details/80869615
今日推荐