Python 在 TensorFlow 中,Session.run() 和 Tensor.eval() 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33610685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:37:01  来源:igfitidea点击:

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

pythontensorflow

提问by Geoffrey Irving

TensorFlow has two ways to evaluate part of graph: Session.runon a list of variables and Tensor.eval. Is there a difference between these two?

TensorFlow 有两种方法来评估图的一部分:Session.run在变量列表上和Tensor.eval. 这两者有区别吗?

采纳答案by mrry

If you have a Tensort, calling t.eval()is equivalent to calling tf.get_default_session().run(t).

如果您有Tensort,则调用t.eval()等效于调用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)

The most important difference is that you can use sess.run()to fetch the values of many tensors in the same step:

最重要的区别是您可以使用sess.run()在同一步骤中获取许多张量的值:

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

Note that each call to evaland runwill execute the whole graph from scratch. To cache the result of a computation, assign it to a tf.Variable.

请注意,每次调用evalrun都会从头开始执行整个图。要缓存计算结果,请将其分配给tf.Variable.

回答by Salvador Dali

The FAQ session on tensor flow has an answer to exactly the same question. I will just go ahead and leave it here:

张量流的常见问题解答会话有完全相同的问题答案。我会继续把它留在这里:



If tis a Tensorobject, t.eval()is shorthand for sess.run(t)(where sessis the current default session. The two following snippets of code are equivalent:

Ift是一个Tensor对象,t.eval()sess.run(t)(where sessis the current default session. 的简写。以下两个代码片段是等效的:

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

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

In the second example, the session acts as a context manager, which has the effect of installing it as the default session for the lifetime of the withblock. The context manager approach can lead to more concise code for simple use cases (like unit tests); if your code deals with multiple graphs and sessions, it may be more straightforward to explicit calls to Session.run().

在第二个示例中,会话充当上下文管理器,其作用是将其安装为with块生命周期的默认会话。上下文管理器方法可以为简单的用例(如单元测试)生成更简洁的代码;如果您的代码处理多个图形和会话,则显式调用Session.run().

I'd recommend that you at least skim throughout the whole FAQ, as it might clarify a lot of things.

我建议您至少浏览整个常见问题解答,因为它可能会澄清很多事情。

回答by Yushin Liu

eval()can not handle the list object

eval()无法处理列表对象

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)
grad = tf.gradients(z, [a, b])

init = tf.global_variables_initializer()

with tf.Session() as sess:
    init.run()
    print("z:", z.eval())
    print("grad", grad.eval())

but Session.run()can

Session.run()可以

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

correct me if I am wrong

如果我错了,请纠正我

回答by Sudeep K Rana

In tensorflow you create graphs and pass values to that graph. Graph does all the hardwork and generate the output based on the configuration that you have made in the graph. Now When you pass values to the graph then first you need to create a tensorflow session.

在 tensorflow 中,您可以创建图形并将值传递给该图形。Graph 完成所有工作并根据您在图中所做的配置生成输出。现在,当您将值传递给图形时,首先您需要创建一个 tensorflow 会话。

tf.Session()

Once session is initialized then you are supposed to use that session because all the variables and settings are now part of the session. So, there are two ways to pass external values to the graph so that graph accepts them. One is to call the .run() while you are using the session being executed.

会话初始化后,您应该使用该会话,因为所有变量和设置现在都是会话的一部分。因此,有两种方法可以将外部值传递给图形,以便图形接受它们。一种是在使用正在执行的会话时调用 .run() 。

Other way which is basically a shortcut to this is to use .eval(). I said shortcut because the full form of .eval() is

其他基本上是一种快捷方式的方法是使用 .eval()。我说捷径是因为 .eval() 的完整形式是

tf.get_default_session().run(values)

You can check that yourself. At the place of values.eval()run tf.get_default_session().run(values). You must get the same behavior.

你可以自己检查一下。在values.eval()run的地方tf.get_default_session().run(values)。你必须得到相同的行为。

what eval is doing is using the default session and then executing run().

eval 所做的是使用默认会话,然后执行 run()。

回答by prosti

The most important thing to remember:

要记住的最重要的事情:

The only way to get a constant, variable (any result) from TenorFlow is the session.

从 TenorFlow 获取常量、变量(任何结果)的唯一方法是会话。

Knowing this everything else is easy:

了解这一点很容易

Both tf.Session.run()and tf.Tensor.eval()get results from the session where tf.Tensor.eval()is a shortcut for calling tf.get_default_session().run(t)

双方tf.Session.run()tf.Tensor.eval()得到其中会话结果tf.Tensor.eval()是通话功能的快捷方式tf.get_default_session().run(t)



I would also outline the method tf.Operation.run()as in here:

我也将概述该方法tf.Operation.run()这里

After the graph has been launched in a session, an Operation can be executed by passing it to tf.Session.run(). op.run()is a shortcut for calling tf.get_default_session().run(op).

在会话中启动图形后,可以通过将其传递给 来执行操作tf.Session.run()op.run()是调用的快捷方式tf.get_default_session().run(op)

回答by Tensorflow Support

Tensorflow 2.x Compatible Answer: Converting mrry's code to Tensorflow 2.x (>= 2.0)for the benefit of the community.

Tensorflow 2.x 兼容答案Tensorflow 2.x (>= 2.0)为了社区的利益,将mrry 的代码转换为。

!pip install tensorflow==2.1
import tensorflow as tf

tf.compat.v1.disable_eager_execution()    

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

#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.multiply(t, u)
ut = tf.multiply(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