TensorFlow study notes (2) -- the basic concepts and usage of TensorFlow

basic use

To use TensorFlow, you must understand TensorFlow:

  • Use graphs to represent computational tasks.
  • The graph is executed in what is called  会话 (Session) a context.
  • Use tensor to represent data.
  • By  变量 (Variable) maintaining state.
  • Use feed and fetch to assign values ​​to or fetch data from arbitrary operations.

Overview

TensorFlow is a programming system that uses graphs to represent computing tasks. The nodes in the graph are called  ops  (abbreviation for operations). An op gets 0 or more  ,Tensor performs calculations, and produces 0 or more  Tensor. Each Tensor is a typed multidimensional array. For example, you could represent a small set of images as a four-dimensional array of floating-point numbers, the four dimensions being  [batch, height, width, channels].

A TensorFlow graph describes the process of computation. In order to perform computations, the graph must  会话 be started in it.  会话 Distribute the graph's ops to something like a CPU or GPU  设备 , and provide methods to execute the ops. After these methods are executed, the resulting tensor returns. In Python, the returned tensor is a  numpy ndarray  object; in C and C++, the returned tensor is an tensorflow::Tensor instance.

Computational graph

TensorFlow programs are usually organized into a build phase and an execution phase. In the build phase, the execution steps of an op are described as a graph. In the execution phase, the ops in the execution graph are executed using sessions.

For example, it is common to create a graph to represent and train a neural network during the build phase, and then repeatedly execute the training ops in the graph during the execution phase.

TensorFlow supports C, C++, Python programming languages. Currently, TensorFlow's Python library is easier to use, and it provides a large number of helper functions to simplify the work of building graphs, which are not yet supported by the C and C++ libraries.

The session libraries for the three languages ​​are identical.

Build the graph

The first step in building a graph is to create a source op (source op). The source op does not require any input, i.e.  常量 (Constant)the output of the source op is passed to other ops for operations.

In the Python library, the return value of the op constructor represents the output of the constructed op, and these return values ​​can be passed to other op constructors as input.

The TensorFlow Python library has a default graph to which the op constructor can add nodes. This default graph is sufficient for many programs. Read the  Graph class  documentation to learn how to manage multiple graphs.

import tensorflow as tf

# 创建一个常量 op, 产生一个 1x2 矩阵. 这个 op 被作为一个节点
# 加到默认图中.
#
# 构造器的返回值代表该常量 op 的返回值.
matrix1 = tf.constant([[3., 3.]])

# 创建另外一个常量 op, 产生一个 2x1 矩阵.
matrix2 = tf.constant([[2.],[2.]])

# 创建一个矩阵乘法 matmul op , 把 'matrix1' 和 'matrix2' 作为输入.
# 返回值 'product' 代表矩阵乘法的结果.
product = tf.matmul(matrix1, matrix2)

The default graph now has three nodes, two  constant() ops, and one matmul() op. In order to actually do the matrix multiplication and get the result of the matrix multiplication, you must start the graph in the session.

Start a graph in one session

The graph cannot be started until the construction phase is complete. The first step in starting a graph is to create an  Session object, and the session constructor will start the default graph without any creation parameters.

For the full session API, read the Session class .

# 启动默认图.
sess = tf.Session()

# 调用 sess 的 'run()' 方法来执行矩阵乘法 op, 传入 'product' 作为该方法的参数. 
# 上面提到, 'product' 代表了矩阵乘法 op 的输出, 传入它是向方法表明, 我们希望取回
# 矩阵乘法 op 的输出.
#
# 整个执行过程是自动化的, 会话负责传递 op 所需的全部输入. op 通常是并发执行的.
# 
# 函数调用 'run(product)' 触发了图中三个 op (两个常量 op 和一个矩阵乘法 op) 的执行.
#
# 返回值 'result' 是一个 numpy `ndarray` 对象.
result = sess.run(product)
print result
# ==> [[ 12.]]

# 任务完成, 关闭会话.
sess.close()

Session Objects need to be closed after use to free resources. In addition to explicitly calling close, the "with" block can be used to automatically complete the closing action.

with tf.Session() as sess:
  result = sess.run([product])
  print result

在实现上, TensorFlow 将图形定义转换成分布式执行的操作, 以充分利用可用的计算资源(如 CPU 或 GPU). 一般你不需要显式指定使用 CPU 还是 GPU, TensorFlow 能自动检测. 如果检测到 GPU, TensorFlow 会尽可能地利用找到的第一个 GPU 来执行操作.

如果机器上有超过一个可用的 GPU, 除第一个外的其它 GPU 默认是不参与计算的. 为了让 TensorFlow 使用这些 GPU, 你必须将 op 明确指派给它们执行. with...Device 语句用来指派特定的 CPU 或 GPU 执行操作:

with tf.Session() as sess:
  with tf.device("/gpu:1"):
    matrix1 = tf.constant([[3., 3.]])
    matrix2 = tf.constant([[2.],[2.]])
    product = tf.matmul(matrix1, matrix2)
    ...

