How to add dimension to a tensor using Tensorflow

倖福魔咒の 提交于 2021-01-02 07:44:32

问题


I have method reformat in which using numpy I convert a label(256,) to label(256,2) shape.

Now I want to do same operation on a Tensor with shape (256,)

My code looks like this (num_labels=2) :--

def reformat(dataset, labels):
  dataset = dataset.reshape((-1, image_size, image_size,num_channels)).astype(np.float32)
  labels = (np.arange(num_labels)==labels[:,None]).astype(np.float32)
  return dataset, labels

回答1:


You can use tf.expand_dims() to add a new dimension.

In [1]: import tensorflow as tf    
        x = tf.constant([3., 2.])
        tf.expand_dims(x, 1).shape

Out[1]: TensorShape([Dimension(2), Dimension(1)])

You can also use tf.reshape() for this, but would recommend you to use expand_dims, as this will also carry some values to new dimension if new shape can be satisfied.

In [1]: tf.reshape(x, [2, 1])
Out[1]: TensorShape([Dimension(2), Dimension(1)])


来源:https://stackoverflow.com/questions/42708652/how-to-add-dimension-to-a-tensor-using-tensorflow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!