第一章
1. 简介
第二章
1. 安装
安装方法在我的博客有,包括cpu版,gpu版。
第三章 TensorFlow入门
1. 计算图
constant是TensorFlow的常量节点,通过constant方法创建,其是计算图(Computational Graph)中的起始节点,是传入数据。
cons = tf.constant(value=[1,2],dtype=tf.float32,shape=(1,2),name='testconst', verify_shape=False)
- 使用图 (graph) 来表示计算任务.
- 在被称之为
会话 (Session)
的上下文 (context) 中执行图. - 使用 tensor 表示数据.
- 通过
变量 (Variable)
维护状态. - 使用 feed 和 fetch 可以为任意的操作(arbitrary operation) 赋值或者从其中获取数据
为了进行计算, 图必须在 会话
里被启动. 会话
将图的 op 分发到诸如 CPU 或 GPU 之类的 设备
上, 同时提供执行 op 的方法. 这些方法执行后, 将产生的 tensor 返回. 在 Python 语言中, 返回的 tensor 是 numpy ndarray
对象
构建图的第一步, 是创建源 op (source op). 源 op 不需要任何输入, 例如 常量 (Constant)
. 源 op 的输出被传递给其它 op 做运算.
构造阶段完成后, 才能启动图. 启动图的第一步是创建一个 Session
对象, 如果无任何创建参数, 会话构造器将启动默认图.
Session
对象在使用完后需要关闭以释放资源. 除了显式调用 close 外, 也可以使用 "with" 代码块 来自动完成关闭动作.
with tf.Session() as sess:
result = sess.run([product])
print result
如果机器上有超过一个可用的 GPU, 除第一个外的其它 GPU 默认是不参与计算的. 为了让 TensorFlow 使用这些 GPU, 你必须将 op 明确指派给它们执行. with...Device
语句用来指派特定的 CPU 或 GPU 执行操作:
with tf.Session() as sess:
with tf.device("/gpu:1"):
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)
...
ensorFlow 程序使用 tensor 数据结构来代表所有的数据, 计算图中, 操作间传递的数据都是 tensor. 你可以把 TensorFlow tensor 看作是一个 n 维的数组或列表. 一个 tensor 包含一个静态类型 rank, 和 一个 shape
assign
x.assign(1)
update = tf.assign(x, 2)
# 创建一个变量, 初始化为标量 0.
state = tf.Variable(0, name="counter")
# 创建一个 op, 其作用是使 state 增加 1
one = tf.constant(1)
new_value = tf.add(state, one)
update = tf.assign(state, new_value)
# 启动图后, 变量必须先经过`初始化` (init) op 初始化,
# 首先必须增加一个`初始化` op 到图中.
init_op = tf.initialize_all_variables()
# 启动图, 运行 op
with tf.Session() as sess:
# 运行 'init' op
sess.run(init_op)
# 打印 'state' 的初始值
print sess.run(state)
# 运行 op, 更新 'state', 并打印 'state'
for _ in range(3):
sess.run(update)
print sess.run(state)
代码中 assign()
操作是图所描绘的表达式的一部分, 正如 add()
操作一样. 所以在调用 run()
执行表达式之前, 它并不会真正执行赋值操作.
fetch和feed机制
tf.placeholder() 为这些操作创建占位符
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.mul(input1, input2)
with tf.Session() as sess:
print sess.run([output], feed_dict={input1:[7.], input2:[2.]})