问题:在TensorFlow中,Session.run()和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?


回答 0

如果您有Tensort,则调用t.eval()等效于tf.get_default_session().run(t)

您可以将会话设置为默认会话,如下所示:

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()在同一步骤中用来获取许多张量的值:

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

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

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)

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

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.


回答 1

关于张量流的FAQ会话对完全相同的问题有一个答案。我将继续并将其留在这里:


如果tTensor对象,t.eval()则为的简写形式sess.run(t)sess当前的默认会话在哪里。以下两个代码段是等效的:

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

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

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

我建议您至少在整个FAQ中略读一遍,因为它可能会阐明很多事情。

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


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

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 with block. 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().

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


回答 2

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())

但是Session.run()可以

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

如果我错了请纠正我

eval() can not handle the list object

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

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

correct me if I am wrong


回答 3

要记住的最重要的事情:

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

知道这一切很容易

两者tf.Session.run()tf.Tensor.eval()从会话中获取结果,这tf.Tensor.eval()是调用的快捷方式tf.get_default_session().run(t)


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

在会话中启动图形后,可以通过将操作传递到来执行操作tf.Session.run()op.run()是呼叫的捷径tf.get_default_session().run(op)

The most important thing to remember:

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

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)


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

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).


回答 4

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

tf.Session()

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

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

tf.get_default_session().run(values)

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

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

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.

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.

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

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.

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


回答 5

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

!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

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

!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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。