张量tensor:
TensorFlow即Tensor(张量)+Flow(流动).Tensor即张量,TensorFlow中的所有数据都称之为tensor,程序中数据的流转都是采用tensor的形式进行的.
图graph:
TensorFlow用图(graph)来表示计算任务,图中的节点被称为op(operation),一个op获得0个或多个张量(tensors).TensorFlow中有一个默认图,op构造器可以为其增加节点.
会话Session:
图必须在会话(Session)里被启动.会话(Session)将图分发到设备(CPU/GPU)上,并提供执行节点op的方法,计算结果以tensor返回(Python中返回的是numpy ndarray对象).Session提供的是运行环境,用完要及时释放.释放方式有两种:显式关闭/调用代码块.
1.显式关闭
直接调用Session.close():
# 计算两个向量的乘积:
import tensorflow as tf
# 产生一个 1x2 矩阵,加到默认图中
# 两个常量op
matrix1 = tf.constant([[3., 1.]])
matrix2 = tf.constant([[2.], [3.]])
# 一个矩阵乘法op
product = tf.matmul(matrix1, matrix2)
# 启动默认图
sess = tf.Session()
# 函数调用run()触发图中三个op的执行
result = sess.run(product)
print result
# 关闭会话
sess.close()
输出:
[[ 9.]]
2.采用代码块
使用with句块开始一个会话,在with句块结束时会话(Session)会被自动析构释放掉.
示例:
# 计算两个向量的乘积:
import tensorflow as tf
# 产生一个 1x2 矩阵,加到默认图中
# 两个常量op
matrix1 = tf.constant([[3., 1.]])
matrix2 = tf.constant([[2.], [3.]])
# 一个矩阵乘法op
product = tf.matmul(matrix1, matrix2)
with tf.Session() as sess:
result = sess.run([product])
print result
输出:
[array([[ 9.]], dtype=float32)]
示例中的默认图有3个节点,2个constant节点,1个matmul节点,然后在会话session中载入这个图,进行矩阵运算得到结果.
会话(Session)将图分发到设备(CPU/GPU)上:
当设备上不止一个GPU时,需要使用with…Device语句指定op操作到不同的CPU或GPU上.
使用字符串指定设备的标识:
- “/cpu:0”:CPU
- “/gpu:0”:第一个GPU
- “/gpu:1”:第二个GPU
示例:
import tensorflow as tf
with tf.Session() as sess:
with tf.device("/cpu:0"):
matrix1 = tf.constant([[1., 3., 1]])
matrix2 = tf.constant([[3.], [2.], [1.]])
product = tf.matmul(matrix1, matrix2)
sess = tf.Session()
result = sess.run([product])
print result
输出:
[array([[ 10.]], dtype=float32)]
交互式 TensorFlow 会话:
在类似IPython的交互式Python环境中,可以使用InteractiveSession代替Session类.使用Tensor.eval()和Operation.run()代替Session.run(),可避免用一个变量来持有会话.
# 交互式TensorFlow会话
import tensorflow as tf
# 使用InteractiveSession代替Session类
sess = tf.InteractiveSession()
x = tf.Variable([1., 2.])
a = tf.constant([3., 2.])
# 用Tensor.eval()和Operation.run()方法代替Session.run()
# 避免使用一个变量来持有会话
# 使用初始化器initializer run()方法初始化x
x.initializer.run()
# 从x减去a
sub = tf.subtract(x, a)
print sub.eval()
输出:
[-2. 0.]