Tensorflow中可视化好助手Tensorboard(一)


学会用Tensorflow自带的Tensorboard去可视化我们所构建的神经网络是一个很好的学习理解方式。用最直观的流程图告诉你,你的神经网络长什么样子,有助于你发现编程中出现的问题和疑问。

首先,看效果图:


同时,我们也可以展开看看每层layer中的一些具体结构:


其实我们展示的就是上篇文章《用Tensorflow构建一个神经网络》 的结构,地址如下:

https://blog.csdn.net/program_developer/article/details/80192550

其次,介绍神经网络可视化的具体步骤和代码:

1.从Input开始:

# 利用占位符定义我们所需要的神经网络的输入。  
# None代表无论输入有多少样本都可以。因为输入只有一个特征,所以这里是1。  
xs = tf.placeholder(tf.float32,[None,1])  
ys = tf.placeholder(tf.float32,[None,1]) 

对于input,我们进行修改如下:首先,可以为xs指定名称为:x_input,为ys指定名称为:y_input。然后使用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. 接下来开始编辑layer层。

编辑前的layer层代码:

# 构造添加一个神经层的函数  
def add_layer(inputs,in_size,out_size,activation_function=None):  
    # 定义weights为一个in_size行,out_size列的随机变量矩阵  
    Weights = tf.Variable(tf.random_normal([in_size,out_size]))  
    biases = tf.Variable(tf.zeros([1,out_size])) + 0.1  
    Wx_plus_b = tf.matmul(inputs,Weights) + biases  
    if activation_function is None:  
        outputs = Wx_plus_b  
    else:  
        outputs = activation_function(Wx_plus_b)  
    return outputs  

这里的名字应该叫layer,下面是编辑后的:

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'):
        Weights= tf.Variable(tf.random_normal([in_size, out_size]))
        # and so on...

在定义完大的框架layer之后,同时也需要定义每一个layer里面的小部件:(Weights、biases和activation function):现在对Weights定义:也是使用tf.name.scope()方法,同时也可以在Weights中指定名字:W

   def add_layer(inputs, in_size, out_size, activation_function=None):
	#define layer name
    with tf.name_scope('layer'):
        #define weights name 
        with tf.name_scope('weights'):
            Weights= tf.Variable(tf.random_normal([in_size, out_size]),name='W')
        #and so on......

接着定义biases,定义方法同上。

def add_layer(inputs, in_size, out_size, activation_function=None):
    #define layer name
    with tf.name_scope('layer'):
        #define weights name 
        with tf.name_scope('weights')
            Weights= tf.Variable(tf.random_normal([in_size, out_size]),name='W')
        # define biase
        with tf.name_scope('Wx_plus_b'):
            Wx_plus_b = tf.add(tf.matmul(inputs, Weights), biases)
        # and so on....

activation_function的话,可以暂时忽略。因为当你自己选择用tensorflow中的激活函数(activation function)的时候,tensorflow会默认添加名称。最终,layer形式如下:

# 构造添加一个神经层的函数
def add_layer(inputs,in_size,out_size,activation_function=None):
    with tf.name_scope("layer"):
        with tf.name_scope("weights"):
            # 定义weights为一个in_size行,out_size列的随机变量矩阵
            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
        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

效果如下:(可以看到刚才定义的layer里面“内部构件”)


3.就是 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]))

4.就是 train部分。

# 让神经网络通过梯度下降法来训练,这里的0.1是学习率
with tf.name_scope("train"):
    train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

5. 我们需要使用tf.summary.FileWriter()将上面的部件画出来保存到一个目录中,以方便后期在浏览器中可以浏览。这个方法中的第二个参数需要使用sess.graph,因此我们需要把这句话放在获取session的后面。这里的graph是将前面定义的框架信息收集起来,然后放在logs/目录下面。

# 定义Session,并用Session来执行init初始化步骤
sess = tf.Session()
writer = tf.summary.FileWriter("logs/",sess.graph)
sess.run(init)

好了!终于把代码部分搞定了!下面,运行你的程序。

程序完成之后,你会在你的程序目录中找到产生的logs文件夹和文件夹里放的文件。


最后,显示神经网络结构。

在你的终端中,使用命令进入到test目录,然后输入tensorboard --logdir logs,然后终端中会产生一个网址,把这个网址复制到浏览器中,便可以看到定义的神经网络框架了。


可能遇到的问题:

(1)与Tensorflow兼容的浏览器是“Google Chrome”。使用其他的浏览器不保证所有的内容都能正常显示。

(2)请确保你的Tensorboard指令是在你的logs文件根目录中执行的。如果在其他目录执行,可能不会成功看到图。

给出完整的代码:

#coding:utf-8
# 导入本次需要的模块
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt


'''
inputs:输入值
in_size:输入的大小
out_size:输出的大小
activation_function:激活函数
'''
# 构造添加一个神经层的函数
def add_layer(inputs,in_size,out_size,activation_function=None):
    with tf.name_scope("layer"):
        with tf.name_scope("weights"):
            # 定义weights为一个in_size行,out_size列的随机变量矩阵
            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
        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

#################导入数据##################################
# 构建所需要的数据。这里的x_data和y_data并不是严格的一元二次函数的关系,
# 因为我们多加了一个noise,这样看起来会更像真实情况。
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

# 利用占位符定义我们所需要的神经网络的输入。
# None代表无论输入有多少样本都可以。因为输入只有一个特征,所以这里是1。
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")
#################导入数据##################################

#################搭建神经网络##################################
# 输入层只有一个属性,所以我们就只有一个输入。
# 我设置隐藏层有10个神经元
# 输出层也只有一层
l1 = add_layer(xs,1,10,activation_function=tf.nn.relu)
prediction = add_layer(l1,10,1,activation_function=None)

# 定义损失函数
with tf.name_scope("loss"):
    loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),reduction_indices=[1]))
# 让神经网络通过梯度下降法来训练,这里的0.1是学习率
with tf.name_scope("train"):
    train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

# 使用变量时,都要对变量进行初始化
init = tf.initialize_all_variables()
# 定义Session,并用Session来执行init初始化步骤
sess = tf.Session()
writer = tf.summary.FileWriter("logs/",sess.graph)
sess.run(init)
#################搭建神经网络##################################

观看此视频笔记:https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/4-1-tensorboard1/

猜你喜欢

转载自blog.csdn.net/program_developer/article/details/80208751