新人上手TensorFlow之TensorFlow基本概念

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/sunjinshengli/article/details/73917245

TensorFlow是Google Brain的第二代机器学习系统,2015年11月9日,作为开源软件发布。TensorFlow的计算用有状态的数据流图表示。这个库的算法源于Google需要指导称为神经网络的计算机系统,类似人类学习和推理的方法,以便派生出新的应用程序承担以前仅人类能胜任的角色和职能;TensorFlow的名字来源于这类神经网络对多维数组执行的操作。这些多维数组被称为“张量(Tensor)”,但这个概念并不等同于数学概念中的‘张量’。
上面这段话摘自TensorFlow的维基百科的介绍。其中提到了TensorFlow的几个重要的概念:Graph,Tensor。本文着重就TensorFlow中的几个概念进行探讨,主要有:
Graph、Tensor、Session 以及Variable、 constant、placeholder等概念。

1 Tensor及Tensor类

1.1 Tensor

Tensor 是TensorFlow 中的核心数据单元,可以简单的理解为 * 多维数组 *。 Tensor根据数组的维度可以分为多个等级

—–示例 ——–等级(Rank)——- ———维度———-
3 a rank 0 tensor; a scalar with shape []
[1. ,2., 3.] #; this is a rank 1 tensor a vector with shape [3]
[[1., 2., 3.], [4., 5., 6.]] a rank 2 tensor a matrix with shape [2, 3]
[[[1., 2., 3.]], [[7., 8., 9.]]] a rank 3 tensor shape [2, 1, 3]

1.2 Tensor类

Tensor类表示Operation类的输出。
A Tensor is a symbolic handle to one of the outputs of an Operation. It does not hold the values of that operation’s output, but instead provides a means of computing those values in a TensorFlow tf.Session.

我这么理解,Tensor 就是一个多维数组,而TF中的Tensor类封装了Operation和Tensor(不知道对不对!)。
一般来说,我们说Tensor以及TensorFlow的API中在指定参数的类型时说的Tensor是指第一种的Tensor的概念,Tensor类的概念一般就是用在Operation的输出上。

2 TensorFlow的计算用有状态的数据流图表示

2.1 数据流图的概念

来看一张莫烦做的TensorFlow的数据流图的示意图:
TensorFlow数据流图动态演示

TensorFlow中的类Graph 是一个数据流图。包含了tf.Operation的集合和tf.Tensor的集合。
我们抽丝剥茧的理解下这句话。
首先这里说的Graph是TensorFlow定义的一个类,定义在:tensorflow/python/framework/ops.py中。
然后,什么是数据流图呢?我们对比一下 控制流图 ,来理解一下数据流图。

—–属性 ——–控制流图 ——- ———数据流图———-
有向图 有向图
组成元素 矩形框、判断菱形、合并点 操作节点, 边(输入、输出)
面向过程 面向对象
节点之间不传递数据 节点之间传递数据
侧重点 表示出程序、应用、服务等的执行过程,及各个过程的结果信息 表明数据是如何在系统的节点之间传递(Flow)的

对于数据流图,每个节点,对应 TensorFlow中的tf.Operation类,每个节点的输入/输出则对应tf.Tensor类。
在图的起始节点,会产生一系列的数据,经过一个节点的处理后,输出到下一个节点,依次类推,直至最终的节点输出,由此构成一张有向图。

2.2 TensorFlow中的计算图

需要指出的是,TF将图的构造和运行分离成两个独立的部分。也就是说,我们在进行TensorFlow核心编程的时候,可以大体上按照两步来走:
1. 构造计算图(Building the computational graph)
2. 运行计算图(Running the computational graph)

那么如何构造,如何运行呢?
TF通过构造运算节点(Operation类)及其相互的关系建立起图,然后利用Session类来运行建立好的图。(A computational graph is a series of TensorFlow operations arranged into a graph of nodes. )

3 Operation类

tf.Operation类表示TensorFlow图中的一个节点,用来执行Tensor运算。
每个节点,可以有多个输入输出,也可以只有输入或者输出。其输入输出都是Tensor对象。比如:

c = tf.matmul(a, b)
这里生成了一个类型为“MatMul”的Operation, 输入时a和b, 输出是c。

3.1 TensorFlow內建的运算操作

参考TensorFlow的API:https://devdocs.io/tensorflow~python/math_ops
给个示例:

#tensorflow 內建的运算操作示例
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf
import numpy as np

#算术操作符
'''
tf.add
tf.subtract
tf.multiply
tf.scalar_mul
tf.div
tf.divide
tf.truediv
tf.floordiv
tf.realdiv
tf.truncatediv
tf.floor_div
tf.truncatemod
tf.floormod
tf.mod
tf.cross
'''
sess = tf.Session()


a = np.array([1,2],dtype = np.float32)
b = np.array([2,1])
#aa = tf.add_n([a,b])
#print(sess.run(aa))
c = tf.add(a,b)
print(sess.run(c))

d = tf.constant(1.0)
e = tf.Variable(2.0)
aa = tf.add_n([d,e])

f = tf.add(d,e)
sess.run(tf.global_variables_initializer())
print('aa:',sess.run(aa))
print(sess.run(f))

h = 1
i = 2
j = tf.add(h,i)
print(sess.run(j))
l = tf.Variable(b, dtype = tf.float32)
k = tf.scalar_mul(i, l)
sess.run(tf.global_variables_initializer())
print(sess.run(k))
sess.close()

运行结果:

[ 3.  3.]
aa: 3.0
3.0
3
[ 4.  2.]

3.2 如何通过Operation来构建图

4 Session类

4. Variable类

4.1 Variable的概念

A variable maintains state in the graph across calls to run(). You add a variable to the graph by constructing an instance of the class Variable.

The Variable() constructor requires an initial value for the variable, which can be a Tensor of any type and shape. The initial value defines the type and shape of the variable. After construction, the type and shape of the variable are fixed. The value can be changed using one of the assign methods.

If you want to change the shape of a variable later you have to use an assign Op with validate_shape=False.

Just like any Tensor, variables created with Variable() can be used as inputs for other Ops in the graph. Additionally, all the operators overloaded for the Tensor class are carried over to variables, so you can also add nodes to the graph by just doing arithmetic on variables.

4.2 Variable的初始化函数:

__init__(
    initial_value=None,
    trainable=True,
    collections=None,
    validate_shape=True,
    caching_device=None,
    name=None,
    variable_def=None,
    dtype=None,
    expected_shape=None,
    import_scope=None
)

看一下主要参数的含义:
- * initial_value:* A Tensor, or Python object convertible to a Tensor, which is the initial value for the Variable. The initial value must have a shape specified unless validate_shape is set to False. Can also be a callable with no argument that returns the initial value when called. In that case, dtype must be specified. (Note that initializer functions from init_ops.py must first be bound to a shape before being used here.)
- validate_shape: If False, allows the variable to be initialized with a value of unknown shape. If True, the default, the shape of initial_value must be known.
- name: Optional name for the variable. Defaults to ‘Variable’ and gets uniquified automatically.
- dtype: If set, initial_value will be converted to the given type. If None, either the datatype will be kept (if initial_value is a Tensor), or convert_to_tensor will decide.

4.3 如何使用Variable:

  1. 生成Variable的方法:

    Create a variable.
    w = tf.Variable(initial-value, name=optional-name)


初始化的initial—value 可以是任意数据类型的任意维度的Tensor。变量的数据类型和维度就根据这个初始值而定,而且不能改变。变量的值可以通过 tf.assign()函数来改变。如果想改变其维度,就要在生成variable的时候,将 validate_shape置false,并通过tf.assign()函数来重新赋值。
  1. Variable的使用:
    可以作为任何图中节点的输入参数。而且,可以通过直接对Variable进行运算将其添加到图中。

  2. 在运行图之前,要先初始化Variable。
    初始化Variable的方法有两种:
    1) 单个初始化:

#Launch the graph in a session.
with tf.Session() as sess:
    # Run the variable initializer.
    sess.run(w.initializer)
    # ...you now can run ops that use the value of 'w'...
2)  全局初始化:
# Add an Op to initialize global variables.
init_op = tf.global_variables_initializer()

# Launch the graph in a session.
with tf.Session() as sess:
    # Run the Op that initializes global variables.
    sess.run(init_op)
    # ...you can now run any Op that uses variable values...

猜你喜欢

转载自blog.csdn.net/sunjinshengli/article/details/73917245