tfboys——tensorflow模块学习,一

Tensorflow的基本使用

TensorFlow 的特点:

  • 使用图 (graph) 来表示计算任务.
  • 在被称之为 会话 (Session) 的上下文 (context) 中执行图.
  • 使用 tensor 表示数据.
  • 通过 变量 (Variable) 维护状态.
  • 使用 feed 和 fetch 可以为任意的操作(arbitrary operation) 赋值或者从其中获取数据.

TensorFlow 综述

TensorFlow 是一个编程系统, 使用图来表示计算任务。图中的节点被称之为 op (operation 的缩写)。 一个 op 获得 0 个或多个Tensor, 执行计算, 产生 0 个或多个 Tensor. 每个 Tensor 是一个类型化的多维数组. 例如, 你可以将一小组图像集表示为一个四维浮点数数组, 这四个维度分别是 [batch, height, width, channels].

一个 TensorFlow 图描述了计算的过程. 为了进行计算, 图必须在 会话 里被启动. 会话 将图的 op 分发到诸如 CPU 或 GPU 之类的 设备 上, 同时提供执行 op 的方法. 这些方法执行后, 将产生的 tensor 返回. 在 Python 语言中, 返回的 tensor 是 numpy ndarray 对象; 在 C 和 C++ 语言中, 返回的 tensor 是tensorflow::Tensor 实例.

TensorFlow 计算图

TensorFlow 程序通常被组织成一个构建阶段和一个执行阶段. 在构建阶段, op 的执行步骤 被描述成一个图. 在执行阶段, 使用会话执行执行图中的 op。

例如, 通常在构建阶段创建一个图来表示和训练神经网络,然后在执行阶段反复执行图中的训练 op。

TensorFlow 支持 C, C++, Python 编程语言. 目前, TensorFlow 的 Python 库更加易用, 它提供了大量的辅助函数来简化构建图的工作, 这些函数尚未被 C 和 C++ 库支持.

三种语言的会话库 (session libraries) 是一致的.

TensorFlow 构建图

构建图的第一步, 是创建源 op (source op)。源 op 不需要任何输入, 例如 常量 (Constant). 源 op 的输出被传递给其它 op 做运算.

Python 库中, op 构造器的返回值代表被构造出的 op 的输出, 这些返回值可以传递给其它 op 构造器作为输入.

TensorFlow Python 库有一个默认图 (default graph), op 构造器可以为其增加节点. 这个默认图对 许多程序来说已经足够用了. 阅读 Graph 类 文档 来了解如何管理多个图.

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)

默认图现在有三个节点, 两个 constant() op, 和一个matmul() op. 为了真正进行矩阵相乘运算, 并得到矩阵乘法的 结果, 你必须在会话里启动这个图.

在一个会话中启动图

构造阶段完成后, 才能启动图. 启动图的第一步是创建一个 Session 对象, 如果无任何创建参数, 会话构造器将启动默认图.

欲了解完整的会话 API, 请阅读Session 类.

# 启动默认图.
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 对象在使用完后需要关闭以释放资源. 除了显式调用 close 外, 也可以使用 "with" 代码块 来自动完成关闭动作.

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, 以此类推.

交互式使用

文档中的 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.

变量

变量维护图执行过程中的状态信息。下面的例子演示了如何使用变量实现一个简单的计数器。

# 创建一个变量, 初始化为标量 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)]

如果没有正确提供 feed, placeholder() 操作将会产生错误。


接下来,将根据tf里的各个模块来介绍函数,同时介绍一些相关函数背后的数学背景

TensorFlow app模块

模块:tf.app

定义在:tensorflow/python/platform/app.py

通用入口点脚本。

flags 模块

flags 模块:实现标志接口。

函数

run(...):使用可选的 “main” 函数和 “argv” 列表运行程序。

tf.app.run

run (  
    main = None ,  
    argv = None
  )

定义在:tensorflow/python/platform/app.py

使用可选的 “main” 函数和 “argv” 列表运行程序。

