0
假設True和False情況下存在單獨的相關性:圖形依賴關係如何與`tf.cond`配合使用?
tensorflow是否假定兩個依賴項都是必需的,因此會處理True和False情況下的完整子圖?或者它:
- 工藝布爾表達式的依賴關係,然後
- 過程的依賴關係無論是真正的異或
tf.cond(...)
的虛假的一面呢?
假設True和False情況下存在單獨的相關性:圖形依賴關係如何與`tf.cond`配合使用?
tensorflow是否假定兩個依賴項都是必需的,因此會處理True和False情況下的完整子圖?或者它:
tf.cond(...)
的虛假的一面呢?的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"
不過請注意,您必須確保任何副作用的運算定義內的lambda
(或等價的功能),你傳遞給tf.cond()
。如果副作用的OPS被外界的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"
感謝您的澄清和謹慎。 lambda內部是一個命令,用於從一個隊列中取出隊列樣本或從另一個隊列中取出隊列樣本,我只是傳入一個布爾值佔位符來告訴它哪一個,當然不希望兩個隊列都發生。 –
@DavidParks如果你想深入瞭解,你可以看看「Switch/Merge」是如何工作的。這些是通過'tf.cond'添加的,但是您也可以通過插入這些語句來執行圖形的某些部分,這裏是一個示例 - https://gist.github.com/yaroslavvb/d67410e240369736fc4ba0267250ef27合併邏輯的描述是這裏 - https://github.com/tensorflow/tensorflow/blob/01daba61e3a5099c6ad6439fa47e30c71560f06b/tensorflow/core/common_runtime/executor.cc#L2391 –