Preparing the data

The first activity is the data preparation. To start, let's import all the required libraries. As we discussed earlier, we are going to use the MNIST database for the dataset of handwritten digits:

from __future__ import print_function
from matplotlib import pyplot as plt
import keras
from keras.datasets import mnist

mnist is the dataset that contains the handwritten digits database, so we need to import that, as follows:

from keras.models import Sequential

The preceding code imports the Sequential model type from Keras. This is simply a linear stack of neural network layers:

from keras.layers import Dense, Dropout, Flatten

Now, we need to import the core layers from Keras. These are the layers that are used in almost any neural network:

from keras.layers import Conv2D, MaxPooling2D

Import the CNN layers from Keras. These are the convolutional layers that will help us efficiently train on image data:

from keras.utils import np_utils

Import Utils. This will help us do data transformation later:

from keras import backend as K 
import coremltools

coremltools will help us convert the Keras model into the Core ML model:

(x_train, y_train), (x_val, y_val) = mnist.load_data()

Load the pre-shuffled MNIST data into train and test sets:

# Inspect x data
print('x_train shape: ', x_train.shape)
print(x_train.shape[0], 'training samples')
print('x_val shape: ', x_val.shape)
print(x_val.shape[0], 'validation samples')
print('First x sample ', x_train[0])

If you run the preceding code, it will show the shape of X, Y, and also the first record of X.

So, we have 60,000 samples in our training set, and the images are 28 x 28 pixels each. We can confirm this by plotting the first sample in matplotlib:

plt.imshow(x_train[0])

This statement will use the matplotlib library to plot the first record of x_train, which will give the following output:

The following lines will print the y_train shape and the first 10 elements in y_train

print('y_train shape: ', y_train.shape)
print('First 10 y_train elements:', y_train[:10])

The following code will find the input shape of the image. The MNIST image data values are of the uint8 type, in the [0, 255] range, but Keras needs values of the float32 type in the [0, 1] range:

img_rows, img_cols = x_train.shape[1], x_train.shape[2]
num_classes = 10

# Set input_shape for channels_first or channels_last
if K.image_data_format() == 'channels_first':
x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
x_val = x_val.reshape(x_val.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_val = x_val.reshape(x_val.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)

print('x_train shape:', x_train.shape)
# x_train shape: (60000, 28, 28, 1)
print('x_val shape:', x_val.shape)
# x_val shape: (10000, 28, 28, 1)
print('input_shape:', input_shape)

Using the following code, we are converting the datatype to be compatible with the datatype that is defined in Keras:

x_train = x_train.astype('float32')
x_val = x_val.astype('float32')
x_train /= 255
x_val /= 255

Now, we have a one-dimensional of 60,000 elements in y. Let's convert it into a 60,000 x 10 array, as follows:

y_train = np_utils.to_categorical(y_train, num_classes)
y_val = np_utils.to_categorical(y_val, num_classes)
print('New y_train shape: ', y_train.shape)
# (60000, 10)
print('New y_train shape: ', y_train.shape)
# (60000, 10)
print('First 10 y_train elements, reshaped: ', y_train[:10])

Now, y_train will look like this:

In the preceding array, we can find that for the presence of digits, the corresponding position will be filled with 1—all others will be filled with 0. For the first record, we can understand that the predicted digit is 5, because the 6th position (starting from 0) was filled with 1.

Now that the data preparation is complete, we need to define the model's architecture.

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

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