user1936768 - 9 months ago 41

Python Question

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`

Answer

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.