利用Tensorboard进行可视化
真是出来混迟早是要还的,之前一直拒绝学习Tensorboard,因为实在是有替代方案,直到发现到了不得不用的地步。下面主要介绍一下怎么使用Tensorboard来可视化参数,损失以及准确率等变数。
1.可视化计算图
下面是一个单层网路的手写体分类示例:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
batch_size = 100
n_batch = mnist.train.num_examples // batch_size
with tf.name_scope(input):
x = tf.placeholder(dtype=tf.float32, shape=[None, 784], name=x_input)
y = tf.placeholder(dtype=tf.int32, shape=[None, 10], name=y_input)
with tf.name_scope(layer):
with tf.name_scope(weights):
W = tf.Variable(tf.random_uniform([784, 10]), name=w)
with tf.name_scope(biases):
b = tf.Variable(tf.zeros(shape=[10], dtype=tf.float32), name=b)
with tf.name_scope(softmax):
prediction = tf.nn.softmax(tf.nn.xw_plus_b(x, W, b))
with tf.name_scope(Loss):
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=prediction))
with tf.name_scope(train):
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss)
with tf.name_scope(acc):
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(prediction, 1))
acc = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
writer = tf.summary.FileWriter(logs/, sess.graph)
for epoch in range(20):
for batch in range(n_batch):
batch_x, batch_y = mnist.train.next_batch(batch_size)
_, accuracy = sess.run([train_step, acc], feed_dict={x: batch_x, y: batch_y})
if batch % 50 == 0:
print("### Epoch: {}, batch: {} acc on train: {}".format(epoch, batch, accuracy))
accuracy = sess.run(acc, feed_dict={x: mnist.test.images, y: mnist.test.labels})
print("### Epoch: {}, acc on test: {}".format(epoch, accuracy))
其计算图的可视化结果如下所示: