seewalker
seewalker

Reputation: 1243

Referring to Undetermined Placeholder Size In Tensorflow?

There is a case where I need to make an elementwise comparison between output of my model and a constant. However, the output of the model has a size depending on a placeholder, and it seems difficult to refer to constants of that same size.

This first attempt somehow produces a scalar value rather than doing elementwise operations:

tf.less(y,tf.constant(k,dtype=tf.float32))

This second attempt has elementwise behavoir, but is a kludge:

 tf.less(y,tf.constant(k,shape= [<INT_GREATER_THAN_BATCHSIZE>],dtype=tf.float32))

Is there a clean way to refer to the yet-undetermined size of the placeholder in the graph?

Upvotes: 0

Views: 354

Answers (1)

mrry
mrry

Reputation: 126194

The easiest way to refer to the shape of a (dynamically sized) tensor is using the tf.shape(x) op, which produces at runtime a vector of integers that contain the true shape of a tensor x.

Note that tf.constant() does not accept a dynamic shape as an argument—for then it would not be constant!—but the similar tf.fill() op does.

Therefore you can write:

p = tf.placeholder(..., shape=[None])
# ...
result = tf.less(y, tf.fill(tf.shape(p), tf.constant(k, dtype=tf.float32)))

PS. Note that, if k is a scalar, the tf.less() op should broadcast the shape of k to match y, and the following should work:

tf.less(y, tf.constant(k, dtype=tf.float32))

...but it's not clear why that's not working for you.

Upvotes: 1

Related Questions