猿问

tensorflow 会话运行张量列表的顺序是什么?

查看代码片段:


import tensorflow as tf


x = tf.Variable(1)

op = tf.assign(x, x + 1)


with tf.Session() as sess:

  tf.global_variables_initializer().run()

  print(sess.run([x, op]))

有两种可能的结果:


x=1 和 op=2

x=2 和 op=2

它们取决于评估的顺序,对于第一种情况,x在 之前评估op,对于第二种情况,x在 之后评估op。


我已经多次运行代码,但结果总是x=2 and op=2. 所以我想tensorflow可以保证x在op. 这样对吗?以及如何tensorflow保证依赖?


更新

对于上述情况,结果是确定的。但在以下情况下,结果是不确定的。


import tensorflow as tf


x = tf.Variable(1)

op = tf.assign(x, x + 1)

x = x + 0                   # add this line


with tf.Session() as sess:

  tf.global_variables_initializer().run()

  for i in range(5):

    print(sess.run([x, op]))

在第一个代码中,xisVariable并且op取决于x,所以x总是在 之后求值op。但在第二种情况下,x变成Tensor,并且op依赖于Variable x(After x = x + 0, x is override)。所以op不依赖于Tensor x.


慕桂英4014372
浏览 222回答 2
2回答

蝴蝶不菲

这有效:with tf.device('/cpu:0'):    # x = tf.get_variable('x', shape=(), initializer=tf.constant_initializer(1), dtype=tf.int32)    x = tf.Variable(1)    op = tf.assign(x, x+1)    with tf.control_dependencies([op]):        x = x + 0        # x = tf.multiply(x, 3)        # x = tf.add(x, 0)但不总是:with tf.device('/cpu:0'):    # x = tf.get_variable('x', shape=(), initializer=tf.constant_initializer(1), dtype=tf.int32)    x = tf.Variable(1)with tf.device('/gpu:0'):  # add this line.    op = tf.assign(x, x+1)    with tf.control_dependencies([op]):        x = x + 0        # x = tf.multiply(x, 3)        # x = tf.add(x, 0)我认为问题出在:某些操作(例如x = x + 0,从读取值Variable然后添加 0)取决于 的值Variable,而Variable由某些分配操作(例如 op = tf.assign(x, x+1))改变。如果没有依赖,这两个操作是并行的。所以在读取 的值时Variable,不确定是否assign已经完成。从不同设备传输数据。即使存在依赖关系,它仍然是不确定的。简而言之,如果所有变量和操作都在同一个设备中,那么with tf.control_dependencies 应该保证op在添加操作之前。注意:(以下这些注释并不重要,但可能对您有所帮助)tf.assign操作只更新Variable,不更新Tensor。当你这样做时x=x+0,新的x变成了Tensor;但op = tf.assign(x, x+1)返回Variable. 所以op应该始终是确定的,因为它取决于Variable不会被其他操作改变的当前值。GPU 不支持 int32 变量。当我在我的机器 (tf-gpu1.12) 上运行你的代码片段时,变量是在 CPU 上创建的,但操作是在 GPU 上完成的。您可以通过config = tf.ConfigProto(log_device_placement=True).
随时随地看视频慕课网APP

相关分类

Python
我要回答