tensorflow - 为什么 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]]
解决方案
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?
推荐阅读
- validation - 将数据验证的 sourceRange 设置为值数组
- sql-server - 我无法在 SQL Server 2008R2 中执行包含链接服务器数据的作业?
- javascript - FS 写入文件破坏了我的 json,如何正确更新一个键?
- c# - 从调度程序继续 foreach 循环
- .net - MVC Razor - 使这个 html.Partial 动态的标准做法是什么
- amazon-web-services - AWS 公有子网 VPC 通信
- php - PHP-FPM 未在 OS X Mojave 下的 Nginx 上运行
- php - 从 laravel 的不同表中获取每个 id 的总数
- botframework - 将此消息发送到您的机器人时出错:HTTP 状态代码已禁止
- reactjs - React 中的 404 页面在每个页面中呈现