sess.run() and “.eval()” in tensorflow programming

ⅰ亾dé卋堺 提交于 2021-01-28 12:12:11

问题


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?


回答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.0
  print(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.0
print(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()



来源:https://stackoverflow.com/questions/58888215/sess-run-and-eval-in-tensorflow-programming

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!