Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakelevi1996/5c532463d59016f42d2bbdcfedd3372a to your computer and use it in GitHub Desktop.
Save jakelevi1996/5c532463d59016f42d2bbdcfedd3372a to your computer and use it in GitHub Desktop.
Convert MNIST to NumPy format using TensorFlow and Python

Convert MNIST to NumPy format using TensorFlow and Python

The MNIST dataset can be loaded and saved in .npz format as follows (tested in Python 3.7.6, TensorFlow 2.1.0, numpy 1.18.1):

import tensorflow as tf, numpy as np

(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

np.savez("data/mnist",
    x_train=x_train, x_test=x_test, y_train=y_train, y_test=y_test)

These numpy arrays can be loaded as follows (without needing to import tensorflow):

import numpy as np

def load_mnist(filename="data/mnist.npz"):
    mnist_file = np.load(filename)
    x_train = mnist_file["x_train"]
    y_train = mnist_file["y_train"]
    x_test = mnist_file["x_test"]
    y_test = mnist_file["y_test"]
    return x_train, y_train, x_test, y_test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment