编写Tensorflow的两个步骤:
- 构建计算图graph
- 使用session去执行graph中的operation
![这里写图片描述]
- Tensor:类型化的多维数组,图的边
- Operation:执行计算的单元,图的节点
- Graph:一张有边与点的图,其表示了需要进行计算的任务
- Session:称之为会话的上下文,用于执行图
三个基本概念
![](https://i-blog.csdnimg.cn/blog_migrate/489e6ec3ce6f4441bc5d83cc8a51f85e.png)
![](https://i-blog.csdnimg.cn/blog_migrate/a63779031cef01c6c16923c1d55b6afd.png)
Tensor
- N维矩阵
- 创建方法
import tensorflow as tf
tf.zeros([row_dim, col_dim])
tf.ones([row_dim, col_dim])
tf.fill([row_dim, col_dim], 42)
tf.consatnt([1, 2, 3])
tf.random_uniform([row_dim, col_dim], minval=0, maxval=1)
tf.random_normal([row_dim, col_dim], mean=0.0, stddev=1.0)
- 三个属性:rank、shape、data_type
Rank: rank一般是指数据的维度,其与线性代数中的rank不是一个概念。其常
用rank举例如下。
Shape:指tensor每个维度数据的个数,可以用python的list/tuple表示。下
图表示了rank,shape的关系。
Data_type: 是指单个数据的类型。常用DT_FLOAT,也就是32位的浮
点数。下图表示了所有的types。
Operation
- 一个符号化的运算过程
- Graph中的计算节点
- 输入输出均为Tensor
Graph
- 定义:Tensorflow中使用tf.Graph表示可计算的图。图是由操作Operation和
张量Tensor来构成,其中Operation表示图的节点(即计算单元),而Tensor
则表示图的边(即Operation之间流动的数据单元)。 - 创建方法:
- tf.Graph.init():创建一个新的空Graph
- 可在一张图中运行,也可构建多张图
import tensorflow as tf
g1 = tf.Graph()
with g1.as_default():
c1 = tf.constant([1.0])
with tf.Graph().as_default() as g2:
c2 = tf.constant([2.0])
with tf.Session(graph=g1) as sess1:
print(sess1.run(c1))
with tf.Session(graph=g2) as sess2:
print(sess2.run(c2))
#result:
#[ 1.]
#[ 2.]
- Session提供了Operation执行和Tensor求值的环境
#构建一个计算图
a = tf.constant([1.0, 2.0])
b = tf.constant([3.0, 4.0])
c = a * b
#构建一个session
sess = tf.Session()
#把计算图放到session理,并运行得到结果
print(sess.run(c))
sess.close()
#result: [ 3. 8.]
- 释放资源
- 调用session.close()方法
- 使用with tf.Session()创建上下文(Context)来执行,当上下文退出时自动释放。
#构建一个计算图
a = tf.constant([1.0, 2.0])
b = tf.constant([3.0, 4.0])
c = a * b
#构建一个session
sess = tf.Session()
#把计算图放到session理,并运行得到结果
with tf.Session() as sess:
print(sess.run(c))
#result: [ 3. 8.]
Variables
作用:保存于更新参数
weights = tf.Variable(tf.random_normal([784, 200], stddev=0.35), name="weights")
biases = tf.Variable(tf.zeros([200]), name="biases")
- Variables初始化
- 初始化所有变量:tf.global_variables_initializer,会在session运算时初始化
所有变量 - 初始化部分变量:tf.variables_initializer
- 示例:v1 = tf.variables_initializer([a,b],name=“v1”)
- 初始化所有变量:tf.global_variables_initializer,会在session运算时初始化
- Varaibles和Constant区别
- Constant一般是常量,可以被赋值给Variables,constant保存在
graph中,如果graph重复载入那么constant也会重复载入,其非常
浪费资源,如非必要尽量不使用其保存大量数据。 - Variables在每个session中都是单独保存的,甚至可以单独存在一个
参数服务器上。
- Constant一般是常量,可以被赋值给Variables,constant保存在
Placeholder与FeedDict
- Placeholder:可以使用tf.placeholder(dtype,shape=None,name=None)
函数来定义
x1 = tf.placeholder(tf.int32, shape=[1], name='x1')
x2 = tf.constant(2, name='x2')
result = x1 + x2
with tf.Session() as sess:
print(sess.run(result))
报错:
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'x1' with dtype int32 and shape [1]
[[Node: x1 = Placeholder[dtype=DT_INT32, shape=[1]
- 最后一行需修改成:print(sess.run(result,{x1:[3]}))