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

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

一、动态显示结果图

# 导入本次需要的模块

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt   
def add_layer(inputs,in_size,out_size,activation_function=None):
    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

x_data = np.linspace(-1,1,300,dtype=np.float32)[:,np.newaxis]

noise = np.random.normal(0,0.05,x_data.shape)
y_data = np.square(x_data) - 0.5 + noise

xs = tf.placeholder(tf.float32,[None,1])
ys = tf.placeholder(tf.float32,[None,1])

l1 = add_layer(xs,1,10,activation_function=tf.nn.relu)
prediction = add_layer(l1,10,1,activation_function=None)

loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

############################## 画取真实曲线 #############################
# 构建图形,用散点图描述真实数据之间的关系
fig = plt.figure() # 创建图形实例
ax = fig.add_subplot(1,1,1) # 增加一个子图
# 绘制散点图
ax.scatter(x_data,y_data,marker='*',c='g')
plt.ion() # 点连续显示,show 之后不暂停
plt.show()
############################## 画取真实曲线 #############################
for i in range(1000):
    sess.run(train_step,feed_dict={xs:x_data,ys:y_data})
############################## 画预测曲线 #############################
    if i%50 ==0:
        # 为了显示出来动态效果需要先抹除画出来的每一条线,然后再画
        try:
            ax.lines.remove(lines[0])
        except Exception:
            pass
        prediction_value = sess.run(prediction,feed_dict={xs:x_data})
        lines = ax.plot(x_data,prediction_value,'r-',lw=5)
        plt.pause(0.1)
############################## 画预测曲线 #############################

注意,这里如果使用 Pycharm 无法显示出效果需要执行以下步骤
在这里插入图片描述

二、可视化所构建的神经网络

效果图
在这里插入图片描述
同时,我们也可以展开看看每层layer中的一些具体结构:
在这里插入图片描述
其次,介绍神经网络可视化的具体步骤和代码:

  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")
  1. 接下来开始编辑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  

编辑后:

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里面“内部构件”)
在这里插入图片描述

  1. 就是 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]))
  1. 就是 train 部分
# 让神经网络通过梯度下降法来训练,这里的0.1是学习率
with tf.name_scope("train"):
    train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
  1. 我们需要使用tf.summary.FileWriter()将上面的部件画出来保存到一个目录中,以方便后期在浏览器中可以浏览。这个方法中的第二个参数需要使用sess.graph,因此我们需要把这句话放在获取session的后面。这里的graph是将前面定义的框架信息收集起来,然后放在logs/目录下面
# 定义Session,并用Session来执行init初始化步骤
sess = tf.Session()
writer = tf.summary.FileWriter("logs/",sess.graph)
sess.run(init)

在这里插入图片描述

完整的代码

#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)
#################搭建神经网络##################################
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南淮北安

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值