tensorboard是tensorflow的可视化工具,它可以通过tensorflow程序运行过程中输出的日志文件可视化tensorflow程序的运行状态。
我们在简单理解tensorboard的过程中仍然以以前写过的tensorflow识别mnist手写数字为例。
我们先用最简单的识别手写数字的神经网络为例,学习tensorboard的可视化。先上代码:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#载入数据集
mnist = input_data.read_data_sets("MNIST_data",one_hot=True)
#可视化结构 定义命名空间
with tf.name_scope('input'):
#定义两个placeholder
x = tf.placeholder(tf.float32,[None,784],name='x-input')
y = tf.placeholder(tf.float32,[None,10],name='y-input')
#创建一个简单的神经网络
with tf.name_scope('layer'):
with tf.name_scope('wight'):
W = tf.Variable(tf.zeros([784,10]),name='W')
with tf.name_scope('biases'):
b = tf.Variable(tf.zeros([10]),name='b')
with tf.name_scope('wx_plus'):
wx_plus_b = tf.matmul(x,W)+b
with tf.name_scope('softmax'):
prediction = tf.nn.softmax(wx_plus_b)
#每个批次的大小
batch_size = 20
#计算一共有多少个批次
n_batch = mnist.train.num_examples // batch_size
#二次代价函数
with tf.name_scope('loss'):
loss = tf.reduce_mean(tf.square(y-prediction))
#梯度下降
with tf.name_scope('train'):
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
#初始化变量 不用命名空间
init = tf.global_variables_initializer()
with tf.name_scope('Accuracy'):
with tf.name_scope('correct_prediction'):
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))
with tf.name_scope('accuracy'):
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
#结果存放在一个布尔型列表中
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))#argmax返回一维张量中最大的值所在的位置
#求准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))#将correct_prediction先转化为浮点型,然后求平均值就是准确率
with tf.Session() as sess:
sess.run(init)
writer = tf.summary.FileWriter('logs/',sess.graph)
for epoch in range(1):
for batch in range(n_batch):
batch_xs,batch_ys = mnist.train.next_batch(batch_size)
sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys})
acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})
print("Iter " + str(epoch) + ",Testing Accuracy " + str(acc))
程序只是为了查看tensorboard,所以只训练了一次
注意程序中 writer = tf.summary.FileWriter('logs/',sess.graph) 将执行后产生LAPTOP-DJHPNJDG格式的文件保存在了logs文件夹下,LAPTOP-DJHPNJDG格式的文件就是程序日志,tensorboard保存了最新程序日志产生的可视化结构。
将程序执行后,在保存程序的当前目录下,找到 logs 这一文件夹,发现了其中含有LAPTOP-DJHPNJDG格式的文件
1.打开命令提示符,win用户需要将命令移动到logs所在盘,比如程序当前目录在D盘则输入 d:
2.接着输入tensorboard --logdir= logs文件夹下LAPTOP-DJHPNJDG格式的文件路径
比如我输入tensorboard --logdir=D:\tensorflow\logs
3.执行后会出现一个类似http://LAPTOP-DJHPNJDG:6006的网址,复制后用浏览器打开就会出现tensorboard的页面
- 我们会看到下图的标题栏

- 在graphs选项中看到以下

以上出现的框图很好的展示了神经网络的结构,经过实线和虚线连接的节点,框图节点里面还包含了各种小框图节点。
tensorboard还支持手动调整可视化结果,可以将节点加入或者移动出主图。
这些操作需要真正的实践。
我们看到tensorboard将同一个命名空间下的所有节点缩成一个点,只有顶层的命名空间才会被显示。
与原程序相比,在tensorboard可视化程序中我们加入了命名空间的管理,使用tf.name_scope函数或者tf.variable_scope函数
程序中的输入层、输出层、隐藏层及其偏置和权重以及代价函数,优化方式等等都可以用命名空间进行管理。
1094

被折叠的 条评论
为什么被折叠?