会看到这么两行代码:

FLAGS, unparsed = parser.parse_known_args()  
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

第一行的含义是对运行命令行时传进来的参数进行解析,如果传进来的参数是之前被add到parser中的,则被传给FLAGS,否则讲传给unpared。

如我们在运行程序时在后面加上了 --epoch 32 参数,如果这个参数之前被加入到parser中,则将parser中的epoch参数更改为32并传诶FLAGS,否则 则将 --epoch 32写入到unparsed中

为了了解第二行的含义,我们在/tensorflow/python/platform中找到app.py并打开。

# Copyright 2015 The TensorFlow Authors. All Rights Reserved.  
#  
# Licensed under the Apache License, Version 2.0 (the "License");  
# you may not use this file except in compliance with the License.  
# You may obtain a copy of the License at  
#  
#     http://www.apache.org/licenses/LICENSE-2.0  
#  
# Unless required by applicable law or agreed to in writing, software  
# distributed under the License is distributed on an "AS IS" BASIS,  
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
# See the License for the specific language governing permissions and  
# limitations under the License.  
# ==============================================================================  
  
"""Generic entry point script."""  
from __future__ import absolute_import  
from __future__ import division  
from __future__ import print_function  
  
import sys as _sys  
  
from tensorflow.python.platform import flags  
from tensorflow.python.util.all_util import remove_undocumented  
  
  
def _benchmark_tests_can_log_memory():  
  return True  
  
  
