【发布时间】:2017-04-04 02:29:48
【问题描述】:
假设 True 和 False 的情况都有独立的依赖关系:
tensorflow 是否假设两个依赖项都是必需的,从而处理 True 和 False 情况的完整子图?还是这样做:
- 处理布尔表达式的依赖关系,然后
- 处理
tf.cond(...)的 True x 或 False 端的依赖关系?
【问题讨论】:
标签: tensorflow
假设 True 和 False 的情况都有独立的依赖关系:
tensorflow 是否假设两个依赖项都是必需的,从而处理 True 和 False 情况的完整子图?还是这样做:
tf.cond(...) 的 True x 或 False 端的依赖关系?【问题讨论】:
标签: tensorflow
tf.cond() 函数旨在只执行一个真或假分支,在评估布尔表达式之后。例如,如果您编写了如下内容:
v = tf.Variable(0)
condition = tf.placeholder(tf.bool, shape=[])
op_to_run = tf.cond(condition, lambda: v.assign_add(1), lambda: v.assign_sub(1))
sess = tf.Session()
sess.run(tf.global_variables_initializer())
print(sess.run(v)) # ==> "0"
for _ in range(3):
sess.run(op_to_run, feed_dict={condition: True})
print(sess.run(v)) # ==> "3"
for _ in range(5):
sess.run(op_to_run, feed_dict={condition: False})
print(sess.run(v)) # ==> "-2"
但是请注意,您必须确保在传递给tf.cond() 的lambda(或等效的函数)内部定义了任何副作用操作。如果副作用操作定义在外部tf.cond(),它们将无条件执行:
v = tf.Variable(0)
condition = tf.placeholder(tf.bool, shape=[])
# N.B. DO NOT DO THIS! Both side-effecting ops are defined outside the `tf.cond()`
# so they will both execute, regardless of the condition.
inc_op = v.assign_add(1)
dec_op = v.assign_sub(1)
op_to_run = tf.cond(condition, lambda: inc_op, lambda: dec_op)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
print(sess.run(v)) # ==> "0"
# Both the `assign_add()` and `assign_sub()` will run, cancelling each other out.
for _ in range(3):
sess.run(op_to_run, feed_dict={condition: True})
print(sess.run(v)) # ==> "0"
# Both the `assign_add()` and `assign_sub()` will run, cancelling each other out.
for _ in range(5):
sess.run(op_to_run, feed_dict={condition: False})
print(sess.run(v)) # ==> "0"
【讨论】:
dequeue 样本或从另一个队列中获取 dequeue 样本,我只是传入一个布尔占位符来告诉它哪个,当然不希望两者都发生。跨度>
tf.cond 添加的,但您也可以通过插入这些语句来有条件地执行图形的某些部分,这是一个示例 -- gist.github.com/yaroslavvb/d67410e240369736fc4ba0267250ef27 合并逻辑的描述在这里 -- github.com/tensorflow/tensorflow/blob/…