1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
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. # cast(x, dtype, name=None) 张量数据类型转换 将数据转换成对应的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) # (60000, 28, 28) (60000,) x 是图片的数据 有60000张28*28的数据 y 是分类数据 batchsz = 128 # 单个batch的size ## 创建训练数据集 db = tf.data.Dataset.from_tensor_slices((x, y)) # 对数据进行切片 datasets中的函数 tf.data.Dataset.from_tensor_slices((features, labels)) db = db.map(preprocess).shuffle(10000).batch(batchsz) # 把数据打乱然后打包成batch ## 创建验证数据集 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) # batch: (128, 28, 28) (128,) ## 创建一个神经网络 每层进行降维 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) # 完成一次前向传播 [b, 784] => [b, 10] y_onehot = tf.one_hot(y, depth=10) # [b] # 求出loss loss_mse = tf.reduce_mean(tf.losses.MSE(y_onehot, logits)) loss_ce = tf.losses.categorical_crossentropy(y_onehot, logits, from_logits=True) loss_ce = tf.reduce_mean(loss_ce) # loss 要求均值因此是针对每一个来做的 # 完成梯度的计算 原地更新 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) # 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)) total_correct += int(correct) total_num += x.shape[0] acc = total_correct / total_num print(epoch, 'test acc:', acc) if __name__ == '__main__': main() |