graph:图,表示具体的计算任务
session:会话,图需要在会话中执行,一个会话可以包含很多图
tensor:张量,在此表示数据
variable:就是本意变量,图的重要组成部分
operation:简称op,是图中计算的节点
feed、fetch:意思是给图添加数据和获取图中的数据,因为训练过程中有些数据需要动态获得、临时给予数据
Tensor
TensorFlow使用tensor数据结构来代表所有的数据,计算图中,操作间传递的数据都是tensor.可以将tensor看做是一个数组或者是列表
Variable(变量)
当创建一个变量时,表明一个张量作为初始值传入构造函数Variable()。参数用来初始化张量,调用tf.variable()添加一些操作(Op,operation)到graph
tf.Variable(initializer, name):initializer是初始化参数,可以有tf.random_normal,tf.constant,tf.constant等,name就是变量的名字
a = tf.Variable(2, name='scalar')
b = tf.Variable([2, 3], name='vector')
c = tf.Variable([[0, 1], [2, 3]], name='matrix')
w = tf.Variable(tf.zeros([784, 10]), name='weight')
变量有着下面几个操作
x = tf.Variable()
x.initializer # 初始化
x.eval() # 读取里面的值
x.assign() # 分配值给这个变量
注意一点,在使用变量之前必须对其进行初始化,初始化可以看作是一种变量的分配值操作。最简单的初始化方式是一次性初始化所有的变量
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
也可以对某一部分变量进行初始化
init_ab = tf.variable_initializer([a, b], name='init_ab')
with tf.Session() as sess:
sess.run(init_ab)
或者是对某一个变量进行初始化
w = tf.Variable(tf.zeros([784, 10]))
with tf.Session() as sess:
sess.run(w.initializer)
如果我们想取出变量的值,有两种方法
w = tf.Variable(tf.truncated_normal([10, 10], name='normal'))
with tf.Session() as sess:
sess.run(w.initializer)
print(w.eval()) # 方法一
print(sess.run(w)) # 方法二
Placeholders(占位符)
tensorflow第一步是定义图,第二步是在session中进行图中的计算。对于图中我们暂时不知道值的量,我们可以定义为占位符,之后再用
feed_dict
去赋值,传入sess.run()函数。
tf.placeholder(dtype, shape=None, name=None)
dtype是必须要指定的参数,shape如果是None,说明任何大小的tensor都能够接受,使用shape=None很容易定义好图,但是在debug的时候这将成为噩梦,所以最好是指定好shape。
a = tf.placeholder(tf.float32, shape=[3])
b = tf.constant([5, 5, 5], tf.float32)
c = a + b
with tf.Session() as sess:
print(sess.run(c, feed_dict={a: [1, 2, 3]}))
constant(常数类型)
tf.constant(value, dtype=None, shape=None, name=’Const’, verify_shape=False)
可以是一维向量和矩阵,或者是使用特殊值的向量创建,也有和numpy类似的序列创建
a = tf.constant([2, 2], name='a')
b = tf.constant([[0, 1], [2, 3]], name='b')
Fetch
input1 = tf.constant([3.0])
input2 = tf.constant([2.0])
input3 = tf.constant([5.0])
intermed = tf.add(input2,input3)
mul = tf.multiply(input1,intermed)
with tf.Session() as sess:
result = sess.run([mul,intermed])
print(result)
Feed
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1,input2)
with tf.Session() as sess:
print(sess.run([output],feed_dict={input1:[7.],input2:[2.]}))