tensorflow 会话运行张量列表的顺序是什么? [英] What is the sequence for tensorflow's session to run a list of tensors?

查看:26
本文介绍了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

它们取决于求值顺序,对于第一种情况,xop 之前求值,对于第二种情况,xop 之后求值.

They depend on the order of evaluation, for the first case, x is evaluated before op, and for the second case, x is evaluated after op.

我已经多次运行代码,但结果总是x=2 and op=2.所以我猜 tensorflow 可以保证 xop 之后被评估.这样对吗?而tensorflow是如何保证依赖的?

I have run the code many times, but the result is always x=2 and op=2. So I guess that tensorflow can guarantee x is evaluated after op. Is it right? And how does tensorflow guarantee the dependence?

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

For the case above, the result is determinate. But in the follow case, the result is not determinate.

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]))

在第一个代码中,xVariableop依赖于x,所以x 总是在 op 之后计算.但是在第二种情况下,x变成了Tensor,而op依赖于变量x(x之后= x + 0,x 被覆盖).所以 op 不依赖于 Tensor x.

In the first code, x is Variable and op depends on x, so x is always evaluated after op. But in the second case, x becomes Tensor, and op depend on Variable x(After x = x + 0, x is overrided). So the op doesn't depend on Tensor x.

推荐答案

张量的计算顺序未定义.请参阅 API 文档(朝向最底部,在返回Session.run() 上的信息).因此,您不应依赖它们以特定顺序执行.如果您需要保证订单,您可能应该对不同的张量/操作使用单独的 run 调用.

The order in which tensors are evaluated is undefined. See the API docs (towards, the very bottom, in the "Returns" info on Session.run()). As such, you should not rely on them being executed in a particular order. If you need to guarantee an order you should probably use separate run calls for the different tensors/ops.

这篇关于tensorflow 会话运行张量列表的顺序是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