最近在學習 tensorflow MNIST 程序時遇到了 tensorflow tf.control_dependencies()
栖秕,具體為:
......
variables_averages_op = variable_averages.apply(tf.trainable_variables()) # apply --vars--> average_op
......
# 優(yōu)化損失函數(shù)
train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)
with tf.control_dependencies([train_step, variables_averages_op]): # 依賴環(huán)境
train_op = tf.no_op(name='train') # here, train_op will only run after [**] have executed.
有人說:
with g.control_dependencies([a, b, c]): # 這會保證 a, b, c 按順序執(zhí)行
# d will only run after a, b and c have executed.
d = ...
事實上嫩与,a蜂桶,b儡毕,c 不會按 [*] 里的順序執(zhí)行。下面看一些實驗扑媚。
import tensorflow as tf
a = tf.Variable(1.0)
c = tf.assign(a, 2.0) # 注意這里 c 和 d 的順序
d = tf.assign(a, 3.0) # c --> d 是 c 在前, 如果 d --> c, 則是 d 在前
with tf.control_dependencies([c, d]): # 看一看 c腰湾,d 的執(zhí)行順序
op = tf.assign_add(a, 6.0) # 后執(zhí)行的將決定 a 的取值
with tf.Session() as sess:
tf.global_variables_initializer().run()
print(sess.run(op))
實驗結果:
- c --> d && [c, d] ==> op == 9.0,說明 a 取值為 3疆股,d 后執(zhí)行
- c --> d && [d, c] ==> op == 9.0费坊,說明 a 取值為 3,d 后執(zhí)行
- d --> c && [c, d] ==> op == 8.0旬痹,說明 a 取值為 2附井,c 后執(zhí)行
- d --> c && [d, c] ==> op == 8.0讨越,說明 a 取值為 2,c 后執(zhí)行
=>結論1:[c, d] 或 [d, c] 順序沒有影響, 實際執(zhí)行順序是由 (c --> d) || (d --> c) 決定
- c --> d && [c] ==> op == 8.0
- c --> d && [d] ==> op == 9.0
=>結論2:只執(zhí)行了 [*] 中的操作, 不在其中的不會執(zhí)行