In [ ]:
import numpy
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers.convolutional import MaxPooling2D
from keras.layers.convolutional import Conv2D
from keras.utils.np_utils import to_categorical
from keras.utils import np_utils
from keras import backend as K
K.set_image_dim_ordering('tf')
In [ ]:
# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
In [ ]:
# load the data - download in matlab format from:
# https://www.nist.gov/itl/iad/image-group/emnist-dataset
import scipy.io
mat = scipy.io.loadmat('../Dataset/emnist-letters.mat')
d = mat['dataset']
X_train = d[0,0]['train'][0,0]['images']
y_train = d[0,0]['train'][0,0]['labels']
X_test = d[0,0]['test'][0,0]['images']
y_test = d[0,0]['test'][0,0]['labels']
print(y_train.shape)
#(X_train, y_train), (X_test, y_test) = mnist.load_data()
# reshape to be [samples][pixels][width][height]
X_train = X_train.reshape(X_train.shape[0], 28,28,1).astype('float32')
X_test = X_test.reshape(X_test.shape[0], 28,28,1).astype('float32')
print(X_train.shape)
In [ ]:
# normalize inputs from 0-255 to 0-1
X_train = X_train / 255
X_test = X_test / 255
# one hot encode outputs
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]
In [ ]:
def baseline_model():
model = Sequential()
model.add(Conv2D(30, (5, 5), padding='valid', input_shape=(28,28,1), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(15, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(50, activation='relu'))
model.add(Dense(num_classes, activation='softmax')) # softmax
# Compile model
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
return model
In [ ]:
# build the model
model = baseline_model()
# Fit the model
model.fit(X_train, y_train,
validation_split=.1,
epochs=12,
batch_size=200,
verbose=True)
# Final evaluation of the model
scores = model.evaluate(X_test, y_test, verbose=0)
print("Baseline Error: %.2f%%" % (100-scores[1]*100))
In [ ]:
import coremltools
coreml_model = coremltools.converters.keras.convert(model, input_names = ['imageAlpha'], output_names = ['letterConfidence'])
coreml_model.author = 'Kate Bonnen and Conrad Stoll'
coreml_model.license = 'MIT'
coreml_model.short_description = "Recognize the hand-drawn letter from an input image."
coreml_model.input_description['imageAlpha'] = 'The input image alpha values, from top down, left to right.'
coreml_model.output_description['letterConfidence'] = 'Confidence for each letter ranging from index 1 to 26. Ignore index 0.'
coreml_model.save('../Models/letters_keras.mlmodel')
In [ ]:
In [ ]: