📜 原文链接:https://tensorflow.google.cn/tutorials/quickstart/advanced

    将 TensorFlow 载入到程序中:

    1. import tensorflow as tf
    2. from tensorflow.keras.layers import Dense, Flatten, Conv2D
    3. from tensorflow.keras import Model

    载入并准备好 MNIST 数据集:

    1. mnist = tf.keras.datasets.mnist
    2. (x_train, y_train), (x_test, y_test) = mnist.load_data()
    3. x_train, x_test = x_train / 255.0, x_test / 255.0
    4. # 添加一个信号维度
    5. x_train = x_train[..., tf.newaxis]
    6. x_test = x_test[..., tf.newaxis]

    使用 tf.data 将数据集切分为批(batch)数据集,并对数据进行打乱:

    1. train_ds = tf.data.Dataset.from_tensor_slices((x_train, y_train)).shuffle(10000).batch(32)
    2. test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32)

    通过 Keras 模块子类 API 构建 tf.keras 模型:

    1. class MyModel(Model):
    2. def __init__(self):
    3. super(MyModel, self).__init__()
    4. self.conv1 = Conv2D(32, 3, activation='relu')
    5. self.flatten = Flatten()
    6. self.d1 = Dense(128, activation='relu')
    7. self.d2 = Dense(10)
    8. def call(self, x):
    9. x = self.conv1(x)
    10. x = self.flatten(x)
    11. x = self.d1(x)
    12. return self.d2(x)
    13. # Create an instance of the model
    14. model = MyModel()

    选择模型训练的优化器和损失函数:

    1. loss_obj = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
    2. optimizer = tf.keras.optimizers.Adam()

    选择衡量指标来度量模型的损失值(loss)和准确率(accuracy),这些指标的值在每次迭代(epoch)上累加,然后打印出整体的结果:

    1. train_loss = tf.keras.metrics.Mean(name='train_loss')
    2. train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')
    3. test_loss = tf.keras.metrics.Mean(name='test_loss')
    4. test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy')

    使用 tf.GradientTape 来训练模型:

    1. @tf.function
    2. def train_step(images, labels):
    3. with tf.GradientTape() as tape:
    4. # train=True is only needed if there are layers with different
    5. # behavior during training versus inference(e.g. Dropout)
    6. predictions = model(images, training=True)
    7. loss = loss_obj(labels, predictions)
    8. gradients = tape.gradient(loss, model.trainable_variables)
    9. optimizer.apply_gradients(zip(gradients, model.trainable_variables))
    10. train_loss(loss)
    11. train_accuracy(labels, predictions)

    测试模型:

    1. @tf.function
    2. def test_step(images, labels):
    3. # train=False is only needed if there are layers with different
    4. # behavior during training versus inference(e.g. Dropout)
    5. predictions = model(images, training=False)
    6. t_loss = loss_obj(labels, predictions)
    7. test_loss(t_loss)
    8. test_accuracy(labels, predictions)
    9. EPOCHS = 5
    10. for epoch in range(EPOCHS):
    11. # Reset the metrics at the start of the next epoch
    12. train_loss.reset_states()
    13. train_accuracy.reset_states()
    14. test_loss.reset_states()
    15. test_accuracy.reset_states()
    16. for images, labels in train_ds:
    17. train_step(images, labels)
    18. for test_images, test_labels in test_ds:
    19. test_step(test_images, test_labels)
    20. template = 'Epoch {}, Loss: {}, Accuracy: {}, Test Loss: {}, Test Accuracy: {}'
    21. print(template.format(epoch + 1,
    22. train_loss.result(),
    23. train_accuracy.result() * 100,
    24. test_loss.result(),
    25. test_accuracy.result() * 100))

    📌 终端输出结果:

    1. Epoch 1, Loss: 0.041934385895729065, Accuracy: 98.72000122070312, Test Loss: 0.05677669122815132, Test Accuracy: 98.13999938964844
    2. Epoch 2, Loss: 0.022656703367829323, Accuracy: 99.2699966430664, Test Loss: 0.056276965886354446, Test Accuracy: 98.27999877929688
    3. Epoch 3, Loss: 0.014473672024905682, Accuracy: 99.51333618164062, Test Loss: 0.06184951588511467, Test Accuracy: 98.19999694824219
    4. Epoch 4, Loss: 0.007586538791656494, Accuracy: 99.7683334350586, Test Loss: 0.06390485912561417, Test Accuracy: 98.38999938964844
    5. Epoch 5, Loss: 0.0070701888762414455, Accuracy: 99.76499938964844, Test Loss: 0.07669035345315933, Test Accuracy: 98.30999755859375