设备用字符串进行标识. 目前支持的设备包括:

  • "/cpu:0": 机器的 CPU.
  • "/gpu:0": 机器的第一个 GPU, 如果有的话.
  • "/gpu:1": 机器的第二个 GPU, 以此类推.

阅读使用GPU章节, 了解 TensorFlow GPU 使用的更多信息.

交互式使用

文档中的 Python 示例使用一个会话 Session 来 启动图, 并调用 Session.run() 方法执行操作.

为了便于使用诸如 IPython 之类的 Python 交互环境, 可以使用 InteractiveSession 代替 Session 类, 使用 Tensor.eval() 和 Operation.run() 方法代替 Session.run(). 这样可以避免使用一个变量来持有会话.

# 进入一个交互式 TensorFlow 会话.
import tensorflow as tf
sess = tf.InteractiveSession()

x = tf.Variable([1.0, 2.0])
a = tf.constant([3.0, 3.0])

# 使用初始化器 initializer op 的 run() 方法初始化 'x' 
x.initializer.run()

# 增加一个减法 sub op, 从 'x' 减去 'a'. 运行减法 op, 输出结果 
sub = tf.sub(x, a)
print sub.eval()
# ==> [-2. -1.]

Tensor

TensorFlow 程序使用 tensor 数据结构来代表所有的数据, 计算图中, 操作间传递的数据都是 tensor. 你可以把 TensorFlow tensor 看作是一个 n 维的数组或列表. 一个 tensor 包含一个静态类型 rank, 和 一个 shape. 想了解 TensorFlow 是如何处理这些概念的, 参见 Rank, Shape, 和 Type.

变量

Variables for more details. 变量维护图执行过程中的状态信息. 下面的例子演示了如何使用变量实现一个简单的计数器. 参见 变量 章节了解更多细节.

# 创建一个变量, 初始化为标量 0.
state = tf.Variable(0, name="counter")

# 创建一个 op, 其作用是使 state 增加 1

one = tf.constant(1)
new_value = tf.add(state, one)
update = tf.assign(state, new_value)

# 启动图后, 变量必须先经过`初始化` (init) op 初始化,
# 首先必须增加一个`初始化` op 到图中.
init_op = tf.initialize_all_variables()

# 启动图, 运行 op
with tf.Session() as sess:
  # 运行 'init' op
  sess.run(init_op)
  # 打印 'state' 的初始值
  print sess.run(state)
  # 运行 op, 更新 'state', 并打印 'state'
  for _ in range(3):
    sess.run(update)
    print sess.run(state)

# 输出:

# 0
# 1
# 2
# 3

代码中 assign() 操作是图所描绘的表达式的一部分, 正如 add() 操作一样. 所以在调用 run() 执行表达式之前, 它并不会真正执行赋值操作.

通常会将一个统计模型中的参数表示为一组变量. 例如, 你可以将一个神经网络的权重作为某个变量存储在一个 tensor 中. 在训练过程中, 通过重复运行训练图, 更新这个 tensor.

Fetch

为了取回操作的输出内容, 可以在使用 Session 对象的 run() 调用 执行图时, 传入一些 tensor, 这些 tensor 会帮助你取回结果. 在之前的例子里, 我们只取回了单个节点 state, 但是你也可以取回多个 tensor:

input1 = tf.constant(3.0)
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)
intermed = tf.add(input2, input3)
mul = tf.mul(input1, intermed)

with tf.Session():
  result = sess.run([mul, intermed])
  print result

# 输出:
# [array([ 21.], dtype=float32), array([ 7.], dtype=float32)]

需要获取的多个 tensor 值,在 op 的一次运行中一起获得(而不是逐个去获取 tensor)。

Feed

上述示例在计算图中引入了 tensor, 以常量或变量的形式存储. TensorFlow 还提供了 feed 机制, 该机制 可以临时替代图中的任意操作中的 tensor 可以对图中任何操作提交补丁, 直接插入一个 tensor.

feed 使用一个 tensor 值临时替换一个操作的输出结果. 你可以提供 feed 数据作为 run() 调用的参数. feed 只在调用它的方法内有效, 方法结束, feed 就会消失. 最常见的用例是将某些特殊的操作指定为 "feed" 操作, 标记的方法是使用 tf.placeholder() 为这些操作创建占位符.


input1 = tf.placeholder(tf.types.float32)
input2 = tf.placeholder(tf.types.float32)
output = tf.mul(input1, input2)

with tf.Session() as sess:
  print sess.run([output], feed_dict={input1:[7.], input2:[2.]})

# 输出:
# [array([ 14.], dtype=float32)]

for a larger-scale example of feeds. 如果没有正确提供 feed, placeholder() 操作将会产生错误. MNIST 全连通 feed 教程 (source code) 给出了一个更大规模的使用 feed 的例子.


本文转载自TensorFlow中文社区

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324686895&siteId=291194637