全部代码如下:(红色部分为与笔记二不同之处)

#1.Import the neccessary libraries needed
import numpy as np
import tensorflow as tf
import matplotlib
from matplotlib import pyplot as plt ######################################################################## #2.Set default parameters for plots
matplotlib.rcParams['font.size'] = 20
matplotlib.rcParams['figure.titlesize'] = 20
matplotlib.rcParams['figure.figsize'] = [9, 7]
matplotlib.rcParams['font.family'] = ['STKaiTi']
matplotlib.rcParams['axes.unicode_minus']=False ######################################################################## #3.Initialize Parameters #Initialize learning rate
lr = 1e-2 #----------------------changed
#Initialize batch size
batchsz = 512
#Initialize loss and accurate array
losses = []
accs = [] #----------------------changed
#Initialize the weights layers and the bias layers
w1=tf.Variable(tf.random.truncated_normal([784,256],stddev=0.1))
b1=tf.Variable(tf.zeros([256]))
w2=tf.Variable(tf.random.truncated_normal([256,128],stddev=0.1))
b2=tf.Variable(tf.zeros([128]))
w3=tf.Variable(tf.random.truncated_normal([128,10],stddev=0.1))
b3=tf.Variable(tf.zeros([10])) ########################################################################
#4.Define preprocess function #----------------------changed
def preprocess(x,y):
x=tf.cast(x,dtype=tf.float32)/255.
x=tf.reshape(x,[-1,28*28])
y=tf.cast(y,dtype=tf.int32)
#one_hot接受的输入为int32,输出为float32
y=tf.one_hot(y,depth=10)
return x,y ######################################################################## #5.Import the minist dataset offline
(x_train,y_train),(x_test,y_test)=tf.keras.datasets.mnist.load_data(path=r'F:\learning\machineLearning\TensorFlow2_deeplearning\forward_progression\mnist.npz')
train_db=tf.data.Dataset.from_tensor_slices((x_train,y_train))
train_db=train_db.shuffle(10000) #-----------------------changed
train_db=train_db.batch(batchsz)
train_db=train_db.map(preprocess)
#Control the epoch times
train_db=train_db.repeat(20) test_db=tf.data.Dataset.from_tensor_slices((x_test,y_test))
test_db=test_db.shuffle(1000).batch(batchsz).map(preprocess) ######################################################################## #The main function
def main():
for step,(x,y) in enumerate(train_db):#Or for x,y in train_db:
with tf.GradientTape() as tape: # tf.Variable
# layer1
h1 = x@w1 + b1
h1 = tf.nn.relu(h1)
# layer2
h2 = h1@w2 + b2
h2 = tf.nn.relu(h2)
# output
out = h2@w3 + b3
# compute loss
loss = tf.square(y-out)
# mean: scalar
loss = tf.reduce_mean(loss)
# compute gradients
grads = tape.gradient(loss, [w1, b1, w2, b2, w3, b3])
#Update the weights and the bias #-----------------------changed
for p, g in zip([w1, b1, w2, b2, w3, b3], grads):
p.assign_sub(lr * g) if step % 80 == 0:
print(step, 'loss:', float(loss))
losses.append(float(loss)) if step % 80 == 0: #-----------------------changed
total, total_correct = 0., 0
for x,y in test_db:
# layer1
h1 = x@w1 + b1
h1 = tf.nn.relu(h1)
# layer2
h2 = h1@w2 + b2
h2 = tf.nn.relu(h2)
# output
out = h2@w3 + b3
pred=tf.argmax(out,axis=1)
y=tf.argmax(y,axis=1)
correct=tf.equal(pred,y)
total_correct+=tf.reduce_sum(tf.cast(correct,dtype=tf.int32)).numpy()
total+=x.shape[0]
print(step,'Evaluate ACC:',total_correct/total)
accs.append(total_correct/total)
plt.figure()
x = [i*80 for i in range(len(losses))]
plt.plot(x, losses, color='C0', marker='s', label='训练')
plt.ylabel('MSE')
plt.xlabel('Step')
plt.legend() plt.figure()
plt.plot(x, accs, color='C1', marker='s', label='测试')
plt.ylabel('准确率')
plt.xlabel('Step')
plt.legend() plt.show()
if __name__ == '__main__':
main()

其中learning rate在此处改为了1e-2,经测试若为1e-3则accurate rate会增长较慢,在20epoch下最终会达到30~40%,而1e-2则会接近80%

并且通过.map(preprocess)方法预处理了train_db,包括将图片数据标准化到(0-1),reshape到[-1,28*28],将标签数据做one-hot处理,深度为10;通过train_db=train_db.repeat(20)代替了for epoch in range(20);用

for p, g in zip([w1, b1, w2, b2, w3, b3], grads):
  p.assign_sub(lr * g)
代替了
w1.assign_sub(lr * grads[0])
b1.assign_sub(lr * grads[1])
w2.assign_sub(lr * grads[2])
b2.assign_sub(lr * grads[3])
w3.assign_sub(lr * grads[4])
b3.assign_sub(lr * grads[5])

