tensorflow学习笔记三——可视化tensorboard

时间:2021-12-15 23:30:31

本笔记主要讲如何运用tensorflow看自己创建网络的结构。

  • 可以通过with tf.name_scope(‘weights’):来添加模块的名称,并且with可以嵌套。对于变量也可以通过name参数来定义名字。然后在终端里输入
    tensorboard –logdir=logs,再在浏览器里打开相应地址即可。
from __future__ import print_function
import tensorflow as tf


def add_layer(inputs, in_size, out_size, activation_function=None):
# add one more layer and return the output of this layer
with tf.name_scope('layer'):
with tf.name_scope('weights'):
Weights = tf.Variable(tf.random_normal([in_size, out_size]), name='W')
with tf.name_scope('biases'):
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='b')
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, )
return outputs


# 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, activation_function=tf.nn.relu)
# add output layer
prediction = add_layer(l1, 10, 1, 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]))

with tf.name_scope('train'):
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

sess = tf.Session()
writer = tf.train.SummaryWriter("logs/", sess.graph)
# important step
sess.run(tf.initialize_all_variables())

下图是Tensorboard所显示信息的示意图,其中的横坐标是tag,纵坐标是run,呈现元素的内容由tag和run来决定。
tensorflow学习笔记三——可视化tensorboard
如图中所示,tag包括: 标量(scalar) :纯粹的数值型的统计量随时间的变化曲线,包括accuracy、dropout、bias、weight、交叉熵等; 直方图(histogram): 其实不是直方图,而是数据的分布随时间的变化的图形。包括weight、bias、activation、pre-activation等。数据分布是通过百分位数(percentile)来指示的。关于百分位数,我在这里加了一个注解,可以了解基本概念。 图像(images): 如果是涉及图像方面的应用,可以用来观察过程中的图像。 图形(graph): 张量和操作通过边连接 起来构成的图形,tensorboard可以直观展示代码中构成的图形的连接关系。

同时,可以通过tf.histogram_summary,tf.scalar_summary创建图表,来观察神经网络中各个值的变化情况。

from __future__ import print_function
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)

Tensorboard的数据来源

Tensorboard前台呈现的数据是tensorflow程序执行过程中,将一些summary类型的数据写入到日志目录的event文件中的。下图标识了数据的写入过程。
tensorflow学习笔记三——可视化tensorboard
如图中所示,summary_op包括了scalarSummary、HistogramSummary、ImageSummary等操作,这些操作输出的是各种summary protobuf,最后通过SummaryWriter写入到event文件中。