7

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.

Hooked
  • 84,485
  • 43
  • 192
  • 261
user1936768
  • 659
  • 1
  • 9
  • 14

2 Answers2

6

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.

Rafał Józefowicz
  • 6,215
  • 2
  • 24
  • 18
0

Try this one:

0 * tf.identity(X) + 1
chenlian
  • 690
  • 6
  • 7