神经网络学习-tensorflow2.0-维度变换
1.tf.reshape(tensor,[newshape]):将原来的tensor变换为指定的新的维度,元素个数不发生变化(一般用于维度合并)
examples:
input:
a=tf.random.normal([4,28,28,3])
b=tf.reshape(a,[4,-1,3])
print(tf.shape(b))
output:
tf.Tensor([ 4 784 3], shape=(3,), dtype=int32)
input:
a=tf.random.normal([4,28,28,3])
c=tf.reshape(tf.reshape(a,[4,-1,3]),[4,14,28,6]).shape
print(c)
output: (4, 14, 28, 6)
2.tf.transpose(tensor,perm=[new order]):将原tensor的维度顺序改为所指定的新顺序
(若不指定new order则默认为倒序)
examples:
input:
a=tf.random.normal([4,28,28,3])
b=tf.transpose(a,[0,3,1,2]).shape
c=tf.transpose(a).shape
print(b,'\n',c)
output:
(4, 3, 28, 28)
(3, 28, 28, 4)
3.tf.expand_dims(tensor,axis=a):在指定的位置增加一个新的维度(新增维度的值为1),若该位置已有维度,则将该位置及其之后的dim向后移动1,该位置变为1
example:
input:
a=tf.random.normal([4,28,28,3])
b=tf.expand_dims(a,axis=2).shape
c=tf.expand_dims(a,axis=0).shape
print(b,'\n',c)
output:
(4, 28, 1, 28, 3)
(1, 4, 28, 28, 3)
4.tf.squeeze(a,axis=a):将指定的值为1的维度去除,若不指定,则去除tensor中所有为1的维度
(*注意*)不可指定值不为1的维度,将会报错。
example:
input:
a=tf.random.normal([4,1,1,3])
b=tf.squeeze(a).shape
c=tf.squeeze(a,axis=1).shape
print(b,'\n',c)
output:
(4, 3)
(4, 1, 3)

浙公网安备 33010602011771号