TensorFlow学习(二)——Graph可视化
TensorFlow使用数据流图实现计算任务,有的图比较简单,仅包含少量的节点和张量,但现实中的模型往往比较复杂,包含众多的节点和参数。这次,就需要创建多个数据流图,并使用名称作用域(name scope)来组织数据流图,同时,也方便使用TensorBoard对graph进行可视化。
(1)创建Graph对象
在一般的TensorFlow程序中,会使用默认的数据流图。当模型比较复杂时,就需要创建多个流图协同工作。
import tensorflow as tf
#获取默认数据流图
default_graph = tf.get_default_graph()
#创建一个新的数据流图
g = tf.Graph()
with g.as_default():
# 将操作添加到默认的graph中
a = tf.add(2,3)
(2)名称作用域
名称作用域本质上就是将op划分到多个不同、有名称的语句块中,方便可视化。
# 定义名称作用域A
with tf.name_scope('A'):
A_mul = tf.multiply(in_1, in_2)
A_out = tf.subtract(A_mul, in_1)
# 定义名称作用域B
with tf.name_scope('B'):
B_mul = tf.multiply(in_2, const)
B_out = tf.subtract(B_mul, in_2)
(3)保存Graph
使用tf.summary.FileWriter保存图到磁盘。
write = tf.summary.FileWriter('./name_scope', graph=graph)
write.close()
(4)TensorBoard可视化
命令行到当前目录,使用命令启动TensorBoard,默认会在本地计算机启动一个端口号为6006的TensorBoard服务器。打开浏览器,在地址栏输入 localhost:6006,查看图。
$ tensorboard --logdir=./name_scope/
(5) 示例
代码
import tensorflow as tf
graph = tf.Graph()
with graph.as_default():
in_1 = tf.placeholder(tf.float32,shape=[], name='input_a')
in_2 = tf.placeholder(tf.float32,shape=[], name='input_b')
const = tf.constant(3,dtype=tf.float32,name='static_value')
with tf.name_scope('Transformation'):
with tf.name_scope('A'):
A_mul = tf.multiply(in_1, in_2)
A_out = tf.subtract(A_mul, in_1)
with tf.name_scope('B'):
B_mul = tf.multiply(in_2, const)
B_out = tf.subtract(B_mul, in_2)
with tf.name_scope('C'):
C_div = tf.div(A_out, B_out)
C_out = tf.add(C_div, const)
with tf.name_scope('D'):
D_div = tf.div(B_out, A_out)
D_out = tf.add(D_div, const)
out = tf.maximum(C_out, D_out)
write = tf.summary.FileWriter('./name_scope2', graph=graph)
write.close()
可视化结果