TensorFlow笔记(十四)——降维函数tf.squeeze()、增维函数expand_dim()

一、降维函数tf.squeeze()

squeeze(
    input,
    axis=None,
    name=None,
    squeeze_dims=None
)

该函数返回一个张量,这个张量是将原始input中所有维度为1的那些维都删掉的结果【1】
axis可以用来指定要删掉的为1的维度,此处要注意指定的维度必须确保其是1,否则会报错

>>>y = tf.squeeze(inputs, [0, 1], name='squeeze')
>>>ValueError: Can not squeeze dim[0], expected a dimension of 1, got 32 for 'squeeze' (op: 'Squeeze') with input shapes: [32,1,1,3].

例子:

#  't' 是一个维度是[1, 2, 1, 3, 1, 1]的张量
tf.shape(tf.squeeze(t))   # [2, 3], 默认删除所有为1的维度

# 't' 是一个维度[1, 2, 1, 3, 1, 1]的张量
tf.shape(tf.squeeze(t, [2, 4]))  # [1, 2, 3, 1],标号从零开始,只删掉了2和4维的1

二、增维函数expand_dim()

tf.expand_dims(
    input,
    axis=None,
    name=None,
    dim=None
)

作用:给定一个input,在axis轴处给input增加一个为1的维度。 

TensorFlow中,想要维度增加一维,可以使用tf.expand_dims(input, axis=None, name=None,dim)函数。当然,我们常用tf.reshape(input, shape=[])也可以达到相同效果,但是有些时候在构建图的过程中,placeholder没有被feed具体的值,这时就会包下面的错误:TypeError: Expected binary or unicode string, got 1 
在这种情况下,我们就可以考虑使用expand_dims来将维度加1。比如我自己代码中遇到的情况,在对图像维度降到二维做特定操作后,要还原成四维[batch, height, width, channels],前后各增加一维。如果用reshape,则因为上述原因报错

one_img2 = tf.reshape(one_img, shape=[1, one_img.get_shape()[0].value, one_img.get_shape()[1].value, 1])

用下面的方法可以实现:

one_img = tf.expand_dims(one_img, 0)
one_img = tf.expand_dims(one_img, -1) #-1表示最后一维
给出官方的例子和说明

# 't' is a tensor of shape [2]
shape(expand_dims(t, 0)) ==> [1, 2]
shape(expand_dims(t, 1)) ==> [2, 1]
shape(expand_dims(t, -1)) ==> [2, 1]

# 't2' is a tensor of shape [2, 3, 5]
shape(expand_dims(t2, 0)) ==> [1, 2, 3, 5]
shape(expand_dims(t2, 2)) ==> [2, 3, 1, 5]
shape(expand_dims(t2, 3)) ==> [2, 3, 5, 1]

axis的0其实代表的第一维度,那么1代表第二维度,2代表第三位度。以此类推。其中-1表示最后一维。

 

【1】链接:https://www.jianshu.com/p/a21c0bc10a38

 

你可能感兴趣的:(TransorFlow笔记)