keras/examples/mnist_cnn.py

71 lines
2.3 KiB
Python
Raw Normal View History

2016-03-19 16:07:15 +00:00
'''Trains a simple convnet on the MNIST dataset.
2015-12-09 02:49:14 +00:00
2016-03-19 16:07:15 +00:00
Gets to 99.25% test accuracy after 12 epochs
(there is still a lot of margin for parameter tuning).
2015-12-09 02:49:14 +00:00
16 seconds per epoch on a GRID K520 GPU.
'''
2015-04-30 00:17:22 +00:00
from __future__ import print_function
import numpy as np
2015-07-26 08:00:18 +00:00
np.random.seed(1337) # for reproducibility
2017-02-11 02:16:11 +00:00
import keras
2015-04-30 00:17:22 +00:00
from keras.datasets import mnist
from keras.models import Sequential
2017-02-11 02:16:11 +00:00
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
2015-04-30 00:17:22 +00:00
2015-06-19 19:52:43 +00:00
batch_size = 128
2017-02-11 02:16:11 +00:00
num_classes = 10
num_epoch = 12
2015-05-04 17:31:03 +00:00
2015-10-05 01:44:49 +00:00
# input image dimensions
img_rows, img_cols = 28, 28
2016-04-04 18:30:24 +00:00
# the data, shuffled and split between train and test sets
2017-02-11 02:16:11 +00:00
(x_train, y_train), (x_test, y_test) = mnist.load_data()
2015-05-04 17:31:03 +00:00
if K.image_data_format() == 'channels_first':
2017-02-11 02:16:11 +00:00
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:
2017-02-11 02:16:11 +00:00
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)
2017-02-11 02:16:11 +00:00
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')
2015-04-30 00:17:22 +00:00
# convert class vectors to binary class matrices
2017-02-11 02:16:11 +00:00
y_train = keras.utils.np_utils.to_categorical(y_train, num_classes)
y_test = keras.utils.np_utils.to_categorical(y_test, num_classes)
2015-04-30 00:17:22 +00:00
model = Sequential()
2017-02-11 02:16:11 +00:00
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())
2017-02-11 02:16:11 +00:00
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
2017-02-11 02:16:11 +00:00
model.add(Dense(num_classes, activation='softmax'))
2015-04-30 00:17:22 +00:00
2017-02-11 02:16:11 +00:00
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adadelta(),
2016-03-19 16:07:15 +00:00
metrics=['accuracy'])
2015-04-30 00:17:22 +00:00
2017-02-11 02:16:11 +00:00
model.fit(x_train, y_train, batch_size=batch_size, num_epoch=num_epoch,
verbose=1, validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
2015-05-04 17:31:03 +00:00
print('Test accuracy:', score[1])