第5章 Tensorboard

TensorBoard是一个可视化工具,能够有效地展示Tensorflow在运行过程中的计算图、各种指标随着时间的变化趋势以及训练中使用到的数据信息。

5.1 Tensorboard网络结构

Tensorflow 自带 tensorboard ,可以自动显示我们所建造的神经网络流程图,有助于你发现编程中间的问题和疑问。

这里写图片描述

图1

同时我们也可以展开看每个layer中的一些具体的结构:
这里写图片描述

图2

好了,通过阅读代码和之前的图片我们大概知道了此处是有一个输入层(inputs),一个隐含层(layer),还有一个输出层(output) 现在可以看看如何进行可视化。
我们先看完完整代码吧。
【代码参看附件test1_tensorboard1.py】

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt#需要安装才可使用

#添加层
def add_layer(inputs, in_size, out_size, activation_function=None):

    #线性模型
    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

#【1】创建原始数据,及要训练的数据
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

#【2】定义节点,输入网络
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')

#【3】定义神经层:隐藏层和预测层
#添加隐藏层,输入值是 xs,在隐藏层有 10 个神经元  
l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)
#添加输出层,输入值是隐藏层 l1,在预测层输出 1 个结果
prediction = add_layer(l1, 10, 1, activation_function=None)

#【4】定义损失函数,误差的均方差
with tf.name_scope('loss'):
    loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),
                                        reduction_indices=[1]))
#【5】选择 optimizer 使 loss 达到最小,选择梯度下降的方法训练数据
with tf.name_scope('train'):
    train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

#【6】初始化数据,tf 的必备步骤,主要声明了变量,就必须初始化才能用
init = tf.initialize_all_variables()

#【7】创建Session会话。启动图
sess = tf.Session()
#writer = tf.train.SummaryWriter("logs/", sess.graph)#新版的TensorFlow已经弃用
writer = tf.summary.FileWriter("logs/",sess.graph)#加载文件

#上面定义的都没有运算,直到 sess.run 才会开始运算
sess.run(init)

运行成功后会在你存放文件的文件夹下生成下列文件。

这里写图片描述

图3生成的网络图文件

打开 terminal,进入你存放的文件夹地址上一层,笔者存放的文件夹是logs。因此,要进入logs的上一级文件,运行命令 tensorboard –logdir=’logs/’ 后会返回一个地址。
这里写图片描述
地址为:http://(主机名):6006/。
然后用浏览器打开这个地址。
这里写图片描述

图4

点击 graph 标签栏下就可以看到流程图了:
这里写图片描述

图5

【注1】在Windows平台上运行命令应用tensorboard –logdir=logs/
【注2】笔者在上述代码中已经进行详细注释了,再次就不在赘述了。

5.2 Tensorboard网络运行

好了,前文讲解的是神经网络的图,接下来在上文的基础上继续使用tensorboard。我们直接上代码吧。
【代码参看附件test2_tensorboard2】

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt#需要安装才可使用

#添加层
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'):
        with tf.name_scope('weights'):
            Weights = tf.Variable(tf.random_normal([in_size, out_size]), name='W')
            tf.summary.histogram(layer_name + '/weights', Weights)
            #tf.histogram_summary(layer_name + '/weights', Weights)#新版已经废弃
        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)
            tf.summary.histogram(layer_name + '/biases', biases)
        if activation_function is None:
            outputs = Wx_plus_b
        else:
            outputs = activation_function(Wx_plus_b, )
        tf.summary.histogram(layer_name + '/outputs', outputs)
        return outputs

#【1】创建原始数据,及要训练的数据
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

#【2】定义节点,输入网络
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')

#【3】定义神经层:隐藏层和预测层
#添加隐藏层,输入值是 xs,在隐藏层有 10 个神经元  
l1 = add_layer(xs, 1, 10, n_layer=1, activation_function=tf.nn.relu)
#添加输出层,输入值是隐藏层 l1,在预测层输出 1 个结果
prediction = add_layer(l1, 10, 1, n_layer=2, activation_function=None)

#【4】定义损失函数,误差的均方差
with tf.name_scope('loss'):
    loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),
                                        reduction_indices=[1]))
    tf.summary.scalar('loss', loss)

#【5】选择 optimizer 使 loss 达到最小,选择梯度下降的方法训练数据
with tf.name_scope('train'):
    train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

#【6】初始化数据,tf 的必备步骤,主要声明了变量,就必须初始化才能用
init = tf.initialize_all_variables()

#【7】创建Session会话。启动图
sess = tf.Session()

#merged = tf.merge_all_summaries()#新版已经废弃
merged = tf.summary.merge_all()
#writer = tf.train.SummaryWriter("logs/", sess.graph)#新版的TensorFlow已经弃用
writer = tf.summary.FileWriter("logs/",sess.graph)#加载文件

#上面定义的都没有运算,直到 sess.run 才会开始运算
sess.run(init)

#【8】训练数据
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)

运行成功后,可以通过网页查看。

这里写图片描述

图6

【注1】前文的几个代码请对比查看其中的异同,笔者在代码中也已经详细的注释了,请仔细阅读吧。
【注2】在使用Spyder的时候,如果多次运行代码,TensorBoard会跟踪生成多个结果。因此注意在每次查看TensorBoard前Restart Kernel。

这里写图片描述

图7

本章参考代码

点击进入

TensorFlow中API版本容错

#writer = tf.train.SummaryWriter(“logs/”, sess.graph)#新版的TensorFlow已经弃用
writer = tf.summary.FileWriter(“logs/”,sess.graph)#加载文件

#tf.histogram_summary(layer_name + ‘/weights’, Weights)#新版已经废弃
tf.summary.histogram(layer_name + ‘/weights’, Weights)

#tf.scalar_summary(‘loss’, loss)#新版已经废弃
tf.summary.scalar(‘loss’, loss)

#merged = tf.merge_all_summaries()#新版已经废弃
merged = tf.summary.merge_all()

猜你喜欢

转载自blog.csdn.net/u013162035/article/details/80924255
今日推荐