1
votes

For tensorflow functions that require a shape argument, how can we feed a dynamic shape as one of the input argument(s)?

For instance, let's say I have a placeholder

x = tf.placeholder(tf.float32, [None, 3])

And now I want to create a 1D random tensor with the same shape as the first dimension of x.

r = tf.random_uniform([x.get_shape()[0]])

This will not work since x.get_shape()[0] will return a static shape "None". Is there a a way to assign a dynamic shape to r based on the dynamic shape of x?

2

2 Answers

1
votes

You can get the dynamic shape of a tensor using the tf.shape() op, and use that as the argument to tf.random_uniform():

x = tf.placeholder(tf.float32, [None, 3])
r = tf.random_uniform(tf.shape(x)[0:1])

(Note that the slice of tf.shape(x), i.e. [0:1] must specify a range rather than a single element, because tf.random_uniform() expects a vector of dimensions.)

0
votes
x = tf.placeholder(tf.float32, [None, 3])
s = tf.shape(x)
s2 = tf.slice(s, [0], [1])
r = tf.random_uniform(s2)
sess = create_session()
print r.eval(feed_dict={x:np.ones((4,3))})

[ 0.69890845 0.64149153 0.16378665 0.89732885]