I need to create a random variable inside my model_fn()
, having shape [batch_size, 20]
.
I do not want to pass batch_size
as an argument, because then I cannot use a different batch size for prediction.
Removing the parts which do not concern this question, my model_fn() is:
def model(inp, out):
eps = tf.random_normal([batch_size, 20], 0, 1, name="eps"))) # batch_size is the
# value I do not want to hardcode
# dummy example
predictions = tf.add(inp, eps)
return predictions, 1
if I replace [batch_size, 20]
by inp.get_shape()
, I get
ValueError: Cannot convert a partially known TensorShape to a Tensor: (?, 20)
when running myclf.setup_training()
.
If I try
def model(inp, out):
batch_size = tf.placeholder("float", [])
eps = tf.random_normal([batch_size.eval(), 20], 0, 1, name="eps")))
# dummy example
predictions = tf.add(inp, eps)
return predictions, 1
I get ValueError: Cannot evaluate tensor using eval(): No default session is registered. Use
with sess.as_default()or pass an explicit session to eval(session=sess)
(understandably, because I have not provided a feed_dict)
How can I access the value of batch_size
inside model_fn()
, while remaining able to change it during prediction?
I wasn't aware of the difference between
Tensor.get_shape()
andtf.shape(Tensor)
. The latter works:As mentionned in Tensorflow 0.8 FAQ: