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

#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. openssl 和libcurl的安装

    /usr/lib/aarch64-linux-gnu/qt5/bin/qmake CONFIG+=release 1 SET(CMAKE_PREFIX_PATH /home/qilin64/Qt5.6 ...

  2. [转]10 Best GTK Themes for Ubuntu 18.04

    原文地址:https://omgfoss.com/10-best-gtk-themes-ubuntu-18-04/

  3. java 快速定位线上cpu偏高

    1.top -c 加 大写P 查找高进程ID 2.top -Hp 加 大写 P 查找高线程ID 3.printf '%x\n' 线程ID 转成16进制 4.jstack 进程ID | grep 16进 ...

  4. 【Docker学习之五】Docker自定义镜像示例

    环境 docker-ce-19.03.1-3.el7.x86_64 centos 7 一.创建centos+jdk+tomcat镜像 对于公用的容器比如,tomcat.nginx.mysql等应用组件 ...

  5. spring boot 2X中@Scheduled实现定时任务及多线程配置

    使用@Scheduled 可以很容易实现定时任务 spring boot的版本 2.1.6.RELEASE package com.abc.demo.common; import org.slf4j. ...

  6. .NetCore中EFCore的使用整理(三)-关联表操作

    一.查询关联表数据 StudyAboard_TestContext _context = new StudyAboard_TestContext(); CrmRole role = _context. ...

  7. 视频质量诊断----PTZ云台运动检测

    一.PTZ云台运动检测是通过配合云台运动的功能检测云台运动是否正常. 二.原理 取云台运动前N帧图像,进行背景建模,得到运动前背景A. 设备发送云台运动指令,让云台进行运动,改变场景. 取云台运动后N ...

  8. rfc 5280 X.509 PKI 解析

    本文以博客园的证书为例讲解,不包含对CRL部分的翻译,如没有对第5章节以及6.3小节进行翻译 3.2. Certification Paths and Trust 下面简单介绍了Public-Key ...

  9. jquery下拉单选框可左右移动数据

    <!doctype html> <html> <head> <meta charset="utf-8"> <title> ...

  10. Django框架之第五篇(模板层) --变量、过滤器、标签、自定义标签、过滤器,模板的继承、模板的注入、静态文件

    模板层 模板层就是html页面,Django系统中的(template) 一.视图层给模板传值的两种方法 方式一:通过键值对的形式传参,指名道姓的传参 n = 'xxx'f = 'yyy'return ...