TensorBoard可以将训练过程中的各种绘制数据展示出来,包括标量(scalars),图片(images),音频(Audio),计算图(graph),数据分布,直方图(histograms)和嵌入式向量。
使用TensorBoard展示数据,需要在执行Tensorflow就算图的过程中,将各种类型的数据汇总并记录到日志文件中。然后使用TensorBoard读取这些日志文件,解析数据并生产数据可视化的Web页面,让我们可以在浏览器中观察各种汇总数据。
summary_op包括了summary.scalar、summary.histogram、summary.image等操作,这些操作输出的是各种summary protobuf,最后通过summary.writer写入到event文件中。
Tensorflow API中包含系列生成summary数据的API接口,这些函数将汇总信息存放在protobuf中,以字符串形式表达。
对标量数据汇总和记录使用tf.summary.scalar,函数格式如下:
- tf.summary.scalar(tags, values, collections=None, name=None)
使用tf.summary.histogram直接记录变量var的直方图,输出带直方图的汇总的protobuf,函数格式如下:
- tf.summary.histogram(tag, values, collections=None, name=None)
输出带图像的probuf,汇总数据的图像的的形式如下: ' tag /image/0', ' tag /image/1', etc.,如:input/image/0等
- tf.summary.image(tag, tensor, max_images=3, collections=None, name=None)
将上面几种类型的汇总再进行一次合并,具体合并哪些由inputs指定,格式如下:
tf.summary.merge(inputs, collections=None, name=None)
合并默认图形中的所有汇总:
- tf.summaries.merge_all(key='summaries')
将汇总的protobuf写入到event文件中去的相关的类: SummaryWriter是一个类,它可以调用以下成员函数来往event文件中添加相关的数据 addsummary(), add sessionlog(), add_event(), or add_graph()
这里注意,计算图形的信息通过add_graph写入到event文件中。
下面通过MNIST代码例子讲解各种类型数据的汇总和展示的方法。
-
-
- import tensorflow as tf
-
-
-
-
-
-
- from tensorflow.examples.tutorials.mnist import input_data
- max_step = 1000
- learning_rate = 0.001
- dropout = 0.9
- data_dir = '/tmp/tensorflow/mnist/input_data'
- log_dir = 'tmp/tensorflow/mnist/logs/mnist_with_summaries'
-
-
- mnist = input_data.read_data_sets(data_dir, one_hot=True)
- sess = tf.InteractiveSession()
-
-
-
-
-
-
-
- with tf.name_scope('input'):
- x = tf.placeholder(tf.float32, [None, 784], name='x_input')
- y = tf.placeholder(tf.float32, [None, 10], name='y_input')
-
- with tf.name_scope('input_reshape'):
- image_shaped_input = tf.reshape(x, [-1, 28, 28, 1])
- tf.summary.image('input', image_shaped_input, 10)
-
-
-
- def weight_variable(shape):
- initial = tf.truncated_normal(shape, stddev=0.1)
- return tf.Variable(initial)
-
- def bias_variable(shape):
- initial = tf.constant(0.1, shape=shape)
- return tf.Variable(initial)
-
-
-
-
-
-
-
- def variable_summaries(var):
- with tf.name_scope('summaries'):
- mean = tf.reduce_mean(var)
- tf.summary.scalar('mean', mean)
- with tf.name_scope('stddev'):
- stddev = tf.sqrt(tf.reduce_mean(tf.square(var-mean)))
- tf.summary.scalar('stddev', stddev)
- tf.summary.scalar('max', tf.reduce_max(var))
- tf.summary.scalar('min', tf.reduce_min(var))
- tf.summary.histogram('histogram', var)
-
-
-
-
-
-
-
-
-
- def nn_layer(input_tensor, input_dim, output_dim, layer_name,act=tf.nn.relu):
- with tf.name_scope(layer_name):
- with tf.name_scope('weight'):
- weights = weight_variable([input_dim, output_dim])
- variable_summaries(weights)
- with tf.name_scope('biases'):
- biases = bias_variable([output_dim])
- variable_summaries(biases)
- with tf.name_scope('Wx_plus_b'):
- preactivate = tf.matmul(input_tensor, weights) + biases
- tf.summary.histogram('pre_activations', preactivate)
- activations = act(preactivate, name='actvations')
- tf.summary.histogram('activations', activations)
- return activations
-
-
-
-
-
- hidden1 = nn_layer(x, 784, 500, 'layer1')
-
- with tf.name_scope('dropout'):
- keep_prob = tf.placeholder(tf.float32)
- tf.summary.scalar('dropout_keep_probability', keep_prob)
- dropped = tf.nn.dropout(hidden1, keep_prob)
-
- y1 = nn_layer(dropped, 500, 10, 'layer2', act=tf.identity)
-
-
-
-
-
- with tf.name_scope('cross_entropy'):
- diff = tf.nn.softmax_cross_entropy_with_logits(logits=y1, labels=y)
- with tf.name_scope('total'):
- cross_entropy = tf.reduce_mean(diff)
- tf.summary.scalar('cross_entropy', cross_entropy)
-
-
-
-
-
- with tf.name_scope('train'):
- train_step = tf.train.AdamOptimizer(learning_rate).minimize(cross_entropy)
- with tf.name_scope('accuracy'):
- with tf.name_scope('correct_prediction'):
- correct_prediction = tf.equal(tf.argmax(y1, 1), tf.arg_max(y, 1))
- with tf.name_scope('accuracy'):
- accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
- tf.summary.scalar('accuracy', accuracy)
-
-
-
-
-
-
-
-
- merged = tf.summary.merge_all()
- train_writer = tf.summary.FileWriter(log_dir + '/train', sess.graph)
- test_writer = tf.summary.FileWriter(log_dir + '/test')
- tf.global_variables_initializer().run()
-
-
-
-
-
-
- def feed_dict(train):
- if train:
- xs, ys = mnist.train.next_batch(100)
- k = dropout
- else:
- xs, ys = mnist.test.images, mnist.test.labels
- k = 1.0
- return {x: xs, y: ys, keep_prob: k}
-
-
-
-
-
-
-
-
-
-
-
-
-
- saver = tf.train.Saver()
- for i in range(max_step):
- if i % 10 == 0:
- summary, acc = sess.run([merged, accuracy], feed_dict=feed_dict(False))
- test_writer.add_summary(summary, i)
- print('Accuracy at step %s: %s' % (i, acc))
- else:
- if i % 100 == 99:
- run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)
- run_metadata = tf.RunMetadata()
- summary, _ = sess.run([merged, train_step], feed_dict=feed_dict(True),
- options=run_options, run_metadata=run_metadata)
- train_writer.add_run_metadata(run_metadata, 'step%03d' % i)
- train_writer.add_summary(summary, i)
- saver.save(sess, log_dir+"/model.ckpt", i)
- print('Adding run metadata for', i)
- else:
- summary, _ = sess.run([merged, train_step], feed_dict=feed_dict(True))
- train_writer.add_summary(summary, i)
- train_writer.close()
- test_writer.close()
之后切换到Linux终端命令下,执行TensorBoard程序,并通过--logdir指定TensorFlow日志路径,然后哦=TensorBoard就可以自动生成所有汇总数据可视化的结果来。
- tensorboard --logdir=/tmp/tensorflow/mnist/logs/mnist_with_summaries
执行上面的命令后,出现一条提示信息,复制其中的网址到浏览器,就可以看到数据可视化的图标来。
- Starting TensorBoard b'39' on port 6006
- (You can naviiage to http://0.0.0.0.6006)
以下是tensorFlow1.0以下版本的方式,可供其他版本的同学借鉴下:
使用tf.scalar_summary来收集想要显示的变量,使用scalar_summary的时候,注意tag和tensor的shape一致,tf.scalar_summary(节点名称,获取的数据),例如:下文代码实例中的loss以及accurary都可以使用。
各层网络权重、偏置的分布,用histogram_summary函数。
historgram_summary用于生成分布图,也可以用saclar_summary记录存数值;前者在history一栏里查看分布图,后者在event一栏中查看数值变化情况。
当需要获取的数据较多的时候,我们一个一个去保存获取到的数据,以及一个一个去运行会显得比较麻烦。tensorflow提供了一个简单的方法,就是合并所有的summary data的获取函数,保存和运行只对一个对象进行操作。比如,写入默认路径中,比如/tmp/mnist_logs (by default)
定义一个summury op, 用来汇总多个变量
- merged = tf.merge_all_summaries()
得到一个summy writer,指定写入路径
添加写入
- train_writer.add_summary()
以下为完整实例代码:
-
-
-
- import tensorflow as tf
- import numpy as np
-
-
- def add_layer(inputs, in_size, out_size, n_layer, activation_function=None):
-
- 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
-
-
-
- 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
-
-
- 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')
-
-
- l1 = add_layer(xs, 1, 10, n_layer=1, activation_function=tf.nn.relu)
-
- prediction = add_layer(l1, 10, 1, n_layer=2, activation_function=None)
-
-
- 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)
-
- 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)
接下来,程序开始运行以后,跑到shell里运行,打开终端,输入如下语句:
cd到指定的文件下
-- = ‘logs/
开始运行tensorboard。接下来打开浏览器,进入127.0.0.1:6006 就能够看到loss值在训练中的变化了。