《TensorFlow2深度学习》学习笔记(四)对笔记二中的模型增加正确率展示的更多相关文章

  1. ThinkPHP 学习笔记 ( 四 ) 数据库操作之关联模型 ( RelationMondel ) 和高级模型 ( AdvModel )

    一.关联模型 ( RelationMondel ) 1.数据查询 ① HAS_ONE 查询 创建两张数据表评论表和文章表: tpk_comment , tpk_article .评论和文章的对应关系为 ...

  2. 深度学习课程笔记(十四)深度强化学习 --- Proximal Policy Optimization (PPO)

    深度学习课程笔记(十四)深度强化学习 ---  Proximal Policy Optimization (PPO) 2018-07-17 16:54:51  Reference: https://b ...

  3. 官网实例详解-目录和实例简介-keras学习笔记四

    官网实例详解-目录和实例简介-keras学习笔记四 2018-06-11 10:36:18 wyx100 阅读数 4193更多 分类专栏: 人工智能 python 深度学习 keras   版权声明: ...

  4. C#可扩展编程之MEF学习笔记(四):见证奇迹的时刻

    前面三篇讲了MEF的基础和基本到导入导出方法,下面就是见证MEF真正魅力所在的时刻.如果没有看过前面的文章,请到我的博客首页查看. 前面我们都是在一个项目中写了一个类来测试的,但实际开发中,我们往往要 ...

  5. iOS阶段学习第四天笔记(循环)

    iOS学习(C语言)知识点整理笔记 一.分支结构 1.分支结构分为单分支 即:if( ){ } ;多分支 即:if( ){ }else{ }  两种 2.单分支 if表达式成立则执行{ }里的语句:双 ...

  6. IOS学习笔记(四)之UITextField和UITextView控件学习

    IOS学习笔记(四)之UITextField和UITextView控件学习(博客地址:http://blog.csdn.net/developer_jiangqq) Author:hmjiangqq ...

  7. java之jvm学习笔记四(安全管理器)

    java之jvm学习笔记四(安全管理器) 前面已经简述了java的安全模型的两个组成部分(类装载器,class文件校验器),接下来学习的是java安全模型的另外一个重要组成部分安全管理器. 安全管理器 ...

  8. Java学习笔记四---打包成双击可运行的jar文件

    写笔记四前的脑回路是这样的: 前面的学习笔记二,提到3个环境变量,其中java_home好理解,就是jdk安装路径:classpath指向类文件的搜索路径:path指向可执行程序的搜索路径.这里的类文 ...

  9. Learning ROS for Robotics Programming Second Edition学习笔记(四) indigo devices

    中文译著已经出版,详情请参考:http://blog.csdn.net/ZhangRelay/article/category/6506865 Learning ROS for Robotics Pr ...

随机推荐

  1. SonarQube + Jenkins代码审查环境安装文档 v1.2

    1. 安装SonarQube 1.1. 下载 下载地址:https://www.sonarqube.org/downloads/ 本次使用安装包为:sonarqube-7.4.zip 需要提前准备jd ...

  2. Dockerfile常用指令说明

    具体解释:https://blog.csdn.net/achenyuan/article/details/80231922 将dockerfile文件和生成好的jar 使用ftp工具上传到linux服 ...

  3. Docker 两键创建 ZeroTier moon 节点

    一条命令创建 ZeroTier moon 节点: $ docker run --name zerotier-moon -d -p 9993:9993 -p 9993:9993/udp seedgou/ ...

  4. linux 程序失败自动重启

    最近写了一个spark streaming 程序,但是程序跑着跑着就报错了,而且不会自动重启,以下脚本实现了程序失败自动重启 基本原理:查看程序日志文件是否有ERROR或Exception字样,有说明 ...

  5. remote origin already exists解决办法

    如图翻译过来就是:致命:远程来源已经存在 此时,我们可以先 git remote -v 查看远程库信息: 可以看到,本地库已经关联了origin的远程库,并且,该远程库指向GitHub. 解决办法如下 ...

  6. sql调优方法实用性总结(一)

    1.选择最有效率的表名顺序(只在基于规则的优化器): Oracle的解析器按照从右向左的顺序处理FROM子句中的表名,FROM子句中写在最后的表将被最先处理(基础表先处理,driving table) ...

  7. kafka的分区

    分区会均匀的分配到不同的broke上,即不同的机器上.

  8. 浅谈PHP中pack、unpack的详细用法

    转自:https://segmentfault.com/a/1190000008305573 PHP中有两个函数pack和unpack,很多PHPer在实际项目中从来没有使用过,甚至也不知道这两个方法 ...

  9. Visual Studio Code (vscode) 配置 C / C++ 环境

    Visual Studio Code (vscode) 配置 C / C++ 环境 昨天突发奇想,想使用vscode配置C++环境,因为不想下载 Dev OR codeblock,然后借助了很多网上教 ...

  10. LeetCode 1253. 重构 2 行二进制矩阵 - Java - 统计

    题目链接:https://leetcode-cn.com/contest/weekly-contest-162/problems/reconstruct-a-2-row-binary-matrix/ ...