In [1]:
from __future__ import print_function
import numpy as np
np.random.seed(1337)  # for reproducibility

import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras import backend as K


Using TensorFlow backend.

Preprocess data


In [2]:
nb_classes = 10

# input image dimensions
img_rows, img_cols = 28, 28
# number of convolutional filters to use
nb_filters = 32
# size of pooling area for max pooling
pool_size = (2, 2)
# convolution kernel size
kernel_size = (3, 3)

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

if K.image_dim_ordering() == 'th':
    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')

# convert class vectors to binary class matrices
Y_train = np_utils.to_categorical(y_train, nb_classes)
Y_test = np_utils.to_categorical(y_test, nb_classes)


X_train shape: (60000, 28, 28, 1)
60000 train samples
10000 test samples

Build a Keras model using the Sequential API


In [3]:
batch_size = 50
nb_epoch = 10

model = Sequential()

model.add(Convolution2D(nb_filters, kernel_size,
                        padding='valid',
                        input_shape=input_shape,
                        activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Convolution2D(nb_filters, kernel_size,activation='relu'))
model.add(Dropout(rate=0.25))
model.add(Flatten())
model.add(Dense(64,activation='relu'))
model.add(Dropout(rate=5))
model.add(Dense(nb_classes,activation='softmax'))

model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
model.summary()


_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 26, 26, 32)        320       
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 13, 13, 32)        0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 11, 11, 32)        9248      
_________________________________________________________________
dropout_1 (Dropout)          (None, 11, 11, 32)        0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 3872)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 64)                247872    
_________________________________________________________________
dropout_2 (Dropout)          (None, 64)                0         
_________________________________________________________________
dense_2 (Dense)              (None, 10)                650       
=================================================================
Total params: 258,090
Trainable params: 258,090
Non-trainable params: 0
_________________________________________________________________

Train and evaluate the model


In [4]:
model.fit(X_train[0:10000, ...], Y_train[0:10000, ...], batch_size=batch_size, epochs=nb_epoch,
          verbose=1, validation_data=(X_test, Y_test))
score = model.evaluate(X_test, Y_test, verbose=0)
print('Test score:', score[0])
print('Test accuracy:', score[1])


Train on 10000 samples, validate on 10000 samples
Epoch 1/10
10000/10000 [==============================] - 5s - loss: 0.4915 - acc: 0.8532 - val_loss: 0.2062 - val_acc: 0.9433
Epoch 2/10
10000/10000 [==============================] - 5s - loss: 0.1562 - acc: 0.9527 - val_loss: 0.1288 - val_acc: 0.9605
Epoch 3/10
10000/10000 [==============================] - 5s - loss: 0.0950 - acc: 0.9704 - val_loss: 0.0890 - val_acc: 0.9741
Epoch 4/10
10000/10000 [==============================] - 5s - loss: 0.0678 - acc: 0.9788 - val_loss: 0.0972 - val_acc: 0.97000.9
Epoch 5/10
10000/10000 [==============================] - 5s - loss: 0.0532 - acc: 0.9826 - val_loss: 0.0822 - val_acc: 0.9739
Epoch 6/10
10000/10000 [==============================] - 5s - loss: 0.0382 - acc: 0.9876 - val_loss: 0.0898 - val_acc: 0.9751
Epoch 7/10
10000/10000 [==============================] - 5s - loss: 0.0293 - acc: 0.9903 - val_loss: 0.0652 - val_acc: 0.9822
Epoch 8/10
10000/10000 [==============================] - 5s - loss: 0.0277 - acc: 0.9917 - val_loss: 0.0840 - val_acc: 0.9758
Epoch 9/10
10000/10000 [==============================] - 5s - loss: 0.0217 - acc: 0.9918 - val_loss: 0.0736 - val_acc: 0.9787
Epoch 10/10
10000/10000 [==============================] - 5s - loss: 0.0188 - acc: 0.9936 - val_loss: 0.0735 - val_acc: 0.9812
Test score: 0.0734814465971
Test accuracy: 0.9812

Save the model


In [5]:
model.save('example_keras_mnist_model.h5')

In [ ]: