是否可以在tf.while_loop中定义多个条件

时间:2017-08-09 15:53:32

标签: tensorflow tensorflow-gpu

是否可以在tensorflow中定义多个条件来终止tf.while_loop?例如,取决于实现两个特定值的两个张量值。例如。 i==2j==3

我还可以在身体中有几个代码块吗?在文档中的所有示例中,似乎正文更像是返回值或元组的单个语句。我想在正文中执行一组几个“顺序”语句。

1 个答案:

答案 0 :(得分:2)

tf.while_loop接受一个必须返回布尔张量的泛型可调用(用def定义的python函数)或lambdas。

因此,您可以使用logical operators链接条件正文中的多个条件,例如tf.logical_andtf.logical_or,...

即使body是一般python可调用的,因此您不仅限于lambdas和单个语句函数。

这样的东西是完全可以接受的并且效果很好:

import tensorflow as tf
import numpy as np


def body(x):
    a = tf.random_uniform(shape=[2, 2], dtype=tf.int32, maxval=100)
    b = tf.constant(np.array([[1, 2], [3, 4]]), dtype=tf.int32)
    c = a + b
    return tf.nn.relu(x + c)


def condition(x):
    x = tf.Print(x, [x])
    return tf.logical_or(tf.less(tf.reduce_sum(x), 1000), tf.equal(x[0, 0], 15))


x = tf.Variable(tf.constant(0, shape=[2, 2]))
result = tf.while_loop(condition, body, [x])

init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    print(sess.run(result))