利用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))
其計算圖的可視化結果如下所示: