Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the sequence for tensorflow's session to run a list of tensors?

See the code snippet:

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

There are two possible results:

  • x=1 and op=2
  • x=2 and op=2

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.

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?

Update

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

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.

like image 423
gaussclb Avatar asked Dec 11 '18 13:12

gaussclb


People also ask

What is a TensorFlow session?

TensorFlow Session is a session object which encapsulates the environment in which Operation objects are executed, and data objects are evaluated. TensorFlow requires a session to execute an operation and retrieve its calculated value. A session may own several resources, for example, tf. QueueBase, tf.

What is TensorFlow how many types of tensors are there?

Each operation you will do with TensorFlow involves the manipulation of a tensor. There are four main tensor type you can create: tf.

How do you declare a tensor in Python?

Method #1: Creating tensor using the constant() function. The most popular function for creating tensors in Tensorflow is the constant() function. We need to give values or list of values as argument for creating tensor. If the values given are of type integer, then int32 is the default data type.


1 Answers

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.

like image 87
xdurch0 Avatar answered Sep 26 '22 01:09

xdurch0