1'''Trains a simple convnet on the MNIST dataset.
2
3Gets to 99.25% test accuracy after 12 epochs
4(there is still a lot of margin for parameter tuning).
516 seconds per epoch on a GRID K520 GPU.
6'''
7
8from __future__ import print_function
9import keras
10from keras.datasets import mnist
11from keras.models import Sequential
12from keras.layers import Dense, Dropout, Flatten
13from keras.layers import Conv2D, MaxPooling2D
14from keras import backend as K
15
16batch_size = 128
17num_classes = 10
18epochs = 12
19
20# input image dimensions
21img_rows, img_cols = 28, 28
22
23# the data, split between train and test sets
24(x_train, y_train), (x_test, y_test) = mnist.load_data()
25
26if K.image_data_format() == 'channels_first':
27    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
28    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
29    input_shape = (1, img_rows, img_cols)
30else:
31    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
32    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
33    input_shape = (img_rows, img_cols, 1)
34
35x_train = x_train.astype('float32')
36x_test = x_test.astype('float32')
37x_train /= 255
38x_test /= 255
39print('x_train shape:', x_train.shape)
40print(x_train.shape[0], 'train samples')
41print(x_test.shape[0], 'test samples')
42
43# convert class vectors to binary class matrices
44y_train = keras.utils.to_categorical(y_train, num_classes)
45y_test = keras.utils.to_categorical(y_test, num_classes)
46
47model = Sequential()
48model.add(Conv2D(32, kernel_size=(3, 3),
49                 activation='relu',
50                 input_shape=input_shape))
51model.add(Conv2D(64, (3, 3), activation='relu'))
52model.add(MaxPooling2D(pool_size=(2, 2)))
53model.add(Dropout(0.25))
54model.add(Flatten())
55model.add(Dense(128, activation='relu'))
56model.add(Dropout(0.5))
57model.add(Dense(num_classes, activation='softmax'))
58
59model.compile(loss=keras.losses.categorical_crossentropy,
60              optimizer=keras.optimizers.Adadelta(),
61              metrics=['accuracy'])
62
63model.fit(x_train, y_train,
64          batch_size=batch_size,
65          epochs=epochs,
66          verbose=1,
67          validation_data=(x_test, y_test))
68score = model.evaluate(x_test, y_test, verbose=0)
69print('Test loss:', score[0])
70print('Test accuracy:', score[1])
71