2016-04-27 2 views
3

Мне нужно создать случайную переменную внутри моего model_fn(), имеющую форму [batch_size, 20].Использовать batch_size в model_fn в skflow

Я не хочу передавать batch_size в качестве аргумента, потому что тогда я не могу использовать другой размер партии для прогнозирования.

Удаление деталей, которые не касаются этого вопроса, мой model_fn() является:

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 

, если я заменю [batch_size, 20] на inp.get_shape(), я получаю

ValueError: Cannot convert a partially known TensorShape to a Tensor: (?, 20) 

при запуске myclf.setup_training().

Если я пытаюсь

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 

я ValueError: Cannot evaluate tensor using eval(): No default session is registered. Use с sess.as_default() or pass an explicit session to eval(session=sess) (по понятным причинам, потому что я не предоставил feed_dict)

Как я могу получить доступ к значению batch_size внутри model_fn(), оставаясь в состоянии изменить его во время предсказания?

+0

Пробуйте, используя None вместо batch_size.eval() – Aaron

+0

@Aaron Я пытался, но это дает мне 'TypeError: Ожидаемая двоичном или строка unicode, полученная None ' –

ответ

2

Я не знал о разнице между Tensor.get_shape() и tf.shape(Tensor). Последние работы:

eps = tf.random_normal(tf.shape(inp), 0, 1, name="eps"))) 

Как упоминалось в Tensorflow 0.8 FAQ:

How do I build a graph that works with variable batch sizes?

It is often useful to build a graph that works with variable batch sizes, for example so that the same code can be used for (mini-)batch training, and single-instance inference. The resulting graph can be saved as a protocol buffer and imported into another program.

When building a variable-size graph, the most important thing to remember is not to encode the batch size as a Python constant, but instead to use a symbolic Tensor to represent it. The following tips may be useful:

Use batch_size = tf.shape(input)[0] to extract the batch dimension from a Tensor called input, and store it in a Tensor called batch_size.

Use tf.reduce_mean() instead of tf.reduce_sum(...)/batch_size.

If you use placeholders for feeding input, you can specify a variable batch dimension by creating the placeholder with tf.placeholder(..., shape=[None, ...]). The None element of the shape corresponds to a variable-sized dimension.

Смежные вопросы