[关闭]
@devilloser 2017-05-25T09:31:50.000000Z 字数 1456 阅读 830

tensorflow(day1)

tensorflow


思想

(1)使用图表示计算任务
(2)在会话中执行图
(3)tensor表示数据
(4)变量维护状态
(5)使用 feed 和fetch可以为任意的操作(arbitrary operation) 赋值或者从其中获取数据

计算图

Tensorflow分为构建和执行程序阶段,构建阶段,op被描述成计算图,执行阶段执行图中的op

构建图

  1. import tensorflow as tf
  2. # 创建一个常量 op, 产生一个 1x2 矩阵. 这个 op 被作为一个节点
  3. # 加到默认图中.
  4. #
  5. # 构造器的返回值代表该常量 op 的返回值.
  6. matrix1 = tf.constant([[3., 3.]])
  7. # 创建另外一个常量 op, 产生一个 2x1 矩阵.
  8. matrix2 = tf.constant([[2.],[2.]])
  9. # 创建一个矩阵乘法 matmul op , 把 'matrix1' 和 'matrix2' 作为输入.
  10. # 返回值 'product' 代表矩阵乘法的结果.
  11. product = tf.matmul(matrix1, matrix2)

会话中启动图

  1. # 启动默认图.
  2. sess = tf.Session()
  3. # 调用 sess 的 'run()' 方法来执行矩阵乘法 op, 传入 'product' 作为该方法的参数.
  4. # 上面提到, 'product' 代表了矩阵乘法 op 的输出, 传入它是向方法表明, 我们希望取回
  5. # 矩阵乘法 op 的输出.
  6. #
  7. # 整个执行过程是自动化的, 会话负责传递 op 所需的全部输入. op 通常是并发执行的.
  8. #
  9. # 函数调用 'run(product)' 触发了图中三个 op (两个常量 op 和一个矩阵乘法 op) 的执行.
  10. #
  11. # 返回值 'result' 是一个 numpy `ndarray` 对象.
  12. result = sess.run(product)
  13. print result
  14. # ==> [[ 12.]]
  15. # 任务完成, 关闭会话.
  16. sess.close()

或者可以用with代码块完成关闭动作

  1. with tf.Session as sess:
  2. result=sess.run(...)
  3. print result

指定设备

  1. with tf.Session() as sess:
  2. matrix1=tf.constant([[3.,3.]])
  3. matrix2=tf.constant([[2.],[2.]])
  4. product=tf.matmul(matrix1,matrix2)

交互式使用

InteractiveSession代替Session类
Tensor.eval()和Operation.run()代替Session.run()

Variables

  1. # 创建一个变量, 初始化为标量 0.
  2. state = tf.Variable(0, name="counter")
  3. # 创建一个 op, 其作用是使 state 增加 1
  4. one = tf.constant(1)
  5. new_value = tf.add(state, one)
  6. update = tf.assign(state, new_value)
  7. # 启动图后, 变量必须先经过`初始化` (init) op 初始化,
  8. # 首先必须增加一个`初始化` op 到图中.
  9. init_op = tf.initialize_all_variables()
  10. # 启动图, 运行 op
  11. with tf.Session() as sess:
  12. # 运行 'init' op
  13. sess.run(init_op)
  14. # 打印 'state' 的初始值
  15. print sess.run(state)
  16. # 运行 op, 更新 'state', 并打印 'state'
  17. for _ in range(3):
  18. sess.run(update)
  19. print sess.run(state)
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注