吴裕雄--天生自然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 ...
随机推荐
- 6.springboot----------JSR303校验
JSR303校验(Java Specification Requests的缩写,意思是Java 规范提案) 有一个注解叫:@Validated //数据校验 这是默认的↓ 这是你可以改的↓
- 题解【BZOJ4145】「AMPPZ2014」The Prices
题目描述 你要购买 \(m\) 种物品各一件,一共有 \(n\) 家商店,你到第 \(i\) 家商店的路费为 \(d[i]\),在第 \(i\) 家商店购买第 \(j\) 种物品的费用为 \(c[i] ...
- 题解【洛谷P1807】最长路_NOI导刊2010提高(07)
题面 题解 最长路模板. 只需要在最短路的模板上把符号改一下\(+\)初值赋为\(-1\)即可. 注意一定是单向边,不然出现了正环就没有最长路了,就好比出现了负环就没有最短路了. 只能用\(SPFA\ ...
- Chrome浏览器添加信任站点
转载来源:https://zhidao.baidu.com/question/1946829886340846268.html 在浏览器地址栏输入:chrome://net-internals/#hs ...
- 用Emmet写前端代码
Emmet插件:可以用 emmet代码+Tap 写出更多并快捷的html代码,主流编辑器均可安装,安装方法也均不相同! <!-- html:5或者!可以生成html5文档 --> < ...
- CLR处理损坏状态的异常
你有没有写过不太正确但足够接近的代码?当一切顺利的时候,你是否不得不编写运行良好的代码,但是你不太确定当出了问题时会发生什么?有一个简单的.不正确的语句可能位于您编写或必须维护的代码中:catch ( ...
- Python 多任务(线程) day2 (1)
结论:多线程全局变量是共享的 (03) 因为多线程一般是配合使用,如果不共享,那么就要等到一个线程执行完,再把变量传递给另一个线程,就变成单线程了 但是如果多个线程同时需要修改一个全局变量,就会出现资 ...
- C# 委托实例实现的多种类型
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- 【PAT甲级】1103 Integer Factorization (30 分)
题意: 输入三个正整数N,K,P(N<=400,K<=N,2<=P<=7),降序输出由K个正整数的P次方和为N的等式,否则输出"Impossible". / ...
- 任意模数 n 次剩余
\(n\) 次剩余 你需要解方程 \(x^n\equiv k\pmod m\),其中 \(x\in [0,m-1]\). 保证解数不超过 \(C=10^6\) \(1\le n,m,k\le 10^9 ...