Python人工智能 | 六.Tensorboard可视化基本用法及神经网络绘制
文章目录:
一.tensorboard初识
二.tensorboard绘制graph
三.tensorboard可视化神经网络学习过程
四.总结
https://github.com/eastmountyxz/
AI-for-TensorFlowhttps://github.com/eastmountyxz/
AI-for-Keras
学Python近八年,认识了很多大佬和朋友,感恩。由于在外求学且需要养娃,故在CSDN设置成了最低价收费专栏,觉得不错的可以购买抬爱;但作者的本意是帮助更多初学者入门,因此在github开源了所有代码,也在公众号同步更新。深知自己很菜,得拼命努力前行,编程也没有什么捷径,干就对了。希望未来能更透彻学习和撰写文章,也能在读博几年里学会真正的独立科研。同时非常感谢参考文献中的大佬们的文章和分享。
- https://blog.csdn.net/eastmount
一.tensorboard初识
# -*- coding: utf-8 -*-
"""
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
#---------------------------------定义神经层---------------------------------
# 函数:输入变量 输入大小 输出大小 激励函数默认None
def add_layer(inputs, in_size, out_size, activation_function=None):
# 权重为随机变量矩阵
Weights = tf.Variable(tf.random_normal([in_size, out_size])) #行*列
# 定义偏置 初始值增加0.1 每次训练中有变化
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1) #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) #平均值0 方差0.05
# 输出
y_data =np.square(x_data) -0.5 + noise
# 设置传入的值xs和ys
xs = tf.placeholder(tf.float32, [None, 1]) #x_data传入给xs
ys = tf.placeholder(tf.float32,[None, 1]) #y_data传入给ys
#---------------------------------定义神经网络---------------------------------
# 隐藏层
L1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu) #激励函数
# 输出层
prediction = add_layer(L1, 10, 1, activation_function=None)
#------------------------------定义loss和初始化-------------------------------
# 预测值与真实值误差 平均值->求和->平方(真实值-预测值)
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),
reduction_indices=[1]))
# 训练学习 学习效率通常小于1 这里设置为0.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()
#---------------------------------神经网络学习---------------------------------
# 学习1000次
n = 1
for i in range(1000):
# 训练
sess.run(train_step, feed_dict={xs:x_data, ys:y_data}) #假设用全部数据x_data进行运算
# 输出结果 只要通过place_holder运行就要传入参数
if i % 50==0:
#print(sess.run(loss, feed_dict={xs:x_data, ys:y_data}))
try:
# 忽略第一次错误 后续移除lines的第一个线段
ax.lines.remove(lines[0])
except Exception:
pass
# 预测
prediction_value = sess.run(prediction, feed_dict={xs:x_data})
# 设置线宽度为5 红色
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
二.tensorboard绘制graph
在某个tf.name_scope()指定的区域中定义所有对象及各种操作,他们的“name”属性上会增加该命名区的区域名,用以区别对象属于哪个区域;
将不同的对象及操作放在由tf.name_scope()指定的区域中,便于在tensorboard中展示清晰的逻辑关系图,这点在复杂关系图中特别重要。
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 17 10:51:40 2019
@author: xiuzhang CSDN Eastmount
"""
import tensorflow as tf
#---------------------------------定义神经层---------------------------------
# 函数:输入变量 输入大小 输出大小 激励函数默认None
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'):
# 定义偏置 初始值增加0.1 每次训练中有变化
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='b') #1行多列
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
#-----------------------------设置传入的值xs和ys-------------------------------
# 输入inputs包括x_input和y_input
with tf.name_scope('inputs'):
xs = tf.placeholder(tf.float32, [None, 1], name='x_input') #x_data传入给xs
ys = tf.placeholder(tf.float32,[None, 1], name='y_input') #y_data传入给ys
#---------------------------------定义神经网络---------------------------------
# 隐藏层
L1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu) #激励函数
# 输出层
prediction = add_layer(L1, 10, 1, activation_function=None)
#------------------------------定义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'):
# 训练学习 学习效率通常小于1 这里设置为0.1可以进行对比
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss) #减小误差
#------------------------------初始化和文件写操作-------------------------------
# 定义Session
sess = tf.Session()
# 整个框架加载到文件中,才能从文件中加载出来至浏览器中查看
writer = tf.summary.FileWriter('logs/', sess.graph)
# 初始化
init = tf.global_variables_initializer()
sess.run(init)
activate tensorflow
cd\
cd C:\Users\xiuzhang\Desktop\TensorFlow
tensorboard --logdir=logs
三.tensorboard可视化
import numpy as np
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()函数。
# 合并所有summary
merged = tf.summary.merge_all()
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 17 10:51:40 2019
@author: xiuzhang CSDN Eastmount
"""
import tensorflow as tf
import numpy as np
#---------------------------------定义神经层---------------------------------
# 函数:输入变量 输入大小 输出大小 神经层名称 激励函数默认None
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'):
# 定义偏置 初始值增加0.1 每次训练中有变化
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='b') #1行多列
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) #平均值0 方差0.05
# 输出
y_data =np.square(x_data) -0.5 + noise
#-----------------------------设置传入的值xs和ys-------------------------------
# 输入inputs包括x_input和y_input
with tf.name_scope('inputs'):
xs = tf.placeholder(tf.float32, [None, 1], name='x_input') #x_data传入给xs
ys = tf.placeholder(tf.float32,[None, 1], name='y_input') #y_data传入给ys
#---------------------------------定义神经网络---------------------------------
# 隐藏层
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和train-------------------------------
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'):
# 训练学习 学习效率通常小于1 这里设置为0.1可以进行对比
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss) #减小误差
#------------------------------初始化和文件写操作-------------------------------
# 定义Session
sess = tf.Session()
# 合并所有summary
merged = tf.summary.merge_all()
# 整个框架加载到文件中,才能从文件中加载出来至浏览器中查看
writer = tf.summary.FileWriter('logs/', sess.graph)
# 初始化
init = tf.global_variables_initializer()
sess.run(init)
#---------------------------------神经网络学习---------------------------------
# 学习1000次
n = 1
for i in range(1000):
# 训练 xs和ys是定义的变量 x_data和y_data是构造的数据
sess.run(train_step, feed_dict={xs:x_data, ys:y_data})
# 每隔50步输出结果
if i % 50==0:
result = sess.run(merged, feed_dict={xs:x_data, ys:y_data})
writer.add_summary(result, i) # 每隔i步输出一个点
四.总结
天行健,君子以自强不息。
地势坤,君子以厚德载物。
[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] 《TensorFlow2.0》低阶 api 入门 - GumKey
[8] TensorFlow之基础知识 - kk123k
[9] tensorboard使用教程 - 七七啊
[10] Tensorflow的可视化工具Tensorboard的使用——标量(scalar)的使用 - 自律者自由