我运行一段代码两次得到两个不同的结果
代码:
import tensorflow as tf
x = tf.placeholder(tf.int32, shape=[], name='x')
y = tf.Variable(2, dtype=tf.int32)
assign_op = tf.assign(y, y + 1)
out = x * y
with tf.control_dependencies([assign_op]):
out_ = out+2
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(3):
print('output:', sess.run(out_, feed_dict={x: 1}))
第一个输出:
output: 4
output: 5
output: 6
第二个输出:
output: 4
output: 6
output: 6
谁能解释一下为什么会这样?
最佳答案
Tensorflow 不会像在普通 Python 程序中那样记录操作的创建顺序,而只会跟踪它们的依赖关系,因此只能保证 operation/op
的所有依赖关系在 之前执行code>op
执行。
所以在某些情况下,out_
可能会在更新 y
的值之后更新,而在其他情况下,它会在更新 y
之前执行因为 out_
仅对 y
具有传递依赖性。即它取决于 y
通过 out
变量。
关于tensorflow - 使用 tf.control_dependencies 的相同代码的不同结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58607510/