所谓维度变换就是,将一个高维度的数据,通过一定的方式转换为低维度,比如下面的例子。
tf.reshape()
In [2]: a=tf.random.normal([4,28,28,3])
2019-07-27 09:38:52.383549: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
In [3]: a.shape,a.ndim
Out[3]: (TensorShape([4, 28, 28, 3]), 4)
In [4]: tf.reshape(a,[4,784,3]).shape
Out[4]: TensorShape([4, 784, 3])
In [5]: tf.reshape(a,[4,-1,3]).shape
Out[5]: TensorShape([4, 784, 3])
In [6]: tf.reshape(a,[4,784*3]).shape
Out[6]: TensorShape([4, 2352])
In [7]: tf.reshape(a,[4,-1]).shape
Out[7]: TensorShape([4, 2352])
In [9]: tf.reshape(tf.reshape(a,[4,-1]),[4,28,28,3]).shape
Out[9]: TensorShape([4, 28, 28, 3])
tf.transpose()(转置)
In [10]: a=tf.random.normal((4,3,2,1))
In [11]: a.shape
Out[11]: TensorShape([4, 3, 2, 1])
In [12]: tf.transpose(a).shape
Out[12]: TensorShape([1, 2, 3, 4])
In [13]: tf.transpose(a,perm=[0,1,3,2]).shape
Out[13]: TensorShape([4, 3, 1, 2])
tf.expand_dims() (增加维度)
当轴给的是正数的时候它会在轴前面增加,给的是负的时候,会在负轴后面添加。
In [14]: a=tf.random.normal([4,35,8])
In [15]: tf.expand_dims(a,axis=0).shape
Out[15]: TensorShape([1, 4, 35, 8])
In [16]: tf.expand_dims(a,axis=3).shape
Out[16]: TensorShape([4, 35, 8, 1])
In [17]: tf.expand_dims(a,axis=-1).shape
Out[17]: TensorShape([4, 35, 8, 1])
In [18]: tf.expand_dims(a,axis=-4).shape
Out[18]: TensorShape([1, 4, 35, 8])
tf.squeeze()
减少shape为1的那个维度
In [19]: tf.squeeze(tf.zeros([1,2,1,1,3])).shape
Out[19]: TensorShape([2, 3])
In [20]: a=tf.zeros([1,2,1,3])
In [21]: tf.squeeze(a,axis=0).shape
Out[21]: TensorShape([2, 1, 3])
In [22]: tf.squeeze(a,axis=2).shape
Out[22]: TensorShape([1, 2, 3])
In [23]: tf.squeeze(a,axis=-2).shape
Out[23]: TensorShape([1, 2, 3])
In [24]: tf.squeeze(a,axis=-4).shape
Out[24]: TensorShape([2, 1, 3])