tensorflow - 使用 tf.control_dependencies 的相同代码的不同结果

标签 tensorflow variables session

我运行一段代码两次得到两个不同的结果

代码:

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/

相关文章:

python - tensorflow MNIST : terminate called after throwing an instance of 'std::bad_alloc'

未在新 session 上设置 MySQL 查询变量

python - 从 web 服务器日志中免费实现用户 session 计数?

python - 带有网络服务器的 Flask 会中断所有 session 吗?

javascript - 在两个 Javascript/Jquery 函数之间传递 var?

java - Spring添加web.xml配置时Session总是过期

python - 为 CNN(音频识别)转换 MFCC 频谱图的输入

python - 连接时间序列神经网络和前馈神经网络

python - 如何允许文本输入到 TensorFlow 模型?

Python,字符串(由变量和字符串组成,连接)用作新变量名?