Tensorflow: How to use expand_Dim() to add dimensions

In tensorflow, you can use to add one dimension to the dimension tf.expand_ Dims (input, dim, name = none) function. Of course, we often use it tf.reshape (input, shape = []) can also achieve the same effect, but sometimes in the process of building a graph, the placeholder is not fed with a specific value, and the following error will be included: type error: expected binary or Unicode string, got 1
in this case, we can consider using expand_ Dims to add one dimension. For example, in the case of my own code, when the image dimension is reduced to two dimensions, I need to restore it to four dimensions [batch, height, width, channels], and add one dimension before and after. If reshape is used, an error will be reported for the above reasons

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

It can be realized by the following methods:

one_img = tf.expand_dims(one_img, 0)
one_img = tf.expand_dims(one_img, -1) #-1 denotes the last dimension

In the end, an official example is given

# '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.

Read More: