简体   繁体   中英

The difference between sess.run(c) and c.eval() in Tensorflow

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

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 Tensor s. But Operation s 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM