MNIST with CNNs

This notebook introduces convolutional neural networks, widely employed for computer vision, using Keras. Their performance is demonstrated on the MNIST handwritten digit data set.


In [ ]:
%matplotlib inline
%matplotlib notebook
import keras
from keras.datasets import mnist
from keras import backend as K
import numpy as np
import matplotlib.pyplot as plt

In [ ]:
# input image dimensions

img_rows, img_cols = 28, 28

# the data, shuffled and split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.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_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print 'x_train shape:', x_train.shape
print x_train.shape[0], 'train samples'
print x_test.shape[0], 'test samples'

In [ ]:
def get_splits(X, y, ratio=0.1, cat=False):
    """
    Finds a random split of size ratio*size(data).
    Returns the corresponding splits of X and y.
    """
    val_ids = np.random.choice(np.arange(X.shape[0]), int(X.shape[0]*ratio), replace=False)
    train_ids = np.delete(np.arange(X.shape[0]), val_ids)
    x_train = X[train_ids,:]
    x_val = X[val_ids,:]
    if cat:
        y_train = y[train_ids,:]
        y_val = y[val_ids,:]
    else:
        y_train = y[train_ids]
        y_val = y[val_ids]                
    return x_train, y_train, x_val, y_val

In [ ]:
# Split apart validation set
x_train, y_train, x_val, y_val = get_splits(x_train, y_train, ratio=0.05, cat=False)
print 'Train: {}. Validation: {}'.format(x_train.shape, x_val.shape)

In [ ]:
# convert labels to one-hot form
num_classes=10
y_train = keras.utils.to_categorical(y_train, num_classes)
y_val = keras.utils.to_categorical(y_val, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

In [ ]:
# Build the CNN
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=(img_rows, img_cols, 1)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))

In [ ]:
model.summary()

In [ ]:
model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])

In [ ]:
train_loss = []
val_loss = []

In [ ]:
# Train
fig = plt.figure()
ax = fig.gca()

batch_size = 128
epochs = 12

for i in range(epochs):
    history = model.fit(x_train, y_train, epochs=1, batch_size=batch_size, verbose=1, validation_data=(x_val, y_val))
    
    train_loss.append(history.history['loss'])
    val_loss.append(history.history['val_loss'])
    
    ax.clear()    
    ax.plot(train_loss, color='red', label='Train')
    ax.plot(val_loss, color='blue', label='Validation')

    fig.canvas.draw()

In [ ]:
# Predict random digits from the test set
import matplotlib.image as mpimg
i = np.random.choice(np.arange(x_test.shape[1]))
img_x = x_test[i].reshape([28,28])
x = np.array([x_test[i]])
print ('Prediction: {}'.format((np.argmax(model.predict(x)))))
plt.imshow(img_x,cmap='gray')

In [ ]:
# Predict our hand-written digits
# Try it at home: draw a number on a 28x28 black background, using any Paint-like app. See if the model can guess it
import matplotlib.image as mpimg
img=mpimg.imread('number.png')
x = np.array([img[:,:,[0]]])
print ('Prediction: {}'.format((np.argmax(model.predict(x)))))
plt.imshow(img,cmap='gray')