从本篇文章开始,作者正式开始研究Python深度学习、神经网络及人工智能相关知识。前一篇文章讲解了TensorFlow创建回归神经网络及Optimizer优化器;本篇文章将详细讲解Tensorboard可视化的基本用法,并绘制整个神经网络及训练、学习的参数变化情况。本文主要结合作者之前的博客、"莫烦大神"的视频和AI经验介绍,后面随着深入会讲解更多的Python人工智能案例及应用。
基础性文章,希望对您有所帮助,如果文章中存在错误或不足之处,还请海涵~作者作为人工智能的菜鸟,希望大家能与我在这一笔一划的博客中成长起来,共勉。写了这么多年博客,尝试第一个付费专栏,但更多博客尤其基础性文章,还是会继续免费分享,但该专栏也会用心撰写,望对得起读者。
同时推荐前面作者另外三个Python系列文章。从2014年开始,作者主要写了三个Python系列文章,分别是基础知识、网络爬虫和数据分析。2018年陆续增加了Python图像识别和Python人工智能专栏。
前文:
[Python人工智能] 一.TensorFlow2.0环境搭建及神经网络入门
[Python人工智能] 二.TensorFlow基础及一元直线预测案例
[Python人工智能] 三.TensorFlow基础之Session、变量、传入值和激励函数
[Python人工智能] 四.TensorFlow创建回归神经网络及Optimizer优化器
一.tensorboard初识
TensorBoard是TensorFlow提供的实用工具,可以图形化的显示Graph,帮助开发者方便的理解、调试、优化TensorFlow程序。Tensorboard主要的面板如下图所示:
很多时候,我们编写了神经网络,却没有很好地进行可视化展示。本篇文章将分享如何可视化神经网络,通过TensorFlow自身提供的Tensorboard进行可视化操作,通过它能够直观地看到整个神经网络或TensorFlow的框架结构,如下图所示。
这个结构大概分成了输入层inputs、两个隐藏层layer和计算误差loss。
点击展开某一个隐藏层,可以看到权重Wights、偏差biases、计算方式Wx_plus_b和激励函数Relu等。我们可以很直观地看到TensorFlow的数据是如何流向神经网络的。
同时,inputs包括x_input和y_input两个值。
接下来,我们开始编写神经网络的可视化功能。这里,我们依旧使用上节课的代码,它通过TensorFlow实现了一个回归神经网络,通过不断学习拟合出一条接近散点的曲线。
"""
Created on Mon Dec 16 21:34:11 2019
@author: xiuzhang CSDN Eastmount
"""
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)[:,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.initialize_all_variables()
sess = tf.Session()
sess.run(init)
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.scatter(x_data, y_data)
plt.ion()
plt.show()
n = 1
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)
name = "test" + str(n) + ".png"
plt.
savefig(name)
n = n + 1
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
输出结果如下图所示,从最早不合理的图形到后面基本拟合,loss误差在不断减小,说明神经网络的真实值和预测值在不断更新接近,神经网络正常运行。
二.tensorboard绘制graph
接下来,我们用Tensorboard进行可视化训练,对上面的代码进行如下修改。
第一步,从input开始修改,调用tf.name_scope()设置输入层名称,并为传入的值xs和ys增加名字。整个inputs包括x_input和y_input。
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')
tf.name_scope()命名空间的实际作用如下:
-
在某个tf.name_scope()指定的区域中定义所有对象及各种操作,他们的“name”属性上会增加该命名区的区域名,用以区别对象属于哪个区域;
-
将不同的对象及操作放在由tf.name_scope()指定的区域中,便于在tensorboard中展示清晰的逻辑关系图,这点在复杂关系图中特别重要。
第二步,修改add_layer()函数,通过tf.name_scope()函数进行区域和变量命名。
这里通过with tf.name_scope(‘layer’)代码进行区域命名,我们把layer层当成一个框架,对应之前可视化图形的那一部分layer区域。注意,激励函数没有命名,是因为它默认会有名字,比如选择了“relu”,其名字就是“relu”。
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.matmul(inputs, Weights) + biases
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b)
return outputs
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
第三步,定义好图层名称。每加一个图层,它都会增加一个对应的框架,就是第二步命名的layer。
L1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)
prediction = add_layer(L1, 10, 1, activation_function=None)
第四步,接着通过tf.name_scope()函数定义loss和train框架。
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.summary.FileWriter('logs/', sess.graph)
init = tf.global_variables_initializer()
sess.run(init)
此时的完整代码如下所示:
"""
Created on Tue Dec 17 10:51:40 2019
@author: xiuzhang CSDN Eastmount
"""
import tensorflow as tf
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.matmul(inputs, Weights) + biases
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b)
return outputs
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')
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]))
with tf.name_scope('train'):
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
sess = tf.Session()
writer = tf.summary.FileWriter('logs/', sess.graph)
init = tf.global_variables_initializer()
sess.run(init)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
我们尝试运行代码,此时会在Python文件目录下新建一个“logs”文件夹和events的文件,如下图所示。
接下来尝试打开它。首先调出Anaconda Prompt,并激活TensorFlow,接着去到events文件的目录,调用命令“tensorboard --logdir=logs运行即可,如下图所示。注意,这里只需要指引到文件夹,它就会自动索引到你的文件。
activate tensorflow
cd\
cd C:\Users\xiuzhang\Desktop\TensorFlow
tensorboard --logdir=logs
此时访问网址“http://localhost:6006/”,选择“Graphs”,运行之后如下图所示,我们的神经网络就出现了。
双击每一个层,可以看到细节部分,比如layer层如下图所示,包括权重、偏置和计算函数。
再比如点击loss计算函数,其处理流程如下图所示。
通常我们会将train部分放置一边,选中“train”然后鼠标右键点击“Remove from main graph”。
此时的显示结果如下图所示,同时输入层inputs包括x_input和y_input。
PS:用tensorboard可视化的时候,显示“No graph definition files were found”,这很可能是路径错误,大家需要注意文件夹命名用英文、避免空格等问题。
三.tensorboard可视化神经网络学习过程
此时的神经网络只有Graph功能,接下来尝试可视化展现它的DISTRIBUTIONS、HISTOGRAMS、EVENTS等面板。
DISTRIBUTIONS是它的整个训练过程,显示了Layer1的Weights、outputs、biases的变化。
在EVENTS中,也可以把其误差loss显示出来。
接着开始讲解代码。
第一步,编写构造数据的代码。
首先导入扩展包numpy。
import numpy as np
然后构造输入、噪声和输出三个变量。
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
第二步,在add_layer()函数中增加绘图显示的名称,如下图左上角所示。
修改如下:
1.自定义一个变量layer_name,其值为add_layer()函数传进来的参数n_layer。
2.函数add_layer(inputs, in_size, out_size, n_layer, activation_function=None)增加参数n_layer,为神经层名称。
3.修改tf.name_scope(layer_name),其传递值为layer_name。
4.通过tf.summary.histogram()函数定义图形的左上角名称,包括weights、biases、outputs。部分TensorFlow的版本是调用tf.histogram_summary()函数。
修改后的代码如下:
def add_layer(inputs, in_size, out_size, n_layer, activation_function=None):
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.summary.histogram(layer_name+'/weights', Weights)
with tf.name_scope('biases'):
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='b')
tf.summary.histogram(layer_name+'/biases', biases)
with tf.name_scope('Wx_plus_b'):
Wx_plus_b = tf.matmul(inputs, Weights) + 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
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
第三步,修改定义神经网络的代码,增加参数n_layer,并设置为第1层和第2层。
L1 = add_layer(xs, 1, 10, n_layer=1, activation_function=tf.nn.relu)
prediction = add_layer(L1, 10, 1, n_layer=2, activation_function=None)
第四步,可视化loss的变化情况,它是以存量的形式在EVENTS\SCALARS中显示,调用tf.scalar_summary()函数实现。如果loss在不断减小,说明这个神经网络是学到东西的。
with tf.name_scope('loss'):
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),
reduction_indices=[1]))
tf.summary.scalar('loss', loss)
第五步,将所有的Summary合并在一起。
merged = tf.summary.merge_all()
第六步,编写神经网络学习的过程,并且每隔50步输出一次结果。
n = 1
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)
最终的完整代码如下所示:
"""
Created on Tue Dec 17 10:51:40 2019
@author: xiuzhang CSDN Eastmount
"""
import tensorflow as tf
import numpy as np
def add_layer(inputs, in_size, out_size, n_layer, activation_function=None):
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.summary.histogram(layer_name+'/weights', Weights)
with tf.name_scope('biases'):
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='b')
tf.summary.histogram(layer_name+'/biases', biases)
with tf.name_scope('Wx_plus_b'):
Wx_plus_b = tf.matmul(inputs, Weights) + 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
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
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')
L1 = add_layer(xs, 1, 10, n_layer=1, activation_function=tf.nn.relu)
prediction = add_layer(L1, 10, 1, n_layer=2, activation_function=None)
with tf.name_scope('loss'):
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),
reduction_indices=[1]))
tf.summary.scalar('loss', loss)
with tf.name_scope('train'):
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
sess = tf.Session()
merged = tf.summary.merge_all()
writer = tf.summary.FileWriter('logs/', sess.graph)
init = tf.global_variables_initializer()
sess.run(init)
n = 1
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)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
运行代码,新生成一个输出文件。
在Anaconda Prompt中输入命令“tensorboard --logdir=logs”,再调用浏览器查看新生成的图形,如下图所示。
此时的SCALARS中会显示loss的可视化图形,发现其误差在不断减小,神经网络再不断学习,拟合曲线也在不断进步。
DISTRIBUTIONS显示的Layer1如下图所示,颜色越深的地方表示它所在的这个区域值越多,每隔50步会生成一个点,包括biases、weights、outputs。
DISTRIBUTIONS显示的Layer2如下图所示
HISTOGRAMS显示如下图所示:
Histograms面板和Distributions面板是显示模型参数随迭代次数的变化情况。Distributions面板用于展示网络中各参数随训练步数增加的变化情况,如权重的分布。Histograms面板和distributions是对同一数据不同方式的展现,它是频数直方图的堆叠。
随着文章分享的深入,后续会结合案例和评估指标讲解不同神经网络的可视化对比,如Accuracy、Precision、Recall、F-measure等。
四.总结
写到这里,这篇文章就结束了,主要内容是利用Tensorboard去观察我们的神经网络。真的非常忙碌,希望这篇基础性文章对您有所帮助,如果文章中存在错误或不足之处,还请海涵~作为人工智能的菜鸟,我希望自己能不断进步并深入,后续将它应用于图像识别、网络安全、对抗样本等领域,一起加油!
PS:这是作者的第一个付费专栏,会非常用心的去撰写,希望能对得起读者的9块钱。本来只想设置1快的,但CSDN固定了价格。写了八年的免费文章,这也算知识付费的一个简单尝试吧!毕竟读博也不易,写文章也花费时间和精力,但作者更多的文章会免费分享。如果您购买了该专栏,有Python数据分析、图像处理、人工智能、网络安全的问题,我们都可以深入探讨,尤其是做研究的同学,共同进步~
(By:Eastmount 2019-12-17 晚上8点夜于珞珈山
http://blog.csdn.net/eastmount/
)
作者theano人工智能系列:
[Python人工智能] 一.神经网络入门及theano基础代码讲解
[Python人工智能] 二.theano实现回归神经网络分析
[Python人工智能] 三.theano实现分类神经网络及机器学习基础
[Python人工智能] 四.神经网络和深度学习入门知识
[Python人工智能] 五.theano实现神经网络正规化Regularization处理
[Python人工智能] 六.神经网络的评价指标、特征标准化和特征选择
[Python人工智能] 七.加速神经网络、激励函数和过拟合
参考文献:
[1] 神经网络和机器学习基础入门分享 - 作者的文章
[2] 斯坦福机器学习视频NG教授:
https://class.coursera.org/ml/class/index
[3] 书籍《游戏开发中的人工智能》、《游戏编程中的人工智能技术》
[4] 网易云莫烦老师视频(强推 我付费支持老师一波):
https://study.163.com/course/courseLearn.htm?courseId=1003209007
[5] 神经网络激励函数 - deeplearning
[6] tensorflow架构 - NoMorningstar
[7] 深度学习之 TensorFlow(二):TensorFlow 基础知识 - 希希里之海
[8] tensorflow中的“tf.name_scope()”有什么用?- 马尔代夫Maldives
[9] tensorboard使用教程 - 七七啊
[10] Tensorflow的可视化工具Tensorboard的使用——标量(scalar)的使用 - 自律者自由
[11] Tensorflow-报错解决方案 - 激进的小鸡蛋