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

#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. 工控随笔_24_关于西门子Step7的Simatic manager打开报3280:503错误。

    微软推出Win10系统后,很多工控软件也被迫跟着升级,但是因为Win10系统的不稳定性,导致很多时候,安装的软件莫名其妙的 不能用. 相对Win7和WinXP来说,Win10在兼容性和稳定性都差很多. ...

  2. windows下ffmpeg批量转码

    以mp4转mp3为例 for %%i in (*.mp4) do ffmpeg -i "%%i" "%%i.mp3" 将当前文件夹下的mp4文件全部转码为mp3

  3. Web API之Web Components

    本文参考<你的前端框架要被web组件替代了>. 于2011年面世的Web Components是一套功能组件,让开发者可以使用 HTML.CSS 和 JavaScript 创建可复用的组件 ...

  4. Windows删除文件夹下的指定格式文件(递归删除)

    问题描述: 今天遇到一个需求,需要对文件夹进行文件筛选.目录结构较为复杂(目录较多,层次较深),数据量较大(总共60GB左右). 鉴于上述情况,直接排除了人工处理方式(否则小伙伴们会打死我的). 解决 ...

  5. MacbookPro15 2019 闪屏雪花现象方案汇总

    1. 系统偏好设置,显示器,关闭 "自动调节亮度" "原彩显示",即取消勾选. 2. 系统偏好设置,节能,关闭 "自动切换图形卡模式",即取 ...

  6. springboot2 设置系统访问的默认首页

    @Configuration public class WebMvcConfig implements WebMvcConfigurer{ @Override public void addViewC ...

  7. linux查看openssh和openssl版本

    查看 openssh 版本命令 ssh -V 查看 openssl 版本命令 openssl version

  8. Java学习之旅(二):生病的狗2(java例化)

    废话不多说,直接上肝货,可运行. 代码简陋,逻辑关系可能还不是很严谨,欢迎交流. public class Owner { //属性部分 //狗主人肯定有一条狗,这条狗可以被别的主人检查,所以设置为p ...

  9. Word 插入脚注、尾注与题注 -- 视频教程(5)

    >> 视频教程链接:B站,速度快,清晰 未完 ...... 点击访问原文(进入后根据右侧标签,快速定位到本文)

  10. 【Python爬虫案例学习】分析Ajax请求并抓取今日头条街拍图片

    1.抓取索引页内容 利用requests请求目标站点,得到索引网页HTML代码,返回结果. from urllib.parse import urlencode from requests.excep ...