1. 为什么需要可视化?
在训练庞大的深度神经网络,为了能够更好的理解运算过程,需要使用可视化的工具将其过程进行描述,在tensorflow中使用TensorBoard 来绘制图像生成的定量指标图以及附加数据;
2. 主要流程
TensorBoard 通过读取tensorflow的事件文件来运行,在事件文件中包含运行中设计的主要数据。
(1) 创建tensorflow图,对节点进行汇总操作,使用 tf.summary.scalar('loss',loss)
(2) 将所有的汇总操作合并,使用: merged = tf.summary.merge_all()
(3) 获取写文件的工具 writer = tf.summary.FileWriter('logs/',sess.graph)
(4) 将需要统计信息写入文件 writer.add_summary(summary,epoch)#将变量和迭代次数写入
3. TensorBoard 使用
(1) cmd打开命令提示框,切换到指定文件根目录;(如,e:) (2) 输入命令:tensorboard --logdir=E:\Python\tensorflow_test\tensorborad\logs (3) 在浏览器访问:http://DESKTOP-MQ30F76:6006
3. 流程可视化(模块命名)
# coding=utf-8
'''
tensorborad图示化网络的执行流程
'''
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#1.加载数据
mnist = input_data.read_data_sets('data/MNIST_data',one_hot=True)
#2.使用小批量训练,定义批次大小
batch_size = 100
#计算训练次数
batch_num = mnist.train.num_examples//batch_size
#3.定义占位符
#创建命名空间
with tf.name_scope('input'):
x = tf.placeholder(tf.float32,[None,784],name='x_input')#输入的占位符
y = tf.placeholder(tf.float32,[None,10],name='y_input')#输出的占位符
#4.定义网络结构
with tf.name_scope('layer'):
with tf.name_scope('weights'):
W = tf.Variable(tf.zeros([784,10]),name='W')
with tf.name_scope('biase'):
b = tf.Variable(tf.zeros([10]),name='b')
#预测
with tf.name_scope('wx_plus_b'):
wx_plus_b = tf.matmul(x,W)+b
with tf.name_scope('softmax'):
predict = tf.nn.sigmoid(wx_plus_b,name='softmax')
#代价函数
with tf.name_scope('loss'):
loss = tf.reduce_mean(tf.square(y-predict))
#梯度下降
with tf.name_scope('train'):
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
#5.开始训练
init = tf.global_variables_initializer()
#结果存储在布尔列表中(概率最大的位置是否相等)
with tf.name_scope('accuracy'):
with tf.name_scope('correct_prediction'):
correct_prediction = tf.equal(tf.a