我试图理解张量流图中的执行顺序。当我运行以下代码时。 testDelegate
打印不确定的结果。
tf.print
这里是20次重复的输出。有时,它打印“ msg1:3”,有时,它打印“ msg1:1”。那么这是怎么回事?
import tensorflow as tf
for _ in range(20):
tf.reset_default_graph()
use_resource = False
v = tf.Variable(0, trainable=False, use_resource=use_resource, name='v')
v_op1 = v.assign_add(1, name='v_op1')
v_op2 = v.assign_add(2, name='v_op2')
with tf.control_dependencies([v_op1]):
w1 = tf.print('msg1:', v, name='v--w')
with tf.control_dependencies([w1, v_op2]):
w2 = tf.print('msg2:', v, '\n', name='w--w')
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
sess.run(w2)
答案 0 :(得分:0)
我认为正在发生的事情是您正在创建w1和v_op2之间的竞争,并且它们都同时执行。 (包含论文行)
with tf.control_dependencies([w1, v_op2]):
例如,如果v_op2在w1之前执行,然后将2添加到v
,然后在执行w1时将其添加1,从而使msg_1打印3。但是,如果能够在执行v_op2之前完成w1,则2之后被添加到v
。
例如情况1
v_op2 executed:
v = 2
w1 executed:
v = 3
print(v)
案例2
w1 executed
v = 1
print(v)
v_op2 executed
v=3