集团站切换校区

验证码已发送,请查收短信

复制成功
微信号:togogoi
添加微信好友, 详细了解课程
已复制成功,如果自动跳转微信失败,请前往微信添加好友
打开微信
图标

学习文章

当前位置:首页 > >学习文章 > >

{HCNA-AI TensorFlow编程基础}之TensorBoard 可视化

发布时间: 2018-11-22 23:21:17

5.1 实验介绍

5.1.1 关于本实验

本实验主要是展示 TensorBoard 的可视化效果。

5.1.2 实验目的

了解 TensorBoard 可视化工具。

5.1.3 实验介绍

TensorFlow 提供了一个可视化工具 TensorBoard。他可以将训练过程的各种回执数据展示出

来,包括标量,图片,音频,计算图,数据分布,直方图和嵌入式向量。通过网页来观察模型的结构和训练过程中各个参数的变化。TensorBoard 是日志展示系统,需要在 session  中运算图时,将各种类型的数据汇总并输出到日志文件中。然后启动 TensorBoard 服务,TensorBoard 读取这些日志文件,并开启 6060 端口提供 Web 服务,让用户可以在浏览器中查看数据。

5.1.4 实验步骤

步骤 1  登陆华为云。

步骤 2 点击右上方的控制台。

步骤 3 选择弹性云服务器,网页中会显示该弹性云的可进行的操作,选择远程登录。即登录到弹性云服务器。

步骤 4 输入指令 ll,查看当前目录下的文件。

步骤 5 输入命令:vi tensorboard.py,创建新的 Python 脚本。

步骤 6 输入命令 i,进入编辑模式开始编辑,输入脚本内容。

步骤 7 输入命令 :wq!,保存并退出。

步骤 8 输入命令 cat tensorboard.py 查看代码。

步骤 9 运行测试。

输入命令:python3 tensorboard.py。




5.2 实验过程

5.2.1 设置编码说明

# -*- coding: utf-8 -*-

5.2.2 导入模块

import tensorflow as tf import numpy as np

import matplotlib.pyplot as plt


plotdata = { "batchsize":[], "loss":[] } def moving_average(a, w=10):

if len(a) < w: return a[:]

return [val if idx < w else sum(a[(idx-w):idx])/w for idx, val in enumerate(a)]


5.2.3 生成模拟数据

#生成模拟数据

train_X = np.linspace(-1, 1, 100)

train_Y = 2*train_X + np.random.randn(*train_X.shape)*0.3 # y=2x,但是加入了噪声

5.2.4 重置计算图

#图形显示

# plt.plot(train_X, train_Y, 'ro', label='Original data') # plt.legend()

plt.show()


tf.reset_default_graph()

5.2.5 创建模型

# 创建模型

# 占位符

X = tf.placeholder("float") Y = tf.placeholder("float")

# 模型参数

W = tf.Variable(tf.random_normal([1]), name="weight") b = tf.Variable(tf.zeros([1]), name="bias")

5.2.6 构建前向结构

# 前向结构

z = tf.multiply(X, W)+ b

tf.summary.histogram('z',z)#将预测值以直方图显示




5.2.7 反向优化

#反向优化

cost =tf.reduce_mean( tf.square(Y - z)) tf.summary.scalar('loss_function', cost) #将损失以标量显示

learning_rate = 0.01 #Gradient descent

optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

5.2.8 初始化变量

# 初始化变量

init = tf.global_variables_initializer()


#参数设置training_epochs = 20

display_step = 2

5.2.9 启动会话

# 启 动 session

with tf.Session() as sess:

sess.run(init)

#合并所有 summary

merged_summary_op = tf.summary.merge_all()

#创建 summary_writer,用于写文件

summary_writer = tf.summary.FileWriter('log/mnist_with_summaries',sess.graph)

5.2.10 向模型中写入数据

#向模型中输入数据

for epoch in range(training_epochs): for (x, y) in zip(train_X, train_Y):

sess.run(optimizer, feed_dict={X: x, Y: y})


#生成 summary

summary_str = sess.run(merged_summary_op,feed_dict={X: x, Y: y}); summary_writer.add_summary(summary_str, epoch);#将 summary 写入文件

