我无法理解Tensorflow系统。 首先,我写了
#coding:UTF-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
const1 = tf.constant(2)
const2 = tf.constant(3)
add_op = tf.add(const1,const2)
with tf.Session() as sess:
result = sess.run(add_op)
print(result)
并打印5。 其次,我写了
#coding:UTF-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
const1 = tf.constant(2)
const2 = tf.constant(3)
add_op = tf.add(const1,const2)
print(add_op)
并打印出Tensor(“Add:0”,shape =(),dtype = int32)。
我无法理解这个系统。
我使用Python和其他语言,所以我认为tf.add()
方法是add方法。但是,在Tensorflow的情况下,它似乎有所不同。
为什么这部分
with tf.Session() as sess:
result = sess.run(add_op)
print(result)
必要? 这部分有什么功能?
答案 0 :(得分:2)
我建议阅读TensorFlow的官方Getting Started with TensorFlow指南,以了解该库的核心概念,例如这里似乎存在的问题:
每个TensorFlow程序由两部分组成:
现在,什么是“计算图”?在TensorFlow中,您可以指定在输入上执行的一系列操作。这一系列操作是您的“计算图”。要理解这一点,让我们看一些例子:
简单补充:让我们看看你的例子,你的代码是
const1 = tf.constant(2)
const2 = tf.constant(3)
add_op = tf.add(const1,const2)
这会在图形中创建两个常量节点,并创建第二个添加它们的节点。从图形上看,这看起来像:
为了使它更复杂一点,我们假设你有一个输入x
,并希望为它添加一个常量3
。然后你的代码将是:
const1 = tf.constant(2)
x = tf.placeholder(tf.float32)
add_op = tf.add(const1,x)
,您的图表是
在这两个示例中,这是程序的第一部分。到目前为止,我们只定义了计算图应该如何看,即我们有什么输入,输出什么,以及所需的所有计算。
但是:到目前为止还没有进行任何计算!在第二个示例中,您甚至不知道输入x
是什么 - 只是它将是{{1 }}。
如果你有GPU,你会发现TensorFlow还没有触及GPU。即使你有一个拥有数百万个训练图像的巨大神经网络,这个步骤也会在几毫秒内完成,因为不需要进行“真正的”工作。
现在是第二部分:正在运行我们在上面定义的图表。这是工作的地方!
我们通过创建float32
来启动TensorFlow,然后我们可以通过调用tf.Session
运行任何内容。
sess.run()
在第二个例子中,我们现在必须告诉TensorFlow我们的值with tf.Session() as sess:
result = sess.run(add_op)
print(result)
应该是什么:
x
tl; dr:每个TensorFlow程序都有两部分:1。构建计算图,以及2.运行此图。使用with tf.Session() as sess:
result = sess.run(add_op, {x: 5.0})
print(result)
,您只需定义图表,但尚未执行任何添加。要运行此图表,请在第一段代码中使用tf.add
。