Training a neural network on MNIST with Keras

使用集合让一切井井有条 根据您的偏好保存内容并对其进行分类。

This simple example demonstrates how to plug TensorFlow Datasets (TFDS) into a Keras model.

在 TensorFlow.org 上查看 在 Google Colab 中运行 在 Github 上查看源代码 下载笔记本
import tensorflow as tf
import tensorflow_datasets as tfds
2022-08-30 23:34:01.338999: E tensorflow/stream_executor/cuda/cuda_blas.cc:2981] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered
2022-08-30 23:34:02.063128: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer.so.7'; dlerror: libnvrtc.so.11.1: cannot open shared object file: No such file or directory
2022-08-30 23:34:02.063398: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer_plugin.so.7'; dlerror: libnvrtc.so.11.1: cannot open shared object file: No such file or directory
2022-08-30 23:34:02.063410: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.

第 1 步:创建输入流水线

首先,使用以下指南中的建议构建有效的输入流水线:

加载数据集

使用以下参数加载 MNIST 数据集:

  • shuffle_files=True:MNIST 数据仅存储在单个文件中,但是对于大型数据集则会以多个文件存储在磁盘中,在训练时最好将它们打乱顺序。
  • as_supervised=True:返回元组 (img, label) 而非字典 {'image': img, 'label': label}
(ds_train, ds_test), ds_info = tfds.load(
    'mnist',
    split=['train', 'test'],
    shuffle_files=True,
    as_supervised=True,
    with_info=True,
)

构建训练流水线

应用以下转换:

  • tf.data.Dataset.map:TFDS 提供 tf.uint8 类型的图像,而模型期望 tf.float32。因此,您需要对图像进行归一化。
  • tf.data.Dataset.cache:将数据集装入内存时,先缓存再打乱顺序以提高性能。
    :应在缓存后应用随机转换。
  • tf.data.Dataset.shuffle:要获得真正的随机性,请将打乱顺序缓冲区设置为完整的数据集大小。
    注:对于无法装入内存的大型数据集,如果系统允许,请使用 buffer_size=1000
  • tf.data.Dataset.batch:打乱顺序后对数据集的元素进行批处理,以在每个周期获得唯一的批次。
  • tf.data.Dataset.prefetch:最好通过预提取结束流水线以提升性能
def normalize_img(image, label):
  """Normalizes images: `uint8` -> `float32`."""
  return tf.cast(image, tf.float32) / 255., label

ds_train = ds_train.map(
    normalize_img, num_parallel_calls=tf.data.AUTOTUNE)
ds_train = ds_train.cache()
ds_train = ds_train.shuffle(ds_info.splits['train'].num_examples)
ds_train = ds_train.batch(128)
ds_train = ds_train.prefetch(tf.data.AUTOTUNE)

构建评估流水线

您的测试流水线与训练流水线类似,只有几点细微差异:

  • 您无需调用 tf.data.Dataset.shuffle
  • 在批处理后进行缓存,因为各个周期之间的批次可以相同。
ds_test = ds_test.map(
    normalize_img, num_parallel_calls=tf.data.AUTOTUNE)
ds_test = ds_test.batch(128)
ds_test = ds_test.cache()
ds_test = ds_test.prefetch(tf.data.AUTOTUNE)

第 2 步:创建并训练模型

将 TFDS 输入流水线插入一个简单的 Keras 模型、编译模型并训练它。

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dense(10)
])
model.compile(
    optimizer=tf.keras.optimizers.Adam(0.001),
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    metrics=[tf.keras.metrics.SparseCategoricalAccuracy()],
)

model.fit(
    ds_train,
    epochs=6,
    validation_data=ds_test,
)
Epoch 1/6
469/469 [==============================] - 4s 4ms/step - loss: 0.3573 - sparse_categorical_accuracy: 0.9015 - val_loss: 0.1897 - val_sparse_categorical_accuracy: 0.9464
Epoch 2/6
469/469 [==============================] - 1s 2ms/step - loss: 0.1617 - sparse_categorical_accuracy: 0.9535 - val_loss: 0.1357 - val_sparse_categorical_accuracy: 0.9601
Epoch 3/6
469/469 [==============================] - 1s 2ms/step - loss: 0.1146 - sparse_categorical_accuracy: 0.9672 - val_loss: 0.1099 - val_sparse_categorical_accuracy: 0.9678
Epoch 4/6
469/469 [==============================] - 1s 2ms/step - loss: 0.0895 - sparse_categorical_accuracy: 0.9739 - val_loss: 0.0890 - val_sparse_categorical_accuracy: 0.9726
Epoch 5/6
469/469 [==============================] - 1s 2ms/step - loss: 0.0716 - sparse_categorical_accuracy: 0.9794 - val_loss: 0.0856 - val_sparse_categorical_accuracy: 0.9741
Epoch 6/6
469/469 [==============================] - 1s 2ms/step - loss: 0.0597 - sparse_categorical_accuracy: 0.9828 - val_loss: 0.0823 - val_sparse_categorical_accuracy: 0.9756
<keras.callbacks.History at 0x7fa2e404a850>