The FAQ session on tensor flow has an answer to exactly the same question. I will just go ahead and leave it here:
If t
is a Tensor
object, t.eval()
is shorthand for sess.run(t)
(where sess
is the current default session. The two following snippets of code are equivalent:
sess = tf.Session()
c = tf.constant(5.0)
print sess.run(c)
c = tf.constant(5.0)
with tf.Session():
print c.eval()
In the second example, the session acts as a context manager, which has the effect of installing it as the default session for the lifetime of the with
block. The context manager approach can lead to more concise code for simple use cases (like unit tests); if your code deals with multiple graphs and sessions, it may be more straightforward to explicit calls to Session.run()
.
I'd recommend that you at least skim throughout the whole FAQ, as it might clarify a lot of things.