tensorflow Tensorboard可视化

tensorboard --logdir=绝对路径

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
import os
learning_rate = 0.01
training_epochs = 25
batch_size = 100
display_step = 1
curpath=os.getcwd()
logs_path=curpath+'/tmp/tensorflow_logs/example/'
try:
    os.makedirs(logs_path)
except:
    print('Existing')
n_hidden_1=256
n_hidden_2=256
n_input=784
n_classes=10

x=tf.placeholder(tf.float32, [None,784], name='InputData')
y=tf.placeholder(tf.float32,[None,10],name='LabelData')

def multilayer(x, weights, biases):
    layer_1 = tf.nn.relu(tf.matmul(x,weights['h1'])+biases['b1'])
    tf.summary.histogram('relu1', layer_1)
    layer_2 = tf.nn.relu(tf.matmul(layer_1,weights['h2'])+biases['b2'])
    tf.summary.histogram('relu2', layer_2)
    output=tf.matmul(layer_2, weights['out'])+biases['out']
    tf.summary.histogram('output', output)
    return output
weights = {
    'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
    'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
    'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))
}

biases = {
    'b1': tf.Variable(tf.random_normal([n_hidden_1])),
    'b2': tf.Variable(tf.random_normal([n_hidden_2])),
    'out': tf.Variable(tf.random_normal([n_classes]))
}

with tf.name_scope('Model'):
    pre=multilayer(x,weights,biases)

with tf.name_scope('Loss'):
    loss=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pre, labels=y))

with tf.name_scope('SGD'):
    optimizer = tf.train.GradientDescentOptimizer(learning_rate)
    grads=tf.gradients(loss, tf.trainable_variables())
    grads=list(zip(grads, tf.trainable_variables()))
    apply_grads=optimizer.apply_gradients(grads_and_vars=grads)
with tf.name_scope('Accuracy'):
    acc = tf.equal(tf.argmax(pre,1),tf.argmax(y,1))
    acc = tf.reduce_mean(tf.cast(acc,tf.float32))
init = tf.global_variables_initializer()

tf.summary.scalar('loss',loss)
tf.summary.scalar('accuracy',acc)
for var in tf.trainable_variables():
    tf.summary.histogram(var.name, var)
for grad, var in grads:
    tf.summary.histogram(var.name+'/gradient', grad)
merged_summary_op = tf.summary.merge_all()

with tf.Session() as sess:
    sess.run(init)
    summary_writer = tf.summary.FileWriter(logs_path,graph=tf.get_default_graph())
    for epoch in range(3):
        avg_cost=0.
        total_batch=mnist.train.num_examples//batch_size
        for i in range(total_batch):
            batch_xs, batch_ys=mnist.train.next_batch(batch_size)
            _, c, summary = sess.run([apply_grads,loss,merged_summary_op],feed_dict={x:batch_xs,y:batch_ys})
            summary_writer.add_summary(summary, epoch*total_batch+i)
            avg_cost += c/total_batch
        if epoch % display_step==0:
            print('Epoch:',epoch+1,'Loss:',avg_cost)
    correct_pre=tf.equal(tf.argmax(y,1),tf.argmax(pre,1))
    accuracy = tf.reduce_mean(tf.cast(correct_pre,tf.float32))
    print('Test accuracy:',accuracy.eval({x:mnist.test.images,y:mnist.test.labels}))
    

;