一.基础:
- 使用图(graph)表示计算任务
- 任务在会话(session)中执行
- 使用(tensor)表示数据
- 使用(Variable)维护状态
- 使用feed和fetch进行操作的(op)赋值和数据获取
tf程序被构建成图,然后通过运行图被执行。
- 定义op(constant常量也属于op)
import tensorflow as tf
#创建一个常量op 返回一个1*2的矩阵
matrix1 = tf.constant([[3., 3.]])
#创建一个常量op 返回一个2*1的矩阵
matrix2 = tf.constant([[2.],[2.]])
#创建一个乘法op,输入为上面定义的两个常量op 可以把product看做是op定义的操作名
product = tf.matmul(matrix1, matrix2)
- 定义变量Variable
x = tf.Variable([1.0, 2.0])
- 启动图:启动图后,变量被初始化,应增加一个初始化变量的op到图里,并执行这个初始化op
with tf.Session() as sess:
result = sess.run([product])
print result
# 创建一个变量, 初始化为标量 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)
- 指定设备运行图:
如果检测到 GPU, TensorFlow 会尽可能地利用找到的第一个 GPU 来执行操作.如果机器上有超过一个可用的 GPU, 除第一个外的其它 GPU 默认是不参与计算的,为了让 TensorFlow 使用这些 GPU, 你必须将 op 明确指派给它们执行:
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)
设备用字符串进行标识. 目前支持的设备包括:
"/cpu:0"
: 机器的 CPU."/gpu:0"
: 机器的第一个 GPU, 如果有的话."/gpu:1"
: 机器的第二个 GPU, 以此类推.
- fech(执行图时获取的多个 tensor 值,在 op 的一次运行中一起获得(而不是逐个去获取 tensor))
input1 = tf.constant(3.0)
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)
intermed = tf.add(input2, input3)
mul = tf.mul(input1, intermed)
with tf.Session():
result = sess.run([mul, intermed])
print result
# 输出:
# [array([ 21.], dtype=float32), array([ 7.], dtype=float32)]
- feed:(可以临时替代图中的任意操作中的 tensor 可以对图中任何操作提交补丁, 直接插入一个 tensor,常见的用例是将某些特殊的操作指定为 "feed" 操作, 标记的方法是使用 tf.placeholder() 为这些操作创建占位符.)
input1 = tf.placeholder(tf.types.float32)
input2 = tf.placeholder(tf.types.float32)
output = tf.mul(input1, input2)
with tf.Session() as sess:
print sess.run([output], feed_dict={input1:[7.], input2:[2.]})
# 输出:
# [array([ 14.], dtype=float32)]