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

Is it possible to have multiple conditions defined in tf.while_loop

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

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

tf.while_loop 接受必须 return 布尔张量的通用可调用函数(python 用 def 定义的函数)或 lambdas。

因此,您可以使用 logical operators 在条件主体内链接多个条件,例如 tf.logical_andtf.logical_or、...

甚至 body 也是一个通用的 python 可调用函数,因此您不限于 lambda 和单语句函数。

类似的东西完全可以接受并且效果很好:

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))