Abhishek Bhatia
Abhishek Bhatia

Reputation: 9806

Is necessary to use to both eval and run?

I understood the difference between the two from this answer. But in most talks/code online I find people using both as below:

import tensorflow as tf
a=tf.constant(5.0)
b=tf.constant(6.0)
c=a*b
with tf.Session() as sess:
    print(sess.run(c))
    print(c.eval())

I don't understand the need and utility for doing so.

Upvotes: 1

Views: 261

Answers (2)

Uvuvwevwevwe
Uvuvwevwevwe

Reputation: 1041

The quick answer to your question is NO.

You just need either Session.run() or Tensor.eval() to evaluate the value of a tensor object. People usually use Tensor.eval() to experiment the programming model, namely print out the value of tensors to track the flow! For example,

import tensorflow as tf

a = tf.constant([1, 2], name='a')
b = tf.constant([3, 4], name='b')
c = tf.constant([1, 3], name='c')

d = tf.add_n([a, b])
e = tf.pow(d, c)

printout_d = tf.Print(d, [a, b, d], 'Input for d and the result: ')
printout_e = tf.Print(e, [d, c, e], 'Input for e and the result: ')

with tf.Session() as sess:
    sess.run([d, e])
    printout_d.eval()
    printout_e.eval()

In the above code, you can simply need sess.run([d, e]) to execute the graph. But, in some cases, for example debugging, you can benefit from printout_d.eval() and printout_e.eval().

Upvotes: 0

nessuno
nessuno

Reputation: 27042

Calling sess.run(c) and c.eval(), in the same session, provide exactly the same results.

You can mix calls to sess.run and <tensor>.eval() in the code, but it makes your code less consistent.

In my opinion, it's better to use always sess.run, beacuse within a single call you can evaluate more then one tensor.

Instead, if you use <tensor>.eval() you can evaluate only the specified <tensor>.

You can see the performance differences running this script:

import time
import tensorflow as tf

a=tf.constant(5.0)
b=tf.constant(6.0)
c=a*b

start = time.time()
with tf.Session() as sess:
    sess.run([c]*100)
end_run = time.time() - start

start = time.time()
with tf.Session() as sess:
    for _ in range(100):
        c.eval()
end_eval = time.time() - start

print('Run: {}\nEval: {}'.format(end_run, end_eval))

Running it with Tensorflow r0.11, on CPU (Intel i3) it gives this result:

Run: 0.009401798248291016
Eval: 0.021142005920410156

As you can see, the execution of a sess.run call with a list of 100 elements is much fast then the execution of 100 c.eval() calls.

In fact, Tensorflow evaluates only once the c tensor in the sess.run call, and reuse the result to do other computation if needed.

Upvotes: 4

Related Questions