Sess.run() And ".eval()" In Tensorflow Programming
In Tensorflow programming, can someone please tell what is the difference between '.eval()' and 'sess.run()'. What do each of them do and when to use them?
Solution 1:
A session
object encapsulates the environment in which Tensor objects are evaluated.
If x
is a tf.Tensor
object, tf.Tensor.eval
is shorthand for tf.Session.run
, where sess
is the current tf.get_default_session
.
You can make session the default as below
x = tf.constant(5.0)
y = tf.constant(6.0)
z = x * y
with tf.Session() as sess:
print(sess.run(z)) # 30.0print(z.eval()) # 30.0
The most important difference is you can use sess.run
to fetch the values of many tensors in the same step as below
print(sess.run([x,y])) # [5.0, 6.0]print(sess.run(z)) # 30.0
Where as eval
fetch single tensor value at a time as below
print(x.eval()) # 5.0print(z.eval()) # 3.0
TensorFlow computations define a computation graph that has no numerical value until evaluated as below
print(x) # Tensor("Const_1:0", shape=(), dtype=float32)
In Tensorflow 2.x (>= 2.0)
, You can use tf.compat.v1.Session()
instead of tf.session()
Post a Comment for "Sess.run() And ".eval()" In Tensorflow Programming"