在 TensorFlow 中,Session.run() 和 Tensor.eval() 有什么区别? [英] In TensorFlow, what is the difference between Session.run() and Tensor.eval()?
问题描述
TensorFlow 有两种方法来评估图的一部分:Session.run
在变量列表上和 Tensor.eval
.这两者有区别吗?
TensorFlow has two ways to evaluate part of graph: Session.run
on a list of variables and Tensor.eval
. Is there a difference between these two?
推荐答案
如果你有一个 Tensor
t,调用 t.eval()
相当于调用 tf.get_default_session().run(t)
.
If you have a Tensor
t, calling t.eval()
is equivalent to calling tf.get_default_session().run(t)
.
您可以将会话设为默认值,如下所示:
You can make a session the default as follows:
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)
最重要的区别是您可以使用 sess.run()
在同一步骤中获取许多张量的值:
The most important difference is that you can use sess.run()
to fetch the values of many tensors in the same 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
请注意,每次调用 eval
和 run
都会从头开始执行整个图.要缓存计算结果,请将其分配给 tf.Variable
一>.
Note that each call to eval
and run
will execute the whole graph from scratch. To cache the result of a computation, assign it to a tf.Variable
.
这篇关于在 TensorFlow 中,Session.run() 和 Tensor.eval() 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!