In [1]:
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
In [2]:
batch_size = 128
num_classes = 10
epochs = 12
img_rows, img_cols = 28,28
In [3]:
(X_Train, y_Train), (X_Test, y_Test) = mnist.load_data()
In [4]:
K.image_data_format()
Out[4]:
In [5]:
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)
In [6]:
X_Train = X_Train.astype('float32')
X_Test = X_Test.astype('float32')
X_Train /= 255
X_Test /= 255
In [7]:
y_Train = keras.utils.to_categorical(y_Train, num_classes)
y_Test = keras.utils.to_categorical(y_Test, num_classes)
In [8]:
model = Sequential()
model.add(Conv2D(32, (3,3), activation='elu', input_shape=(img_rows,img_cols,1)))
model.add(Conv2D(65, (3,3), activation='elu'))
model.add(MaxPooling2D((2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='elu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adam(),
metrics=['accuracy'])
In [9]:
model.fit(X_Train, y_Train,
batch_size=batch_size,
epochs=epochs,
verbose=2,
validation_data=(X_Test, y_Test))
Out[9]:
In [10]:
score = model.evaluate(X_Test, y_Test, verbose=0)
print("Test Loss:", score[0])
print("Test Accuracy:", score[1])
In [11]:
model_json = model.to_json()
with open("model.json","w") as json_file:
json_file.write(model_json)
model.save_weights("model.h5")
print("Saved model")
In [ ]: