tensorboard使用详解

先说使用步骤:

1.对标量数据汇总和记录使用tf.summary.scalar,函数格式如下:

tf.summary.scalar(tags, values, collections=None, name=None)

2.使用tf.summary.histogram直接记录变量var的直方图

3.将要保存的变量存在一起

merged_summary_op = tf.summary.merge_all()

4.写入记录数据文件

summary_writer = tf.summary.FileWriter("logs/",sess.graph)

5.运行所有保存变量,并将值写入

summary_str = sess.run(merged_summary_op,feed_dict={x: x_train_a, y_: y_train_a})
summary_writer.add_summary(summary_str, epoch)

6.在命令行里输入下列代码(pycharm在左下角teminal里输入即可),会跳出网址,注意用谷歌浏览器,其他浏览器可能会出问题!
tensorboard --logdir=logs

注:输入步骤6时要先将文件目录跳转到logs上一层,注意是上一层(用 cd logs即可),有些博客说跳进logs里再操作是错的!另外在tf.summary.scalar存loss,acc之类值时一定要保证是标量才能存,不然会出错!

代码案例:

import tensorflow as tf
import numpy as np
 
 
def add_layer(inputs, in_size, out_size, n_layer, activation_function=None):
    # add one more layer and return the output of this layer
    layer_name = 'layer%s' % n_layer
    with tf.name_scope(layer_name):
        with tf.name_scope('weights'):
            Weights = tf.Variable(tf.random_normal([in_size, out_size]), name='W')
            tf.histogram_summary(layer_name + '/weights', Weights)
        with tf.name_scope('biases'):
            biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='b')
            tf.histogram_summary(layer_name + '/biases', biases)
        with tf.name_scope('Wx_plus_b'):
            Wx_plus_b = tf.add(tf.matmul(inputs, Weights), biases)
        if activation_function is None:
            outputs = Wx_plus_b
        else:
            outputs = activation_function(Wx_plus_b, )
        tf.histogram_summary(layer_name + '/outputs', outputs)
        return outputs
 
 
# Make up some real data
x_data = np.linspace(-1, 1, 300)[:, np.newaxis]
noise = np.random.normal(0, 0.05, x_data.shape)
y_data = np.square(x_data) - 0.5 + noise
 
# define placeholder for inputs to network
with tf.name_scope('inputs'):
    xs = tf.placeholder(tf.float32, [None, 1], name='x_input')
    ys = tf.placeholder(tf.float32, [None, 1], name='y_input')
 
# add hidden layer
l1 = add_layer(xs, 1, 10, n_layer=1, activation_function=tf.nn.relu)
# add output layer
prediction = add_layer(l1, 10, 1, n_layer=2, activation_function=None)
 
# the error between prediciton and real data
with tf.name_scope('loss'):
    loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),
                                        reduction_indices=[1]))
    tf.scalar_summary('loss', loss)
 
with tf.name_scope('train'):
    train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
 
sess = tf.Session()
merged = tf.merge_all_summaries()
writer = tf.train.SummaryWriter("logs/", sess.graph)
# important step
sess.run(tf.initialize_all_variables())
 
for i in range(1000):
    sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
    if i % 50 == 0:
        result = sess.run(merged, feed_dict={xs: x_data, ys: y_data})
        writer.add_summary(result, i)

refer blog

你可能感兴趣的:(Tensorflow学习之路)