Tensorflow学习笔记——张量、图、常量、变量(一)

来源:互联网 发布:python simyou 编辑:程序博客网 时间:2024/06/06 17:26

1 张量和图

TensorFlow是一种采用数据流图(data flow graphs),用于数值计算的开源软件库。其中 Tensor 代表传递的数据为张量(多维数组),Flow 代表使用计算图进行运算。数据流图用「结点」(nodes)和「边」(edges)组成的有向图来描述数学运算。「结点」一般用来表示施加的数学操作,但也可以表示数据输入的起点和输出的终点,或者是读取/写入持久变量(persistent variable)的终点。边表示结点之间的输入/输出关系。这些数据边可以传送维度可动态调整的多维数据数组,即张量(tensor)。

a = tf.constant(2, tf.int16)b = tf.constant(4, tf.float32)graph = tf.Graph()with graph.as_default():    a = tf.Variable(8, tf.float32)    b = tf.Variable(tf.zeros([2,2], tf.float32))    with tf.Session(graph=graph) as session:    tf.global_variables_initializer().run()    print(f)    print(session.run(a))    print(session.run(b))#输出:>>> <tf.Variable 'Variable_2:0' shape=() dtype=int32_ref>>>> 8>>> [[ 0.  0.]>>>  [ 0.  0.]]

在 Tensorflow 中,所有不同的变量和运算都是储存在计算图。所以在我们构建完模型所需要的图之后,还需要打开一个会话(Session)来运行整个计算图。在会话中,我们可以将所有计算分配到可用的 CPU 和 GPU 资源中。

如下所示代码,我们声明两个常量 a 和 b,并且定义一个加法运算。但它并不会输出计算结果,因为我们只是定义了一张图,而没有运行它:

  1. a=tf.constant([1,2],name="a")
  2. b=tf.constant([2,4],name="b")
  3. result = a+b
  4. print(result)

#输出:Tensor("add:0", shape=(2,), dtype=int32)

下面的代码才会输出计算结果,因为我们需要创建一个会话才能管理 TensorFlow 运行时的所有资源。但计算完毕后需要关闭会话来帮助系统回收资源,不然就会出现资源泄漏的问题。下面提供了使用会话的两种方式:
a=tf.constant([1,2,3,4])b=tf.constant([1,2,3,4])result=a+bsess=tf.Session()print(sess.run(result))sess.close#输出 [2 4 6 8]with tf.Session() as sess:    a=tf.constant([1,2,3,4])    b=tf.constant([1,2,3,4])    result=a+b    print(sess.run(result))#输出 [2 4 6 8]

2 常量和变量

TensorFlow 中最基本的单位是常量(Constant)、变量(Variable)和占位符(Placeholder)。常量定义后值和维度不可变,变量定义后值可变而维度不可变。在神经网络中,变量一般可作为储存权重和其他信息的矩阵,而常量可作为储存超参数或其他结构信息的变量。下面我们分别定义了常量与变量:
a = tf.constant(2, tf.int16)b = tf.constant(4, tf.float32)c = tf.constant(8, tf.float32)d = tf.Variable(2, tf.int16)e = tf.Variable(4, tf.float32)f = tf.Variable(8, tf.float32)g = tf.constant(np.zeros(shape=(2,2), dtype=np.float32))h = tf.zeros([11], tf.int16)i = tf.ones([2,2], tf.float32)j = tf.zeros([1000,4,3], tf.float64)k = tf.Variable(tf.zeros([2,2], tf.float32))l = tf.Variable(tf.zeros([5,6,5], tf.float32))

在上面代码中,我们分别声明了不同的常量(tf.constant())和变量(tf.Variable()),其中tf.float 和tf.int tftf分别声明了不同的浮点型和整数型数据。而 tf.ones() 和 tf.zeros() 分别产生全是 1、全是 0 的矩阵。我们注意到常量 g,它的声明结合了 TensorFlow 和 Numpy,这也是可执行的。
w1=tf.Variable(tf.random_normal([2,3],stddev=1,seed=1))

以上语句声明一个2 行 3 列的变量矩阵,该变量的值服从标准差为 1 的正态分布,并随机生成。

现在,我们可以应用变量来定义神经网络中的权重矩阵和偏置项向量:
weights = tf.Variable(tf.truncated_normal([256 * 256, 10]))biases = tf.Variable(tf.zeros([10]))print(weights.get_shape().as_list())print(biases.get_shape().as_list())#输出>>>[65536, 10]>>>[10]



阅读全文
0 0
原创粉丝点击