手撕代码:BP神经网络实现FashionMINST分类(基于Tensorflow + Keras实现)

共分为五个步骤:
1 读取数据集和预处理(batch)
2 创建网络:layers.Dense
3 梯度下降:tape.gradient(损失函数, 变量) + optimizer.apply_gradients(zip(…))
4 计算测试集准确率

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'

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)

batchsz = 128

# 二、数据预处理
db = tf.data.Dataset.from_tensor_slices((x,y))
db = db.map(preprocess).shuffle(10000).batch(batchsz)      # map用法:传入函数

db_test = tf.data.Dataset.from_tensor_slices((x_test,y_test))
db_test = db_test.map(preprocess).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):    #db中已经变成按batch分好的组,一个step即为一个batch一起训练

            # x: [b, 28, 28] => [b, 784]
            # y: [b]
            x = tf.reshape(x, [-1, 28*28])   # 此处x需要打平送入网络!
            # 四、梯度下降
            with tf.GradientTape() as tape:
                # [b, 784] => [b, 10]
                logits = model(x)           # 前向传播,调用了model的call方法
                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))


            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])
            # [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)  # tf.cast类型转换
            # 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))  # 统计1的个数

            total_correct += int(correct)    # 正确样本数
            total_num += x.shape[0]          # 当前epoch测试集总数

        acc = total_correct / total_num
        print(epoch, 'test acc:', acc)



if __name__ == '__main__':
    main()

你可能感兴趣的:(手撕算法,#,机器学习,神经网络)