-
Notifications
You must be signed in to change notification settings - Fork 21
/
mnist_mlp.py
67 lines (56 loc) · 1.98 KB
/
mnist_mlp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# organize imports
import numpy as np
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Dropout
from keras.datasets import mnist
from keras.utils import np_utils
import tensorflowjs as tfjs
# fix a random seed for reproducibility
np.random.seed(9)
# user inputs
nb_epoch = 25
num_classes = 10
batch_size = 64
train_size = 60000
test_size = 10000
v_length = 784
model_save_path = "output"
# split the mnist data into train and test
(trainData, trainLabels), (testData, testLabels) = mnist.load_data()
# reshape and scale the data
trainData = trainData.reshape(train_size, v_length)
testData = testData.reshape(test_size, v_length)
trainData = trainData.astype("float32")
testData = testData.astype("float32")
trainData /= 255
testData /= 255
# convert class vectors to binary class matrices --> one-hot encoding
mTrainLabels = np_utils.to_categorical(trainLabels, num_classes)
mTestLabels = np_utils.to_categorical(testLabels, num_classes)
# create the MLP model
model = Sequential()
model.add(Dense(512, input_shape=(v_length,)))
model.add(Activation("relu"))
model.add(Dense(256))
model.add(Activation("relu"))
model.add(Dropout(0.2))
model.add(Dense(num_classes))
model.add(Activation("softmax"))
# compile the model
model.compile(loss="categorical_crossentropy",
optimizer="rmsprop",
metrics=["accuracy"])
# fit the model
history = model.fit(trainData,
mTrainLabels,
validation_data=(testData, mTestLabels),
batch_size=batch_size,
nb_epoch=nb_epoch,
verbose=2)
# evaluate the model
scores = model.evaluate(testData, mTestLabels, verbose=0)
# print the results
print ("[INFO] test score - {}".format(scores[0]))
print ("[INFO] test accuracy - {}".format(scores[1]))
# save tf.js specific files in model_save_path
tfjs.converters.save_keras_model(model, model_save_path)