Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TensorFlow initializing Tensor of ones

So suppose I have a tensor

X = tf.placeholder("float", [None, 5])

So that I know the number of columns but not the number of rows. I need to initialize a vector of ones of dimension nrows x 1

Now the following block of code does not work,

o = tf.ones(shape=(tf.shape(X)[0], 1))
==> TypeError: List of Tensors when single Tensor expected

Nor does,

o = tf.ones(shape=(X.get_shape()[0].value, 1))
==> TypeError: Input 'dims' of 'Fill' Op has type 
    string that does not match expected type of int32.

Now, I have found that one way to get around this is to actually make my vector of ones a placeholder,

o = tf.placeholder(dtype=tf.float32, shape=[None, 1])

And to pass in a numpy array of ones of appropriate size in my feed_dict. But this solution strikes me as inelegant and not the intended use of a placeholder. I could be wrong here, but surely there's a better way.

like image 492
user1936768 Avatar asked Nov 14 '15 17:11

user1936768


People also ask

How do you initialize a TensorFlow variable?

To initialize a new variable from the value of another variable use the other variable's initialized_value() property. You can use the initialized value directly as the initial value for the new variable, or you can use it as any other tensor to compute a value for the new variable.

How do you initialize a TensorFlow variable in a matrix?

First, remember that you can use the TensorFlow eye functionality to easily create a square identity matrix. We create a 5x5 identity matrix with a data type of float32 and assign it to the Python variable identity matrix. So we used tf. eye, give it a size of 5, and the data type is float32.

What is the difference between Eagertensor and tensor?

EagreTensor represents a tensor who's value has been calculated in eager mode whereas Tensor represents a tensor node in a graph that may not yet have been calculated.


1 Answers

The way to solve your problem is to use tf.pack operation:

o = tf.ones(shape=tf.pack([tf.shape(X)[0], 1]))

The reason you had errors is that TensorFlow shape is expected to be a list of integers or a tensor link. tf.pack makes it easy to convert a list of integers and/or TensorFlow scalars into a Tensor object.

like image 64
Rafał Józefowicz Avatar answered Nov 15 '22 09:11

Rafał Józefowicz