/
train_mnist_keras.py
204 lines (155 loc) · 7.36 KB
/
train_mnist_keras.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
"""
This example is based on keras's mnist_mlp.py and mnist_cnn.py
Trains a simple deep NN on the MNIST dataset.
"""
import argparse
import json
import os
import keras
from webdnn.backend import generate_descriptor, backend_names
from webdnn.frontend.keras import KerasConverter
batch_size = 128
num_classes = 10
epochs = 2
img_rows, img_cols = 28, 28
def get_input_shape(model_type):
if model_type in ["conv", "dilated_conv", "residual", "complex"]:
return img_rows, img_cols, 1
elif model_type == "fc":
return img_rows * img_cols,
else:
raise NotImplementedError("Unknown model type")
def _setup_model(model_type):
from keras import backend as K
from keras.layers import Dense, Dropout, Flatten, Conv2D, AtrousConv2D, MaxPooling2D, Input, add, GlobalAveragePooling2D, Activation
from keras.models import Sequential, Model
input_shape = get_input_shape(model_type)
if model_type == "conv":
model = Sequential()
model.add(Conv2D(8, kernel_size=(3, 3), activation="relu", input_shape=input_shape))
model.add(Conv2D(16, (3, 3), activation="relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(32, activation="relu"))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation="softmax"))
elif model_type == "dilated_conv":
model = Sequential()
model.add(AtrousConv2D(8, kernel_size=(3, 3), atrous_rate=(2, 2), activation="relu", input_shape=input_shape)) # shape is 5x5
model.add(AtrousConv2D(16, kernel_size=(3, 3), atrous_rate=(3, 3), activation="relu")) # shape is 7x7
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(32, activation="relu"))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation="softmax"))
elif model_type == "fc":
model = Sequential()
model.add(Dense(512, activation="hard_sigmoid", input_shape=(784,)))
model.add(Dropout(0.2))
model.add(Dense(512, activation="relu"))
model.add(Dropout(0.2))
model.add(Dense(10, activation="softmax"))
elif model_type == "residual":
nn_input = Input(shape=(28, 28, 1))
hidden = Conv2D(8, kernel_size=(3, 3), activation="relu")(nn_input)
hidden = MaxPooling2D(pool_size=(2, 2))(hidden)
hidden_1 = Conv2D(16, kernel_size=(1, 1), activation="relu", padding="same")(hidden)
hidden_2 = Conv2D(16, kernel_size=(3, 3), activation="relu", padding="same")(hidden)
hidden = add([hidden_1, hidden_2])
hidden_1 = hidden
hidden_2 = Conv2D(16, kernel_size=(3, 3), activation="relu", padding="same")(hidden)
hidden = add([hidden_1, hidden_2])
hidden = GlobalAveragePooling2D()(hidden)
nn_output = Dense(num_classes, activation="softmax")(hidden)
model = Model(inputs=[nn_input], outputs=[nn_output])
elif model_type == "complex":
# graph which has graph and sequential
# this is for testing converting complex model
nn_input = Input(shape=(28, 28, 1))
hidden_1 = Conv2D(8, kernel_size=(3, 3), activation="relu")(nn_input)
submodel_input = Input(shape=(26, 26, 8))
submodel_conv = Conv2D(8, kernel_size=(3, 3), activation="relu")
submodel_1 = submodel_conv(submodel_input)
submodel_2 = submodel_conv(submodel_1) # use same layer multiple times
submodel_3 = Conv2D(16, kernel_size=(3, 3), activation="relu")(submodel_1)
submodel = Model(inputs=[submodel_input], outputs=[submodel_3, submodel_2])
subseq = Sequential()
subseq.add(Conv2D(16, kernel_size=(3, 3), activation="relu", input_shape=(22, 22, 16)))
subseq.add(Flatten())
subseq.add(Dense(10))
hidden_2, hidden_3 = submodel(hidden_1)
hidden_4 = subseq(hidden_2)
hidden_5 = Flatten()(hidden_3)
hidden_6 = Dense(10)(hidden_5)
hidden_sum = add([hidden_4, hidden_6])
nn_output = Activation(activation="softmax")(hidden_sum)
model = Model(inputs=[nn_input], outputs=[nn_output])
else:
raise NotImplementedError("Unknown model type")
print(f"input shape: {input_shape}, data_format: {K.image_data_format()}")
return model
def _train_and_save(model_type, model_path, sample_path):
import keras
from keras import backend as K
from keras.datasets import mnist
from keras.optimizers import RMSprop
(x_train, y_train), (x_test, y_test) = mnist.load_data()
if model_type in ["conv", "dilated_conv", "residual", "complex"]:
if K.image_data_format() == "channels_first":
raise NotImplementedError("Currently, WebDNN converter does not data_format==channels_first")
else:
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)
elif model_type == "fc":
x_train = x_train.reshape(x_train.shape[0], img_rows * img_cols)
x_test = x_test.reshape(x_test.shape[0], img_rows * img_cols)
else:
raise NotImplementedError("Unknown model type")
x_train = x_train.astype("float32")
x_test = x_test.astype("float32")
x_train /= 255
x_test /= 255
print(x_train.shape[0], "train_and_save samples")
print(x_test.shape[0], "test samples")
# convert class vectors to binary class matrices
y_test_orig = y_test # for exporting test sample
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
model = _setup_model(model_type)
model.summary()
model.compile(loss="categorical_crossentropy", optimizer=RMSprop(), metrics=["accuracy"])
model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print("Test loss:", score[0])
print("Test accuracy:", score[1])
print("Saving trained model")
os.makedirs(os.path.dirname(model_path), exist_ok=True)
model.save(model_path)
print("Exporting test samples (for demo purpose)")
test_samples_json = []
for i in range(10):
test_samples_json.append({"x": x_test[i].flatten().tolist(), "y": int(y_test_orig[i])})
with open(sample_path, "w") as f:
json.dump(test_samples_json, f)
def generate_graph(model_type, output_dir):
model_path = os.path.join(output_dir, f"./keras_model/{model_type}.h5")
sample_path = os.path.join(output_dir, "test_samples.json")
if not os.path.exists(model_path):
_train_and_save(model_type, model_path, sample_path)
model = keras.models.load_model(model_path, compile=False)
graph = KerasConverter(batch_size=1).convert(model)
return model, graph
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--model", default="fc", choices=["fc", "conv", "dilated_conv", "residual", "complex"])
parser.add_argument("--out", default="output_keras")
parser.add_argument("--backend", default=",".join(backend_names))
args = parser.parse_args()
model, graph = generate_graph(args.model, args.out)
for backend in args.backend.split(","):
exec_info = generate_descriptor(backend, graph)
exec_info.save(args.out)
if __name__ == "__main__":
main()