TensorFlow 是一个采用数据流图(data flow graphs),用于数值计算的开源软件库。节点(Nodes)在图中表示数学操作,图中的线(edges)则表示在节点间相互联系的多维数据数组,即张量(tensor)。
1.Tensor
tensor,表示张量,在TensorFlow中常用Tensor来描述矩阵信息。如下表示创建一个tensor,并将其初始化为0(zeros函数表示初始化一个tensor,并将其所有成员置位为0,缺省类型为float32)。
import tensorflow as tf #一般对导入库进行重命名,减少后续引用的复杂性 a=tf.zeros(shape=[3,4]) print(a) #输出 Tensor("zeros:0", shape=(3, 4), dtype=float32)
2.常量
格式:a=tf.constant(shape),shape可以为一维矩阵,也可为多维矩阵。如下所示:
b=tf.constant([[1]]) c=tf.constant([[1,1]]) d=tf.constant([[1],[1]]) e=tf.constant([[[1],[1]]]) print("a =",a) print("b =",b) print("c =",c) print("d =",d) print("e =",e) #输出如下 # a = Tensor("Const:0", shape=(1,), dtype=int32) # b = Tensor("Const_1:0", shape=(1, 1), dtype=int32) # c = Tensor("Const_2:0", shape=(1, 2), dtype=int32) # d = Tensor("Const_3:0", shape=(2, 1), dtype=int32) # e = Tensor("Const_4:0", shape=(1, 2, 1), dtype=int32)
3.变量
在TensorFlow中,用Variable来表示变量。变量的使用如下:
#创建一个变量 w = tf.Variable(<initial-value>, name=<optional-name>) #变量使用 y = tf.matmul(w, ...another variable or tensor...) #重载运算符 z = tf.sigmoid(w + y)#sigmoid 激活函数 #赋值, Assign a new value to the variable with `assign()` or a related method. w.assign(w + 1.0) w.assign_add(1.0)
特别注意:变量在使用前需要初始化,变量初始化可以对单个变量初始化(tf.session(w.initializer)),也可调用函数对所有变量进行初始化(tf.globalvariablesinitializer()),推荐使用全局变量初始化。
4.占位符(placeholder)
有时候有些变量我们无法初始化值时,我们用占位符来表示。
a = tf.placeholder(tf.int16) b = tf.placeholder(tf.int16) add = tf.add(a, b)
5.图、会话
图类似于一个容器,将所有的会话都放在里面,并在其上进行运算(操作,op)。
会话用来表示一个运行的空间。
一个图可以有多个会话,一个会话包含于一个图中。官方解释如下:
If no `graph` argument is specified when constructing the session,the default graph will be launched in the session. If you are using more than one graph (created with `tf.Graph()` in the same process, you will have to use different sessions for each graph,but each graph can be used in multiple sessions.
会话的使用:
#方式1:特别注意,这种方式需要关闭会话 sess = tf.Session() result = sess.run(add) sess.close() #方式2 推荐使用该方式 with tf.Session() as sess sess.run(add)
6.示例
import tensorflow as tf #常量与变量计算 a = tf.constant([[1,2]]) b = tf.Variable([[1],[3]]) c = tf.matmul(a,b) with tf.Session() as sess: # 初始化变量 sess.run(tf.global_variables_initializer()) sess.run(c) print(c) #>>Tensor("MatMul:0", shape=(1, 1), dtype=int32) #占位符的使用 c = tf.placeholder(tf.int16) d = tf.placeholder(tf.int16) add = tf.add(c, d) with tf.Session() as sess: print('a+b=',sess.run(add, feed_dict={c: 2, d: 3})) #>>a+b= 5
小结:Tensorflow采用图(graphs)表示计算任务,采用会话上下文来执行图,用Tensor表示数据,通过变量来维护状态.
Enjoy.
转载请注明出处,Juyin@2017/11/11