为什么tf.cond中的false_fn从未调用过?

时间:2018-07-30 02:59:43

标签: tensorflow

tf.while_looptf.cond一起使用是很容易的。为什么错误条件从未得到满足?

i0 = tf.constant(1)
m0 = tf.zeros([1, 2], dtype=tf.int32)
first_set = tf.Variable(True, dtype=tf.bool)

def cond_true_fn(i, m):
    global first_set
    first_set = tf.assign(first_set, False)
    return [i + 1, tf.concat([m, [[6, 6]]], axis=0)]


def cond_false_fn(i, m):
    return [i + 1, tf.concat([m, [[3, 3]]], axis=0)]


def body(i, m):
    return tf.cond(first_set, lambda:cond_true_fn(i,m), lambda:cond_false_fn(i,m))

def condi(i, m):
    return tf.less_equal(i, 3)

_, r = tf.while_loop(condi, body, loop_vars=[i0, m0], shape_invariants=[i0.get_shape(), tf.TensorShape([None, 2])], back_prop=False)

with tf.Session() as sess:
    tf.global_variables_initializer().run()
    _r = sess.run([r])
    print(_r)

它总是处于真实状态。给我意外的结果,如下所示: [[0, 0], [6, 6], [6, 6], [6, 6]]

1 个答案:

答案 0 :(得分:0)

i0 = tf.constant(1)
m0 = tf.zeros([1, 2], dtype=tf.int32)
f0 = tf.constant(True)
def cond_true_fn(i, m):
    return [i + 1, tf.concat([m, [[6, 6]]], axis=0), False]


def cond_false_fn(i, m):
    return [i + 1, tf.concat([m, [[3, 3]]], axis=0), False]


def body(i, m, f):
    return tf.cond(f, lambda:cond_true_fn(i,m), lambda:cond_false_fn(i,m))

def condi(i, m, f):
    return tf.less_equal(i, 3)

_, r = tf.while_loop(condi, body, loop_vars=[i0, m0, f0], shape_invariants=[i0.get_shape(), tf.TensorShape([None, 2]), f0.get_shape()], back_prop=False)

with tf.Session() as sess:
    tf.global_variables_initializer().run()
    _r = sess.run([r])
    print(_r)

这有效!但是为什么?