Loading MNIST

Luckily for us, an MNIST loading function that retrieves the MNIST data and loads it for us is built right into Keras. All we need to do is import keras.datasets.mnist and use the load_data() method, as shown in the following code:

(train_X, train_y), (test_X, test_y) = mnist.load_data()

The shape of train_X is 50,000 x 28 x 28. As we explained in the Model inputs and outputs section, we will need to flatten the 28x28 matrix into a 784 element vector. NumPy makes that pretty easy. The following code illustrates this technique:

train_X = train_X.reshape(-1, 784)

With that out of the way, we should think about scaling the input. Previously, we used scikit-learn's StandardScaler. There's no need to do so with MNIST. Since we know every pixel is in the same range, from 0 to 255, we can easily convert the value to between 0 and 1 by dividing by 255, explicitly casting the data type to float32 before we do it, as shown in the following code:

train_X = train_X.astype('float32')
train_X /= 255

While we're loading data, we should probably convert our dependent variable vectors to categorical ones, as we talked about in the Model inputs and outputs section. To do so, we will use keras.utils.to_categorical(), with the help of the following code:

train_y = to_categorical(train_y)

With that, our data is now ready for training!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.172.38