Load NumPy Data with tf.data

View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook

This tutorial provides an example of loading data from NumPy arrays into a tf.data.Dataset.

This example loads the MNIST dataset from a .npz file. However, the source of the NumPy arrays is not important.

Setup

!pip install -q tensorflow==2.0.0-beta1
from __future__ import absolute_import, division, print_function, unicode_literals
 
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds

Load from .npz file

DATA_URL = 'https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz'

path = tf.keras.utils.get_file('mnist.npz', DATA_URL)
with np.load(path) as data:
  train_examples = data['x_train']
  train_labels = data['y_train']
  test_examples = data['x_test']
  test_labels = data['y_test']

Load NumPy arrays with tf.data.Dataset

Assuming you have an array of examples and a corresponding array of labels, pass the two arrays as a tuple into tf.data.Dataset.from_tensor_slices to create a tf.data.Dataset.

train_dataset = tf.data.Dataset.from_tensor_slices((train_examples, train_labels))
test_dataset = tf.data.Dataset.from_tensor_slices((test_examples, test_labels))

Use the datasets

Shuffle and batch the datasets

BATCH_SIZE = 64
SHUFFLE_BUFFER_SIZE = 100

train_dataset = train_dataset.shuffle(SHUFFLE_BUFFER_SIZE).batch(BATCH_SIZE)
test_dataset = test_dataset.batch(BATCH_SIZE)

Build and train a model

model = tf.keras.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer=tf.keras.optimizers.RMSprop(),
                loss=tf.keras.losses.SparseCategoricalCrossentropy(),
                metrics=[tf.keras.metrics.SparseCategoricalAccuracy()])
model.fit(train_dataset, epochs=10)
WARNING: Logging before flag parsing goes to stderr.
W0614 17:49:15.084038 140002163730176 deprecation.py:323] From /tmpfs/src/tf_docs_env/lib/python3.5/site-packages/tensorflow/python/ops/math_grad.py:1250: add_dispatch_support.<locals>.wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.where in 2.0, which has the same broadcast rule as np.where

Epoch 1/10
938/938 [==============================] - 4s 5ms/step - loss: 7.1200 - sparse_categorical_accuracy: 0.5548
Epoch 2/10
938/938 [==============================] - 3s 4ms/step - loss: 5.9246 - sparse_categorical_accuracy: 0.6306
Epoch 3/10
938/938 [==============================] - 3s 4ms/step - loss: 5.7627 - sparse_categorical_accuracy: 0.6411
Epoch 4/10
938/938 [==============================] - 3s 4ms/step - loss: 4.9406 - sparse_categorical_accuracy: 0.6913
Epoch 5/10
938/938 [==============================] - 4s 4ms/step - loss: 4.3595 - sparse_categorical_accuracy: 0.7276
Epoch 6/10
938/938 [==============================] - 3s 4ms/step - loss: 4.2325 - sparse_categorical_accuracy: 0.7357
Epoch 7/10
938/938 [==============================] - 4s 4ms/step - loss: 4.1040 - sparse_categorical_accuracy: 0.7441
Epoch 8/10
938/938 [==============================] - 4s 4ms/step - loss: 3.8213 - sparse_categorical_accuracy: 0.7610
Epoch 9/10
938/938 [==============================] - 4s 4ms/step - loss: 2.7590 - sparse_categorical_accuracy: 0.8268
Epoch 10/10
938/938 [==============================] - 4s 4ms/step - loss: 2.6806 - sparse_categorical_accuracy: 0.8320

<tensorflow.python.keras.callbacks.History at 0x7f547a4b6e10>
model.evaluate(test_dataset)
157/157 [==============================] - 0s 3ms/step - loss: 2.5322 - sparse_categorical_accuracy: 0.8411

[2.5322052703541553, 0.8411]