fashion_mnist 数据集 tf2.0 练习--带详细注释

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics
# datasets :用于数据集管理 layers.Dense:用于构建全连接层, optimizers:优化器 metics:测试的度量器

def preprocess(x, y):

    x = tf.cast(x, dtype=tf.float32) / 255  # tf.convert_to_tensor 用于将不同数据转化为张量 可以是numpy数据 python数据 tensor数据
    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)

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).batch(batchsz)  # 测试集不需要shuffle

db_iter = iter(db)      # iter函数用来生成迭代器
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]
])

model.build(input_shape=[None, 28*28]) # 建立模型,传入数据
model.summary() # 调试的功能,作用是打印网络结构
optimizer = optimizers.Adam(lr=1e-3)

def main():

    for epoch in range(30):   # 数据集训练30遍

        for step, (x, y) in enumerate(db):
            # x: [b, 28*28]
            # y:[b]
            x = tf.reshape(x, [-1, 28*28])
            y_one_hot = tf.one_hot(y, depth=10)

            with tf.GradientTape() as tape:
                logits = model(x) # 把没有加激活函数的输出值称作logits。
                loss = tf.reduce_mean(tf.losses.MSE(y_one_hot, logits)) # 均方差损失函数。
                loss2 = tf.losses.categorical_crossentropy(y_one_hot, logits, from_logits=True) # 交叉熵损失函数,直接用logits进行运算,一定要设置from_logits=True。这里tf进行了封装,内部会转化为softmax并有一些优化,效果上,比手动算出softmax,然后计算loss,数值更稳定。
                loss2 = tf.reduce_mean(loss2) # 由于上一步计算的loss2是tensor,这里要做一下求平均值

            grads = tape.gradient(loss2, model.trainable_variables) # model.trainable_variables返回变量列表,不需要我们再额外管理变量
            optimizer.apply_gradients(zip(grads, model.trainable_variables)) # 反向传播计算。参数中 梯度(grads)和变量要一一对应,所以用了zip()

            if step % 100 == 0:
                print(epoch, step, 'loss:', float(loss2), float(loss))

        # test
        total_correct = 0
        total_num = 0
        for step, (x_test, y_test) in enumerate(db_test):
            # x: [b, 28*28]
            # y:[b] 测试情况下,y不需要做one_hot
            x = tf.reshape(x, [-1, 28*28])
            # [b, 28*28] => [b, 10]
            logits = model(x)
            # logits => prob [b, 10]
            prob = tf.nn.softmax(logits, axis=1)
            # [b, 10] => [b]
            pred = tf.argmax(prob, axis=1)
            pred = tf.cast(pred, 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, 'acc:', acc)





if __name__ == '__main__':
    main()

你可能感兴趣的:(学习总结)