# In TensorFlow, what is the difference between Session.run() and Tensor.eval() ?

In TensorFlow, what is the difference between Session.run() and Tensor.eval() ?

When you had a Tensor t, calling t.eval() is identical to calling tf.get_default_session().run(t).

t = tf.constant(42.0)
sess = tf.Session()
with sess.as_default(): # or with sess: to close on exit
assert sess is tf.get_default_session()
assert t.eval() == sess.run(t)


Main difference is that you can utilize sess.run() to fetch the value of a large tensor in a similar step:

t = tf.constant(42.0)
u = tf.constant(37.0)
tu = tf.mul(t, u)
ut = tf.mul(u, t)
with sess.as_default():
tu.eval() # runs one step
ut.eval() # runs one step
sess.run([tu, ut]) # evaluates both tensors in a single step


On the off chance that t is a Tensor object, t.eval() is shorthand for sess.run(t).

sess = tf.Session()
c = tf.constant(5.0)
print sess.run(c)

c = tf.constant(5.0)
with tf.Session():
print c.eval()


When your code manages various graphs and sessions, it might be more clear to explicit calls to Session.run().

In Tensorflow, eval() are not able to handle the list object

tf.reset_default_graph()
a = tf.Variable(0.2, name="a")
b = tf.Variable(0.3, name="b")
z = tf.constant(0.0, name="z0")
for i in range(100):
z = a * tf.cos(z + i) + z * tf.sin(b - i)
init = tf.global_variables_initializer()
with tf.Session() as sess:
init.run()
print("z:", z.eval())


but Session.run() can handle it

print("grad", sess.run(grad))