step1、数据集预处理
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, Sequential,datasets,optimizers
# 将数据转换为tensor
def preprocess(x, y):
# [0~255] => [-1~1]
x = 2 * tf.cast(x, dtype=tf.float32) / 255. - 1.
y = tf.cast(y, dtype=tf.int32)
return x,y
# 数据加载
(x, y), (x_val, y_val) = datasets.mnist.load_data()
# 制作训练集以及测试集,方便迭代获取每个batch
batchsz = 128
train_db = tf.data.Dataset.from_tensor_slices((x,y))
train_db = train_db.map(preprocess).shuffle(10000).batch(batchsz)
test_db = tf.data.Dataset.from_tensor_slices((x_val, y_val))
test_db = test_db.map(preprocess).batch(batchsz)
step2、模型构建
model = Sequential([
layers.Dense(512, activation='relu'),
layers.Dense(256, activation='relu'),
layers.Dense(10)])
model.build(input_shape=[None, 28*28])
optimizer = optimizers.SGD(learning_rate=1e-3)
step3、模型训练
for epoch in range(5):
for step,(x,y) in enumerate(train_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)) # 以MSE做损失函数
# 以交叉熵做损失函数,用于分类
loss_ce = tf.losses.categorical_crossentropy(y_onehot, logits, from_logits=True)
loss_ce = tf.reduce_mean(loss_ce)
# 利用交叉熵损失函数来求梯度
# model.trainable_variables包含所有需更新参数
grads = tape.gradient(loss_ce, model.trainable_variables)
# 利用梯度对参数进行更新
optimizer.apply_gradients(zip(grads, model.trainable_variables))
if step % 100 == 0:
print(epoch, step, 'loss:', float(loss_ce), float(loss_mse))
# 在测试集上进行测试
total_correct = 0
total_num = 0
for x, y in test_db :
# 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], int64
pred = tf.argmax(prob, axis=1) # 得到概率值最大的索引
pred = tf.cast(pred, dtype=tf.int32)
# pred:[b]
# y: [b]
# correct: [b], True: equal, False: not equal
# 统计 True 的个数,即预测正确的个数
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)