1.前言
本节内容会用到浏览器, 而且与 tensorboard 兼容的浏览器是 “Google Chrome”. 使用其他的浏览器不保证所有内容都能正常显示.
学会用 Tensorflow 自带的 tensorboard 去可视化我们所建造出来的神经网络是一个很好的学习理解方式. 用最直观的流程图告诉你你的神经网络是长怎样,有助于你发现编程中间的问题和疑问.
2.搭建网络图纸
2.1.定义输入
首先从 Input 开始,对于input我们进行如下修改: 首先,可以为xs指定名称为x_in,然后再次对ys指定名称y_in。
这里指定的名称将来会在可视化的图层inputs中显示出来
使用with tf.name_scope(‘inputs’)可以将xs和ys包含进来,形成一个大的图层,图层的名字就是with tf.name_scope()方法里的参数。
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')
2.2.定义layer层
在定义完大的框架layer之后,同时也需要定义每一个’框架‘里面的小部件:(Weights biases 和 activation function): 现在现对 Weights 定义: 定义的方法同上,可以使用tf.name.scope()方法,同时也可以在Weights中指定名称W。 即为:
import tensorflow as tf
def add_layer(inputs,in_size,out_size,activation_function):
with tf.name_scope('layer'): #命名域:tf.name_scope() 变量域:tf.variable_scope()
with tf.name_scope('weight'):
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
最后编辑loss部分:将with tf.name_scope()添加在loss上方,并为它起名为loss
with tf.name_scope('loss'):
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),reduction_indices=[1]))
使用with tf.name_scope()再次对train_step部分进行编辑,如下:
with tf.name_scope('train'):
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
2.3.保存绘制的图到目录
我们需要使用 tf.summary.FileWriter() (tf.train.SummaryWriter() 这种方式已经在 tf >= 0.12 版本中摒弃) 将上面‘绘画’出的图保存到一个目录中,以方便后期在浏览器中可以浏览。 这个方法中的第二个参数需要使用sess.graph , 因此我们需要把这句话放在获取session的后面。 这里的graph是将前面定义的框架信息收集起来,然后放在logs/目录下面。
sess = tf.Session()
writer = tf.summary.FileWriter('logs/',sess.graph)
init = tf.global_variables_initializer()
sess.run(init)
2.4.浏览器查看绘制的图
最后在你的terminal(终端)中 ,使用以下命令
$ tensorboard --logdir='logs/'
同时将终端中输出的网址(http://localhost:6006)复制到浏览器中,便可以看到之前定义的视图框架了。
tensorboard 还有很多其他的参数,希望大家可以多多了解, 可以使用 tensorboard --help 查看tensorboard的详细参数