TensorBoard简介
TensorBoard是Tensorflow自带的一个强大的可视化工具,也是一个web应用程序套件。在众多机器学习库中,Tensorflow是目前唯一自带可视化工具的库,这也是Tensorflow的一个优点。学会使用TensorBoard,将可以帮助我们构建复杂模型。
这里需要理解“可视化”的意义。“可视化”也叫做数据可视化。是关于数据之视觉表现形式的研究。这种数据的视觉表现形式被定义为一种以某种概要形式抽提出来的信息,包括相应信息单位的各种属性和变量。例如我们需要可视化算法运行的错误率,那么我们可以取算法每次训练的错误率,绘制成折线图或曲线图,来表达训练过程中错误率的变化。可视化的方法有很多种。但无论哪一种,均是对数据进行摘要(summary)与处理。
通常使用TensorBoard有三个步骤:
- 首先需要在需要可视化的相关部位添加可视化代码,即创建摘要、添加摘要;
- 其次运行代码,可以生成了一个或多个事件文件(event files);
- 最后启动TensorBoard的Web服务器。
完成以上三个步骤,就可以在浏览器中可视化结果,Web服务器将会分析这个事件文件中的内容,并在浏览器中将结果绘制出来。
如果我们已经拥有了一个事件文件,也可以直接利用TensorBoard查看这个事件文件中的摘要。
Logistic回归的Tensorboard可视化
代码语言:javascript复制from __future__ import print_function
import tensorflow as tf
导入数据集
代码语言:javascript复制# Import MINST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("./data/", one_hot=True)
代码语言:javascript复制Extracting ./data/train-images-idx3-ubyte.gz
Extracting ./data/train-labels-idx1-ubyte.gz
Extracting ./data/t10k-images-idx3-ubyte.gz
Extracting ./data/t10k-labels-idx1-ubyte.gz
参数设置
代码语言:javascript复制# Parameters
learning_rate = 0.01
training_epochs = 25
batch_size = 100
display_epoch = 1
logs_path = './log/example/' # log存放位置
# tf Graph Input
# mnist data image of shape 28*28=784
#(name=''将在Tensorboard中显示)
x = tf.placeholder(tf.float32, [None, 784], name='InputData') #输入数据(InputData)
# 0-9 digits recognition => 10 classes
y = tf.placeholder(tf.float32, [None, 10], name='LabelData') # 输出标签(LabelData)
# Set model weights
W = tf.Variable(tf.zeros([784, 10]), name='Weights') #权重(Weights)
b = tf.Variable(tf.zeros([10]), name='Bias') #偏置(Bias)
构建模型和操作(模型 损失函数 优化 准确率)
代码语言:javascript复制# Construct model and encapsulating all ops into scopes, making
# Tensorboard's Graph visualization more convenient
with tf.name_scope('Model'):
# Model
pred = tf.nn.softmax(tf.matmul(x, W) b) # Softmax
with tf.name_scope('Loss'):
# Minimize error using cross entropy
cost = tf.reduce_mean(-tf.reduce_sum(y * tf.log(pred), reduction_indices=1))
with tf.name_scope('SGD'):
# Gradient Descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
with tf.name_scope('Accuracy'):
# Accuracy
acc = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
acc = tf.reduce_mean(tf.cast(acc, tf.float32))
# Initializing the variables
init = tf.global_variables_initializer()
# Create a summary to monitor cost tensor
tf.summary.scalar("loss", cost)
# Create a summary to monitor accuracy tensor
tf.summary.scalar("accuracy", acc)
# Merge all summaries into a single op
merged_summary_op = tf.summary.merge_all()
训练并保存log
代码语言:javascript复制# Start Training
with tf.Session() as sess:
sess.run(init)
# op to write logs to Tensorboard
summary_writer = tf.summary.FileWriter(logs_path, graph=tf.get_default_graph())
# Training cycle
for epoch in range(training_epochs):
avg_cost = 0.
total_batch = int(mnist.train.num_examples / batch_size)
# Loop over all batches
for i in range(total_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
# Run optimization op (backprop), cost op (to get loss value)
# and summary nodes
_, c, summary = sess.run([optimizer, cost, merged_summary_op],
feed_dict={x: batch_xs, y: batch_ys})
# Write logs at every iteration
summary_writer.add_summary(summary, epoch * total_batch i)
# Compute average loss
avg_cost = c / total_batch
# Display logs per epoch step
if (epoch 1) % display_epoch == 0:
print("Epoch:", 'd' % (epoch 1), "cost=", "{:.9f}".format(avg_cost))
print("Optimization Finished!")
# Test model
# Calculate accuracy
print("Accuracy:", acc.eval({x: mnist.test.images, y: mnist.test.labels}))
print("Run the command line:n"
"--> tensorboard --logdir=./log"
"nThen open http://0.0.0.0:6006/ into your web browser")
代码语言:javascript复制Epoch: 0001 cost= 1.183717763
Epoch: 0002 cost= 0.665147323
Epoch: 0003 cost= 0.552818966
Epoch: 0004 cost= 0.498699070
Epoch: 0005 cost= 0.465521080
Epoch: 0006 cost= 0.442596199
Epoch: 0007 cost= 0.425560050
Epoch: 0008 cost= 0.412205354
Epoch: 0009 cost= 0.401337254
Epoch: 0010 cost= 0.392412475
Epoch: 0011 cost= 0.384738669
Epoch: 0012 cost= 0.378180920
Epoch: 0013 cost= 0.372407395
Epoch: 0014 cost= 0.367316018
Epoch: 0015 cost= 0.362715464
Epoch: 0016 cost= 0.358595766
Epoch: 0017 cost= 0.354887394
Epoch: 0018 cost= 0.351458600
Epoch: 0019 cost= 0.348339875
Epoch: 0020 cost= 0.345448156
Epoch: 0021 cost= 0.342770365
Epoch: 0022 cost= 0.340232303
Epoch: 0023 cost= 0.337901928
Epoch: 0024 cost= 0.335753958
Epoch: 0025 cost= 0.333657109
Optimization Finished!
Accuracy: 0.9136
Run the command line:
--> tensorboard --logdir=./log
Then open http://0.0.0.0:6006/ into your web browser
损失和准确率的可视化
Loss and Accuracy Visualization
计算图模型的基本单元
计算图模型的可视化
Graph Visualization
参考
[TensorBoard: 图表可视化]http://wiki.jikexueyuan.com/project/tensorflow-zh/how_tos/graph_viz.html