【问题标题】:I cannot understand Tensorflow system我无法理解 TensorFlow 系统
【发布时间】:2017-04-06 11:30:33
【问题描述】:

我无法理解 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)

有必要吗? 这部分有什么功能?

【问题讨论】:

    标签: python numpy tensorflow


    【解决方案1】:

    我建议阅读 TensorFlow 的官方 Getting Started with TensorFlow 指南以了解该库的核心概念,例如这里似乎存在问题的概念:

    每个 TensorFlow 程序都由两部分组成:

    1. 构建计算图。
    2. 运行计算图。

    现在,什么是“计算图”?在 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 是什么 - 只知道它将是 float32。 如果你有 GPU,你会注意到 TensorFlow 甚至还没有接触到 GPU。即使您拥有一个包含数百万张训练图像的庞大神经网络,这一步也可以在几毫秒内运行,因为不需要完成“真正的”工作。

    现在是第二部分:运行我们上面定义的图表。这就是工作发生的地方! 我们通过创建 tf.Session 来启动 TensorFlow,然后我们可以通过调用 sess.run()运行任何东西。

    with tf.Session() as sess:
        result = sess.run(add_op)
        print(result)
    

    在第二个示例中,我们现在必须告诉 TensorFlow 我们的值 x 应该是什么:

    with tf.Session() as sess:
        result = sess.run(add_op, {x: 5.0})
        print(result)
    

    tl;dr: 每个 TensorFlow 程序都有两个部分:1. 构建计算图,2. 运行该图。使用tf.add,您只需定义图形,但尚未执行添加。要运行此图表,请在您的第一段代码中使用sess.run()

    【讨论】:

    • thx!!你的回答对我来说很好,可以很好理解。我有一个问题,我可以调用tf.Session方法是激活函数吗?我阅读了Tensorflow教程,但我不能很好理解这部分。
    • 很好的解释,特别适合初学者。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-03
    • 2016-02-29
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 2020-07-01
    相关资源
    最近更新 更多