在TensorFlow中对tensor的维度进行拓展和压缩

参考:

https://blog.csdn.net/jasonzzj/article/details/60811035

https://blog.csdn.net/UESTC_V/article/details/80310487

TensorFlow中,想要维度增加一维,可以使用tf.expand_dims(input, dim, name=None)函数。

当然,我们常用tf.reshape(input, shape=[])也可以达到相同效果,

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

但是有些时候在构建图的过程中,placeholder没有被feed具体的值,这时就会包下面的错误:

TypeError: Expected binary or unicode string, got 1

因此我们使用tf.expand_dims的方法

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]


Args: 
input: A Tensor. 
dim: A Tensor. Must be one of the following types: int32, int64. 0-D (scalar). 
      Specifies the dimension index at which to expand the shape of input. 
name: A name for the operation (optional).

Returns: 
A Tensor. Has the same type as input. Contains the same data as input,
         but its shape has an additional dimension of size 1 added.

可以看到在调用函数后,tensor中加入了一个“1”的维度,我在网上查了一下,这个“1”只是代表增加了一个维度,

没有任何具体的含义。

说完了维度扩张的方法再来看一下降低维度的方法

tf.squeeze()

参数列表

tf.squeeze(input, axis=None, name=None, squeeze_dims=None)
#  一些实例


# 't' is a tensor of shape [1, 2, 1, 3, 1, 1]
  shape(squeeze(t)) ==> [2, 3]
# 't' is a tensor of shape [1, 2, 1, 3, 1, 1]
  shape(squeeze(t, [2, 4])) ==> [1, 2, 3, 1]

无意之间看到了一个春招的帖子,给大家分享一下

https://blog.csdn.net/dQCFKyQDXYm3F8rB0/article/details/89391988

猜你喜欢

转载自blog.csdn.net/Pierce_KK/article/details/89439090