#显示训练中的详细信息

if epoch % display_step == 0:

loss = sess.run(cost, feed_dict={X: train_X, Y:train_Y})

print ("Epoch:", epoch+1, "cost=", loss,"W=", sess.run(W), "b=", sess.run(b))

if not (loss == "NA" ): plotdata["batchsize"].append(epoch) plotdata["loss"].append(loss)


print (" Finished!")




print ("cost=", sess.run(cost, feed_dict={X: train_X, Y: train_Y}), "W=", sess.run(W), "b=", sess.run(b))

print ("cost:",cost.eval({X: train_X, Y: train_Y}))

5.2.11 图形化展示

结果可视化:

plt.plot(train_X, train_Y, 'ro', label='Original data')

plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line') plt.legend()

plt.show()


plotdata["avgloss"] = moving_average(plotdata["loss"]) plt.figure(1)

plt.subplot(211)

plt.plot(plotdata["batchsize"], plotdata["avgloss"], 'b--') plt.xlabel('Minibatch number')

plt.ylabel('Loss')

plt.title('Minibatch run vs. Training loss')


plt.show()


模型结果测试:

print("x=0.2,z=", sess.run(z, feed_dict={X: 0.2}))

5.2.12 实验结果Epoch:1cost=0.26367584W=[1.4959534] b= [0.1584389]Epoch:3cost=0.11837075W=[1.927753] b= [0.04088809]Epoch:5cost=0.10505076W=[2.04464] b= [-0.00315647]Epoch:7cost=0.10374546W=[2.074953] b= [-0.01477524]Epoch:9cost=0.10355354W=[2.0827925] b= [-0.01778343]Epoch:11cost=0.10351367W=[2.0848196] b= [-0.01856134]Epoch:13cost=0.10350403W=[2.0853424] b= [-0.01876191]Epoch:15cost=0.10350155W=[2.0854788] b= [-0.01881423]Epoch:17cost=0.10350095W=[2.0855126] b= [-0.01882721]Epoch:19cost=0.10350082W=[2.0855196] b= [-0.01882991]Finished!

cost= 0.1035008 W= [2.085521] b= [-0.01883046]

5.1 实验介绍

5.1.1 关于本实验

本实验主要是展示 TensorBoard 的可视化效果。

5.1.2 实验目的

了解 TensorBoard 可视化工具。

5.1.3 实验介绍

TensorFlow 提供了一个可视化工具 TensorBoard。他可以将训练过程的各种回执数据展示出

来,包括标量,图片,音频,计算图,数据分布,直方图和嵌入式向量。通过网页来观察模型的结构和训练过程中各个参数的变化。TensorBoard 是日志展示系统,需要在 session  中运算图时,将各种类型的数据汇总并输出到日志文件中。然后启动 TensorBoard 服务,TensorBoard 读取这些日志文件,并开启 6060 端口提供 Web 服务,让用户可以在浏览器中查看数据。

5.1.4 实验步骤

步骤 1  登陆华为云。

步骤 2 点击右上方的控制台。

步骤 3 选择弹性云服务器,网页中会显示该弹性云的可进行的操作,选择远程登录。即登录到弹性云服务器。

步骤 4 输入指令 ll,查看当前目录下的文件。

步骤 5 输入命令:vi tensorboard.py,创建新的 Python 脚本。

步骤 6 输入命令 i,进入编辑模式开始编辑,输入脚本内容。

步骤 7 输入命令 :wq!,保存并退出。

步骤 8 输入命令 cat tensorboard.py 查看代码。

步骤 9 运行测试。

输入命令:python3 tensorboard.py。




5.2 实验过程

5.2.1 设置编码说明

# -*- coding: utf-8 -*-

5.2.2 导入模块

import tensorflow as tf import numpy as np

import matplotlib.pyplot as plt


plotdata = { "batchsize":[], "loss":[] } def moving_average(a, w=10):

if len(a) < w: return a[:]

return [val if idx < w else sum(a[(idx-w):idx])/w for idx, val in enumerate(a)]


5.2.3 生成模拟数据

#生成模拟数据

train_X = np.linspace(-1, 1, 100)

train_Y = 2*train_X + np.random.randn(*train_X.shape)*0.3 # y=2x,但是加入了噪声

