首页 > 解决方案 > 为什么 tf.cond 中的 false_fn 从未调用过?

问题描述

它是如此连接tf.while_loop在一起使用tf.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]]

标签: tensorflow

解决方案


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)

This works! but WHY?


推荐阅读