# 导入库
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, datasets, optimizers, Sequential, metrics
# 获取fashion_mnist数据集
(x, y), (x_test, y_test) = datasets.fashion_mnist.load_data()
print(x.shape, y.shape)
# 定义batch大小
batch_size = 128
# 定义预处理函数
def preprocess(x, y):
# 把x转换为float32,并把值压缩到[0, 1]
x = tf.cast(x, dtype=tf.float32) / 255.
# 把y转换为int32
y = tf.cast(y, dtype=tf.int32)
return x, y
# db数据集
# 将x,y转换成Dataset对象,才能进行随机打散,设置batch等操作
db = tf.data.Dataset.from_tensor_slices((x, y))
# 调用预处理函数,返回新的x,y的值。并随机打散,设置batch为128
db = db.map(preprocess).shuffle(10000).batch(batch_size)
# db_test测试数据集
# 将x_test,y_test转换成Dataset对象,才能进行设置batch等操作
db_test = tf.data.Dataset.from_tensor_slices((x_test, y_test))
# 调用预处理函数,返回新的x,y的值。并设置batch为128
db_test = db_test.map(preprocess).batch(batch_size)
# 查看样本
# db_iter = iter(db)
# spmple = next(db_iter)
# print(spmple[0].shape, spmple[1].shape)
# 定义网络模型
# 5个全连接层
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]
])
# 用于初始化层内的参数和变量(权重w和偏置值b),构建权值矩阵
# 通过build 函数完成内部张量(权值)的创建,其中None为任意设置的batch 数量,28*28为输入特征长度
model.build(input_shape=[None, 28*28])
# 查看网络结构
model.summary()
# 设置梯度优化器
# 对所有w、b进行更新操作,即w = w - lr * grad
optimizer = optimizers.Adam(lr=1e-3)
# 主函数
def main():
# epoch = 30
for epoch in range(30):
for step, (x, y) in enumerate(db):
# x: [b, 28, 28]
# y: [b]
x = tf.reshape(x, [-1, 784]) # [b, 28, 28] => [b, 784]
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)
# 梯度更新,对所有trainable_variables更新
optimizer.apply_gradients(zip(grads, model.trainable_variables))
# 每100个step打印一次信息
if step % 100 == 0:
print(epoch, step, 'loss:', float(loss_ce))
# 测试数据集test
total_correct, total_num = 0, 0
for x,y in db_test:
# x: [b, 28, 28]
# y: [b]
x = tf.reshape(x, [-1, 784])
logits = model(x)
# logits => prod [b, 10]
prod = tf.nn.softmax(logits, axis=1)
# [b, 10] => [b]
pred = tf.argmax(prod, axis=1)
pred = tf.cast(pred, dtype=tf.int32)
# pred: [b]
# y: [b]
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, 'test acc', acc)
if __name__ == '__main__':
main()
【TF2】记录一次完整的深度学习代码
最新推荐文章于 2024-03-13 22:52:58 发布