5.2.4 重置计算图

#图形显示

# plt.plot(train_X, train_Y, 'ro', label='Original data') # plt.legend()

plt.show()


tf.reset_default_graph()

5.2.5 创建模型

# 创建模型

# 占位符

X = tf.placeholder("float") Y = tf.placeholder("float")

# 模型参数

W = tf.Variable(tf.random_normal([1]), name="weight") b = tf.Variable(tf.zeros([1]), name="bias")

5.2.6 构建前向结构

# 前向结构

z = tf.multiply(X, W)+ b

tf.summary.histogram('z',z)#将预测值以直方图显示




5.2.7 反向优化

#反向优化

cost =tf.reduce_mean( tf.square(Y - z)) tf.summary.scalar('loss_function', cost) #将损失以标量显示

learning_rate = 0.01 #Gradient descent

optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

5.2.8 初始化变量

# 初始化变量

init = tf.global_variables_initializer()


#参数设置training_epochs = 20

display_step = 2

5.2.9 启动会话

# 启 动 session

with tf.Session() as sess:

sess.run(init)

#合并所有 summary

merged_summary_op = tf.summary.merge_all()

#创建 summary_writer,用于写文件

summary_writer = tf.summary.FileWriter('log/mnist_with_summaries',sess.graph)

5.2.10 向模型中写入数据

#向模型中输入数据

for epoch in range(training_epochs): for (x, y) in zip(train_X, train_Y):

sess.run(optimizer, feed_dict={X: x, Y: y})


#生成 summary

summary_str = sess.run(merged_summary_op,feed_dict={X: x, Y: y}); summary_writer.add_summary(summary_str, epoch);#将 summary 写入文件

#显示训练中的详细信息

if epoch % display_step == 0:

loss = sess.run(cost, feed_dict={X: train_X, Y:train_Y})

print ("Epoch:", epoch+1, "cost=", loss,"W=", sess.run(W), "b=", sess.run(b))

if not (loss == "NA" ): plotdata["batchsize"].append(epoch) plotdata["loss"].append(loss)


print (" Finished!")




print ("cost=", sess.run(cost, feed_dict={X: train_X, Y: train_Y}), "W=", sess.run(W), "b=", sess.run(b))

print ("cost:",cost.eval({X: train_X, Y: train_Y}))

5.2.11 图形化展示

结果可视化:

plt.plot(train_X, train_Y, 'ro', label='Original data')

plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line') plt.legend()

plt.show()


plotdata["avgloss"] = moving_average(plotdata["loss"]) plt.figure(1)

plt.subplot(211)

plt.plot(plotdata["batchsize"], plotdata["avgloss"], 'b--') plt.xlabel('Minibatch number')

plt.ylabel('Loss')

plt.title('Minibatch run vs. Training loss')


plt.show()


模型结果测试:

print("x=0.2,z=", sess.run(z, feed_dict={X: 0.2}))

5.2.12 实验结果Epoch:1cost=0.26367584W=[1.4959534] b= [0.1584389]Epoch:3cost=0.11837075W=[1.927753] b= [0.04088809]Epoch:5cost=0.10505076W=[2.04464] b= [-0.00315647]Epoch:7cost=0.10374546W=[2.074953] b= [-0.01477524]Epoch:9cost=0.10355354W=[2.0827925] b= [-0.01778343]Epoch:11cost=0.10351367W=[2.0848196] b= [-0.01856134]Epoch:13cost=0.10350403W=[2.0853424] b= [-0.01876191]Epoch:15cost=0.10350155W=[2.0854788] b= [-0.01881423]Epoch:17cost=0.10350095W=[2.0855126] b= [-0.01882721]Epoch:19cost=0.10350082W=[2.0855196] b= [-0.01882991]Finished!

cost= 0.1035008 W= [2.085521] b= [-0.01883046]


上一篇: {Springboot}介绍

下一篇: {Docker}发布Docker应用到阿里云

十五年老品牌
微信咨询:togogoi 咨询电话:18922156670 咨询网站客服:在线客服

相关课程推荐

在线咨询 ×

您好,请问有什么可以帮您?我们将竭诚提供最优质服务!