吴裕雄--天生自然TensorFlow2教程:手写数字问题实战
import tensorflow as tf
from tensorflow import keras
from keras import Sequential,datasets, layers, optimizers, metrics def preprocess(x, y):
"""数据处理函数"""
x = tf.cast(x, dtype=tf.float32) / 255.
y = tf.cast(y, dtype=tf.int32)
return x, y # 加载数据
(x, y), (x_test, y_test) = datasets.fashion_mnist.load_data()
print(x.shape, y.shape) # 处理train数据
batch_size = 128
db = tf.data.Dataset.from_tensor_slices((x, y))
db = db.map(preprocess).shuffle(10000).batch(batch_size) # 处理test数据
db_test = tf.data.Dataset.from_tensor_slices((x_test, y_test))
db_test = db_test.map(preprocess).batch(batch_size) # # 生成train数据的迭代器
db_iter = iter(db)
sample = next(db_iter)
print(f'batch: {sample[0].shape,sample[1].shape}') # 设计网络结构
model = Sequential([
layers.Dense(256, activation=tf.nn.relu), # [b,784] --> [b,256]
layers.Dense(128, activation=tf.nn.relu), # [b,256] --> [b,128]
layers.Dense(64, activation=tf.nn.relu), # [b,128] --> [b,64]
layers.Dense(32, activation=tf.nn.relu), # [b,64] --> [b,32]
layers.Dense(10) # [b,32] --> [b,10], 330=32*10+10
]) model.build(input_shape=[None, 28 * 28])
model.summary() # 调试
# w = w - lr*grad
optimizer = optimizers.Adam(lr=1e-3) # 优化器,加快训练速度 def main():
"""主运行函数"""
for epoch in range(10):
for step, (x, y) in enumerate(db):
# x:[b,28,28] --> [b,784]
# y:[b]
x = tf.reshape(x, [-1, 28 * 28])
with tf.GradientTape() as tape:
# [b,784] --> [b,10]
logits = model(x)
y_onehot = tf.one_hot(y, depth=10)
# [b]
loss_mse = tf.reduce_mean(tf.losses.MSE(y_onehot, logits))
loss_ce = tf.reduce_mean(tf.losses.categorical_crossentropy(y_onehot,logits,from_logits=True))
grads = tape.gradient(loss_ce, model.trainable_variables)
optimizer.apply_gradients(zip(grads, model.trainable_variables))
if step % 100 == 0:
print(epoch, step, f'loss: {float(loss_ce),float(loss_mse)}') # test
total_correct = 0
total_num = 0
for x, y in db_test:
# x:[b,28,28] --> [b,784]
# y:[b]
x = tf.reshape(x, [-1, 28 * 28])
# [b,10]
logits = model(x)
# logits --> prob [b,10]
prob = tf.nn.softmax(logits, axis=1)
# [b,10] --> [b], int32
pred = tf.argmax(prob, axis=1)
pred = tf.cast(pred, dtype=tf.int32)
# pred:[b]
# y:[b]
# correct: [b], True: equal; False: not equal
correct = tf.equal(pred, y)
correct = tf.reduce_sum(tf.cast(correct, dtype=tf.int32))
total_correct += int(correct)
total_num += x.shape[0]
acc = total_correct / total_num
print(epoch, f'test acc: {acc}') if __name__ == '__main__':
main()
吴裕雄--天生自然TensorFlow2教程:手写数字问题实战的更多相关文章
- 吴裕雄--天生自然TensorFlow2教程:前向传播(张量)- 实战
手写数字识别流程 MNIST手写数字集7000*10张图片 60k张图片训练,10k张图片测试 每张图片是28*28,如果是彩色图片是28*28*3-255表示图片的灰度值,0表示纯白,255表示纯黑 ...
- 吴裕雄--天生自然TensorFlow2教程:函数优化实战
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def himme ...
- 吴裕雄--天生自然TensorFlow2教程:反向传播算法
- 吴裕雄--天生自然TensorFlow2教程:链式法则
import tensorflow as tf x = tf.constant(1.) w1 = tf.constant(2.) b1 = tf.constant(1.) w2 = tf.consta ...
- 吴裕雄--天生自然TensorFlow2教程:多输出感知机及其梯度
import tensorflow as tf x = tf.random.normal([2, 4]) w = tf.random.normal([4, 3]) b = tf.zeros([3]) ...
- 吴裕雄--天生自然TensorFlow2教程:单输出感知机及其梯度
import tensorflow as tf x = tf.random.normal([1, 3]) w = tf.ones([3, 1]) b = tf.ones([1]) y = tf.con ...
- 吴裕雄--天生自然TensorFlow2教程:损失函数及其梯度
import tensorflow as tf x = tf.random.normal([2, 4]) w = tf.random.normal([4, 3]) b = tf.zeros([3]) ...
- 吴裕雄--天生自然TensorFlow2教程:激活函数及其梯度
import tensorflow as tf a = tf.linspace(-10., 10., 10) a with tf.GradientTape() as tape: tape.watch( ...
- 吴裕雄--天生自然TensorFlow2教程:梯度下降简介
import tensorflow as tf w = tf.constant(1.) x = tf.constant(2.) y = x * w with tf.GradientTape() as ...
随机推荐
- 数据结构学习笔记 <1> 线性表
一.线性表的抽象数据类型描述 类型名:线性表(List) 数据对象集:线性表示n(>=0)个元素构成的有序序列(a1,a2,……,an) 操作集:线性表L∈List, 整数i表示位置,元素X∈ ...
- AlertDialog 、SimpleDialog、 showModalBottomSheet、showToast 自定义 Dialog
// AlertDialog .SimpleDialog.showModalBottomSheet.showToast // 使用showToast安装插件 https://pub.dev/packa ...
- centos 添加rpmfusion源,yum 安装 ffmpeg
rpmfusion提供了,在Fedora和 centos 源之外的其他yum 源 例如ffmpeg 在 centos 基础源和epel-release 里面都没有, 但是可以在rpmfusion中找到 ...
- scrapy下载 大文件处理
# 一个校花网图片下载的案例,也适合大文件处理,多个文件视频,音频处理 工程流程 -- scrapy startproject xx cd xx scrapy genspider hh www.xx. ...
- 自己centos7成功的修改了主机名(记录了该改哪些文件)
1.更改/etc/hosts 方法(1)可以直接的去更改这个文件,更改的格式:直接vi编辑器打开,之后直接写上自己想要的主机名字就好,不用写成键值对的形式 [root@localhost etc]# ...
- app内区域截图利用html2Canvals保存到手机 截屏 (html2Canvas使用版本是:0.5.0-beta3。)
app内区域截图利用html2Canvals保存到手机 app内有时候需要区域内的截图保存dom为图像,我们可以使用html2Canvas将dom转换成base64图像字符串,然后再利用5+api保存 ...
- Centos610-Nginx-TCP代理配置
1.安装Nginx 详见<nginx>安装 2.下载nginx_tcp_proxy_module模块 下载 wget https://github.com/yaoweibin/nginx ...
- 「JSOI2015」圈地
「JSOI2015」圈地 传送门 显然是最小割. 首先对于所有房子,权值 \(> 0\) 的连边 \(s \to i\) ,权值 \(< 0\) 的连边 \(i \to t\) ,然后对于 ...
- Spring Cloud Alibaba 实战 之 Nacos 服务注册和发现
服务注册与发现,服务发现主要用于实现各个微服务实例的自动化注册与发现,是微服务治理的核心,学习 Spring Cloud Alibaba,首先要了解框架中的服务注册和发现组件——Nacos. 一.Sp ...
- JavaScript自学笔记(1)---表单验证,let和const,JSON文件
今天开个JS自学笔记,本身JS的语法很简单,如果学过Java或者C系的都很容易,就不讨论了.主要是讨论实际应用的问题. 1.表单验证: a.html自动验证: HTML 表单验证可以通过浏览器来自动完 ...