ref: https://stackoverflow.com/questions/53165418/order-of-sess-runop1-op2-in-tensorflow
-
一次sess.run() 更新一次图。与写fetch_list的顺序无关
-
对于数值多次变化存在于多条分支的情况,数值的更新顺序可能不同(跟实际执行时间有关),例如
import tensorflow as tf
v = tf.Variable(0)
v2 = 2 * v
v_update = v.assign(v + 1)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for i in range(5):
print(sess.run([v_update, v2]))
这段代码可能输出为:
[1, 0]
[2, 2]
[3, 4]
[4, 8]
[5, 10]
v2与v的更新时刻在图中可能有差异,导致歧义
- 针对上面这种情况,可以增加依赖关系,指定更新顺序
import tensorflow as tf
v = tf.Variable(0)
v2 = 2 * v
with tf.control_dependencies([v2]):
v_update = v.assign(v + 1)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for i in range(5):
print(sess.run([v_update, v2]))
这里使用tf.control_dependencies指明v_update 的更新在 v2之后, 就不会产生歧义,输出为:
[1, 0]
[2, 2]
[3, 4]
[4, 6]
[5, 8]