Fashion-Minst数据集是Minst数据集的升级版,具有更高的复杂性
如下代码实现Fashion-Minst数据集的训练及测试
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics
import os
# 避免出现一些不必要的警告
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# 下载数据集
(x, y), (x_test, y_test) = datasets.fashion_mnist.load_data()
print(x.shape, y.shape)
print(x_test.shape, y_test.shape)
# 定义一个预处理的函数
def preprocess(x, y):
x = tf.cast(x, dtype=tf.float32) / 255. # 转化到0到1的范围
y = tf.cast(y, dtype=tf.int32)
return x, y
batchsz = 128
# 构建数据集、进行预处理
db = tf.data.Dataset.from_tensor_slices((x, y))
db = db.map(preprocess).shuffle(10000).batch(batchsz)
db_test = tf.data.Dataset.from_tensor_slices((x_test, y_test))
db_test = db_test.map(preprocess).shuffle(10000).batch(batchsz)
# 得到一个迭代器
db_iter = iter(db)
sample = next(db_iter)
print('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(30):
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)) # MSE完成均方差的计算
loss_ce = tf.losses.categorical_crossentropy(y_onehot, logits, from_logits=True)
loss_ce = tf.reduce_mean(loss_ce) # 为了求标量
grads = tape.gradient(loss_ce, model.trainable_variables)
optimizer.apply_gradients(zip(grads, model.trainable_variables)) # zip 对每一个地方的梯度在前,参数在后
if step % 100 == 0:
print(epoch, step, '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])
# y = tf.reshape(y, [128 * 128, ])
# [b, 10]
logits = model(x)
# logits => prob ,[b, 10]
prob = tf.nn.softmax(logits, axis=1) # 完成概率的转换 在0和1之间 总和为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, F: not equal
# print(pred.dtype, y.dtype) # 都是int32类型
# print(pred.shape, y.shape)
# y = tf.reshape(y, [-1, 128 * 128])
correct = tf.equal(pred, y)
correct = tf.reduce_sum(tf.cast(correct, dtype=tf.int32))
total_correct += int(correct) # tensor => numpy
total_num += x.shape[0]
acc = total_correct / total_num
print(epoch, 'test acc:', acc)
# 避免全局变量的error
if __name__ == '__main__':
main()