def run(main=None, argv=None):  
  """Runs the program with an optional \'main\' function and \'argv\' list."""  
  f = flags.FLAGS  
  
  # Extract the args from the optional `argv` list.  
  args = argv[1:] if argv else None  
  
  # Parse the known flags from that list, or from the command  
  # line otherwise.  
  # pylint: disable=protected-access  
  flags_passthrough = f._parse_flags(args=args)  
  # pylint: enable=protected-access  
  
  main = main or _sys.modules[\'__main__\'].main  
  
  # Call the main function, passing through any arguments  
  # to the final program.  
  _sys.exit(main(_sys.argv[:1] + flags_passthrough))

我们给这个方法传递了两个参数,一个是要运行的主方法,另一个是:

argv=[sys.argv[0]] + unparsed

这个列表中储存了我们要运行的程序的位置,以及没有被parser匹配的参数。

help中写道run()方法的用途是用argv列表运行一个可选的main方法。

下面的语句将没有被parser匹配的参数放入argv中并且通过一个flags对象传入要执行的函数中。

args = argv[1:] if argv else None  
flags_passthrough = f._parse_flags(args=args)  
main = main or _sys.modules[\'__main__\'].main  
_sys.exit(main(_sys.argv[:1] + flags_passthrough))

如果我们传入了一个函数名,则程序会去用没有匹配的参数执行这个函数,否则,则会用没有匹配的参数去执行__main__。


参考:http://blog.csdn.net/u013171318/article/details/73740818


tf.bitwise模块

模块:tf.bitwise

定义在:tensorflow/python/ops/bitwise_ops.py

用于操纵整数的二进制表示的操作。

函数

bitwise_and(...):元素计算 x 和 y 的按位与。

bitwise_or(...):元素计算 x 和 y 的按位或。

bitwise_xor(...):元素计算 x 和 y 的按位异或。

invert(...):翻转所有位元素。

tf.bitwise.bitwise_and 元素按位与运算

bitwise_and ( 
    x , 
    y , 
    name = None
 )

元素计算 x 和 y 的按位与。

结果将设置那些在 x 和 y 中设置的位。对 x 和 y 的基础表示进行计算。

ARGS:
  • x:张量。必须是下列类型之一:int8,int16,int32,int64,uint8,uint16。
  • y:张量。必须与 x 具有相同的类型。
  • name:操作的名称(可选)。
返回:

返回一个张量,与 x 具有相同的类型。

tf.bitwise.bitwise_or 元素按位或运算

bitwise_or ( 
    x , 
    y , 
    name = None
 )

元素计算 x 和 y 的按位或。

结果将设置那些在 x、y 或两者中设置的位。对 x 和 y 的基础表示进行计算。

ARGS:
  • x:张量。必须是下列类型之一:int8,int16,int32,int64,uint8,uint16。
  • y:张量。必须与 x 具有相同的类型。
  • name:操作的名称(可选)。
返回:

返回张量,与 x 具有相同的类型。

tf.bitwise.bitwise_xor 元素按位异或

bitwise_xor ( 
    x , 
    y , 
    name = None
 )

元素计算 x 和 y 的按位异或。

结果将设置位,在 x 和 y 中是不同的。对 x 和 y 的基础表示进行计算。

ARGS:
  • x:张量。必须是下列类型之一:int8,int16,int32,int64,uint8,uint16。
  • y:张量。必须与 x 具有相同的类型。
  • name:操作的名称(可选)。
返回:

返回张量。与 x 具有相同的类型。

tf.bitwise.invert 所有位元素翻转

invert ( 
    x , 
    name = None
 )

翻转所有位元素。

结果将准确地设置那些未在 x 中设置的位。计算是在 x 的基础表示形式上执行的。

ARGS:
  • x:张量。必须是下列类型之一:int8,int16,int32,int64,uint8,uint16。
  • name:操作的名称(可选)。
返回:

返回张量。与 x 具有相同的类型。


tf.compat模块

TensorFlow Python / tf.compat

  • 模块:tf.compat
  • tf.compat.as_bytes
  • tf.compat.as_str_any
  • tf.compat.as_text

tf.compat

定义在:tensorflow/python/util/compat.py

与 Python 2 和 3 具有兼容性的函数。

转换例程

除了以下功能之外,as_str 将对象转换为 str。

类型

兼容性模块还提供以下类型:

  • bytes_or_text_types
  • complex_types
  • integral_types
  • real_types

功能

as_bytes(...):将字节或 unicode 转换为 bytes,使用 UTF-8 编码进行文本处理。

as_str(...):将字节或 unicode 转换为 bytes,使用 UTF-8 编码进行文本处理。

as_str_any(...):转换 str 为 str(value),但 as_str 用于 bytes。

as_text(...):以 unicode 字符串的形式返回给定的参数。

其他成员

bytes_or_text_types

complex_types

integral_types

real_types

tf.compat.as_bytes

tf.compat.as_str

(字节和Unicode转换)

tf.compat.as_str

as_bytes (  
    bytes_or_text ,  
    encoding = \'utf-8\' 
)

定义在:tensorflow/python/util/compat.py

将字节或 Unicode 转换为 bytes,使用 UTF-8 编码文本。

ARGS:
  • bytes_or_text:bytes,str 或 unicode 对象。
  • encoding:一个字符串,表示用于编码 unicode 的字符集。
返回:

返回一个 bytes 对象。

注意:
  • TypeError:当 bytes_or_text 不是二进制或 Unicode 字符串。

tf.compat.as_str_any 任何值转化为str

as_str_any ( value )

定义在:tensorflow/python/util/compat.py

转换 str 为 str(value),但 as_str 用于 bytes。

ARGS:
  • value:可以转换为 str 的对象。
返回:

返回一个 str 对象。

tf.compat.as_text 返回给定参数

as_text ( 
    bytes_or_text , 
    encoding = \'utf-8\' 
)

定义在:tensorflow/python/util/compat.py

以 unicode 字符串形式返回给定的参数。

ARGS:
  • bytes_or_text:一个 bytes,str 或 orunicode对象。
  • encoding:一个字符串,表示用于解码 unicode 的字符集。
返回:

A unicode(在 Python 2 中)或 str(在 Python 3 中)对象。

注意:
  • TypeError:当 bytes_or_text 不是二进制或 unicode 字符串。

参考网站:https://www.w3cschool.cn/tensorflow_python/tensorflow_python-oaet2coo.html