Modified National Institute of Standards and Technology (MNIST) Data: Convolutional Neural Network (CNN)

In [1]:
'''Trains a simple convnet on the MNIST dataset.

Gets to 99.25% test accuracy after 12 epochs
(there is still a lot of margin for parameter tuning).
16 seconds per epoch on a GRID K520 GPU.
'''

from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
Using CNTK backend
In [2]:
batch_size = 128
num_classes = 10
epochs = 12

# 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)
In [3]:
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 = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
x_train shape: (60000, 28, 28, 1)
60000 train samples
10000 test samples
In [4]:
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=input_shape))
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'))
model.summary()
# ParameterCount = FilterCount * (InputCount * FilterHeight * FilterWidth + 1)
# 32 * ( 1 * 3 * 3 + 1) =       320
# 64 * (32 * 3 * 3 + 1) =    18,496
# 64 * 12 * 12          =     9,216
# (9216 + 1) * 128      = 1,179,776
# 129 * 10              =     1,290

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

model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 26, 26, 32)        320       
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 24, 24, 64)        18496     
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 12, 12, 64)        0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 12, 12, 64)        0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 9216)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 128)               1179776   
_________________________________________________________________
dropout_2 (Dropout)          (None, 128)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 10)                1290      
=================================================================
Total params: 1,199,882
Trainable params: 1,199,882
Non-trainable params: 0
_________________________________________________________________
Train on 60000 samples, validate on 10000 samples
Epoch 1/12
  256/60000 [..............................] - ETA: 108s - loss: 2.2850 - acc: 0.1406
/home/dadebarr/anaconda3/lib/python3.5/site-packages/cntk/core.py:351: UserWarning: your data is of type "float64", but your input variable (uid "Input113") expects "<class 'numpy.float32'>". Please convert your data beforehand to speed up training.
  (sample.dtype, var.uid, str(var.dtype)))
60000/60000 [==============================] - 15s - loss: 0.3489 - acc: 0.8931 - val_loss: 0.0814 - val_acc: 0.9749
Epoch 2/12
60000/60000 [==============================] - 14s - loss: 0.1145 - acc: 0.9660 - val_loss: 0.0513 - val_acc: 0.9833
Epoch 3/12
60000/60000 [==============================] - 16s - loss: 0.0864 - acc: 0.9746 - val_loss: 0.0453 - val_acc: 0.9850
Epoch 4/12
60000/60000 [==============================] - 15s - loss: 0.0734 - acc: 0.9779 - val_loss: 0.0397 - val_acc: 0.9872
Epoch 5/12
60000/60000 [==============================] - 15s - loss: 0.0634 - acc: 0.9814 - val_loss: 0.0351 - val_acc: 0.9876
Epoch 6/12
60000/60000 [==============================] - 15s - loss: 0.0580 - acc: 0.9826 - val_loss: 0.0345 - val_acc: 0.9883
Epoch 7/12
60000/60000 [==============================] - 15s - loss: 0.0515 - acc: 0.9844 - val_loss: 0.0321 - val_acc: 0.9893
Epoch 8/12
60000/60000 [==============================] - 15s - loss: 0.0487 - acc: 0.9857 - val_loss: 0.0335 - val_acc: 0.9884
Epoch 9/12
60000/60000 [==============================] - 15s - loss: 0.0446 - acc: 0.9862 - val_loss: 0.0310 - val_acc: 0.9901
Epoch 10/12
60000/60000 [==============================] - 15s - loss: 0.0414 - acc: 0.9876 - val_loss: 0.0293 - val_acc: 0.9898
Epoch 11/12
60000/60000 [==============================] - 15s - loss: 0.0396 - acc: 0.9883 - val_loss: 0.0298 - val_acc: 0.9905
Epoch 12/12
60000/60000 [==============================] - 15s - loss: 0.0393 - acc: 0.9886 - val_loss: 0.0306 - val_acc: 0.9901
Test loss: 0.0306268027848
Test accuracy: 0.9901
In [ ]: