Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add dimension to a tensor using Tensorflow

Tags:

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
like image 893
Anuj Avatar asked Mar 10 '17 01:03

Anuj


1 Answers

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)])
like image 134
umutto Avatar answered Sep 21 '22 11:09

umutto