Attend the Women in ML Symposium on December 7 Register now

Training a neural network on MNIST with Keras

Stay organized with collections Save and categorize content based on your preferences.

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

View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook
import tensorflow as tf
import tensorflow_datasets as tfds

Step 1: Create your input pipeline

Start by building an efficient input pipeline using advices from:

Load a dataset

Load the MNIST dataset with the following arguments:

  • shuffle_files=True: The MNIST data is only stored in a single file, but for larger datasets with multiple files on disk, it's good practice to shuffle them when training.
  • as_supervised=True: Returns a tuple (img, label) instead of a dictionary {'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,
)
2022-02-10 08:54:21.184186: E tensorflow/stream_executor/cuda/cuda_driver.cc:271] failed call to cuInit: CUDA_ERROR_NO_DEVICE: no CUDA-capable device is detected

Build a training pipeline

Apply the following transformations:

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)

Build an evaluation pipeline

Your testing pipeline is similar to the training pipeline with small differences:

  • You don't need to call tf.data.Dataset.shuffle.
  • Caching is done after batching because batches can be the same between epochs.
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)

Step 2: Create and train the model

Plug the TFDS input pipeline into a simple Keras model, compile the model, and train it.

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 3ms/step - loss: 0.3661 - sparse_categorical_accuracy: 0.8988 - val_loss: 0.1958 - val_sparse_categorical_accuracy: 0.9445
Epoch 2/6
469/469 [==============================] - 1s 2ms/step - loss: 0.1666 - sparse_categorical_accuracy: 0.9525 - val_loss: 0.1336 - val_sparse_categorical_accuracy: 0.9607
Epoch 3/6
469/469 [==============================] - 1s 2ms/step - loss: 0.1197 - sparse_categorical_accuracy: 0.9657 - val_loss: 0.1163 - val_sparse_categorical_accuracy: 0.9647
Epoch 4/6
469/469 [==============================] - 1s 2ms/step - loss: 0.0928 - sparse_categorical_accuracy: 0.9733 - val_loss: 0.1000 - val_sparse_categorical_accuracy: 0.9699
Epoch 5/6
469/469 [==============================] - 1s 2ms/step - loss: 0.0760 - sparse_categorical_accuracy: 0.9775 - val_loss: 0.0862 - val_sparse_categorical_accuracy: 0.9733
Epoch 6/6
469/469 [==============================] - 1s 2ms/step - loss: 0.0628 - sparse_categorical_accuracy: 0.9814 - val_loss: 0.0823 - val_sparse_categorical_accuracy: 0.9755
<keras.callbacks.History at 0x7fb3b06a4650>