1

When printing out the value of the node "c" in the following example, to me, it seems that there's no difference between print sess.run(c) and print c.eval(). Can I assume that sess.run(c) and c.eval() are equivalent? Or are there any differences?

import tensorflow as tf

a = tf.Variable(2.0, name="a")
b = tf.Variable(3.0, name="b")
c = tf.add(a, b, name="add")
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print sess.run(c)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print c.eval()
P-Gn
  • 23,115
  • 9
  • 87
  • 104
chanwcom
  • 4,420
  • 8
  • 37
  • 49
  • Possible duplicate of [In TensorFlow, what is the difference between Session.run() and Tensor.eval()?](https://stackoverflow.com/questions/33610685/in-tensorflow-what-is-the-difference-between-session-run-and-tensor-eval) – Vijay Mariappan May 29 '18 at 07:20

1 Answers1

2

When you call c.eval() on a tensor, you are basically calling tf.get_default_session().run(c). It is a convenient shortcut.

However, Session.run() is much more general.

  1. It allows you to query several outputs at once: sess.run([a, b, ...]). When those outputs are related and depend on a state that may change, it is important to get them simultaneously to have a consistent result. People are regularly surprised by this [1], [2].
  2. Session.run() can take a few parameters that Tensor.eval() does not have, such as RunOptions, that can be useful for debugging or profiling.
    • Note however that eval() can take a feed_dict.
  3. eval() is a property of Tensors. But Operations such as global_variables_initializer() on the other hand do not have an eval() but a run() (another convenient shortcut). Session.run() can run both.
P-Gn
  • 23,115
  • 9
  • 87
  • 104
  • And most importantly `sess.run` can handle a list compared to `.eval()` which causes [some trouble](https://stackoverflow.com/questions/50177766/official-zeroout-gradient-example-error-attributeerror-list-object-has-no-at/50177935#50177935) – Patwie May 29 '18 at 08:09