首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么tf.cond中的false_fn从不调用?

为什么tf.cond中的false_fn从不调用?
EN

Stack Overflow用户
提问于 2018-07-30 10:59:43
回答 1查看 48关注 0票数 0

同时使用tf.while_looptf.cond是如此紧密相连。为什么错误的条件从未满足?

代码语言:javascript
复制
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]]

EN

回答 1

Stack Overflow用户

发布于 2018-07-30 15:38:08

代码语言:javascript
复制
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)

这行得通!但是为什么呢?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51586459

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档