-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
421 lines (369 loc) · 13.8 KB
/
main.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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
#! /bin/env python3
"""
* Neural Network Model Manager
* Fri Jun 04 20:38:14 CST 2021
* @Version 1.4
* @Auther ASjet
* @Email [email protected]
* @License GNU GPLv3
* @Copyright © 2021, ASjet
"""
import pickle
import shutil
import json
import os
from sys import meta_path
from cv import recognition
from nn import *
import web
__version__ = "1.4"
""" Changelog
@Version 1.4
add web command
@Version 1.3
add cam command
add shw command
@Version 1.2
fix bugs
optimize training options
Refactor whole project structure
Add train command
@Version 1.1
Fix bugs
Refactor functions
Add help
Refactor model path tree structure
Rename commands
Add mnt command
Add tst command
@Version 1.0
Add ls command
Add la command
Add sel command
Add chm command
"""
model_path = "model/"
cfg_name = "cfg.dat"
hpname_cnn = "hyperparameters_cnn.json"
hpname_mlp = "hyperparameters_mlp.json"
model_types = [
"mlp",
"cnn"
]
class Model(object):
def __init__(self, model_type, model_name, empty=False):
self.type = ""
self.name = ""
self.info = {}
self.models = []
if(not empty):
self.chtype(model_type)
self.chname(model_name)
def loadIndex(self):
with open(model_path+"index",'r') as f:
index = f.read().splitlines()
self.type = index[0]
if(len(index) == 2):
self.name = index[1]
def getModels(self):
self.models = []
with os.scandir(model_path + self.type) as model_folder:
for entry in model_folder:
if(os.path.exists(entry.path + "/info.json")):
self.models.append(entry.name)
def getInfo(self, model_name):
info = {}
with open(model_path + self.type + '/' + model_name + "/info.json") as f:
info = json.load(f)
return info
def chtype(self, model_type):
if(model_type in model_types):
self.type = model_type
self.name = ""
self.info = {}
self.getModels()
print("Model type changed to %s." % self.type)
save(self)
return True
else:
return False
def chname(self, id):
self.name = self.models[id]
self.info = self.getInfo(self.name)
print("Model changed to %s." % self.name)
save(self)
def rm(self, model_name):
shutil.rmtree(model_path+self.type+'/'+model_name)
print("Removed %s model %s." % (self.type, model_name))
if(model_name == self.name):
self.name = ""
self.info = {}
print("Currently using model had been removed.")
if(self.chkEmpty()):
self.printAll()
new_id = int(input("Please choose a new one:"))
if(self.chkID(new_id)):
self.chname(new_id)
save(self)
def printInfo(self):
if(self.chkEmpty()):
for key, value in self.info.items():
print(key, value, sep=': ')
def printAll(self):
self.getModels()
if(self.chkEmpty()):
if(self.type == "cnn"):
print(" ID|Accuracy|TrainSize|MBS|Epoch| Eta|Lambda| Mu|Layers")
for i, model in enumerate(self.models):
info = self.getInfo(model)
fmtstring = ('>' if model == self.name else ' ') + \
"%3d|%8d|%9d|%3d|%5d|%.6f|%.4f|%.1f|%s"
print(fmtstring % (i, info["Accuracy"], info["TrainSet_Size"], info["Mini_Batch_Size"],
info["Epoch"], info["Eta"], info["Lambda"], info["Mu"], info["Feature_Num"]))
print("Count: %d" % len(self.models))
return True
elif(self.type == "mlp"):
print(" ID|Accuracy|TrainSize|MBS|Epoch| Eta|Lambda| Mu|Layers")
for i, model in enumerate(self.models):
info = self.getInfo(model)
fmtstring = ('>' if model == self.name else ' ') + \
"%3d|%8d|%9d|%3d|%5d|%.6f|%.4f|%.1f|%s"
print(fmtstring % (i, info["Accuracy"], info["TrainSet_Size"], info["Mini_Batch_Size"],
info["Epoch"], info["Eta"], info["Lambda"], info["Mu"], info["Layer"]))
print("Count: %d" % len(self.models))
return True
return False
def chmodel(self):
model_type = input("Please select model type[mlp/cnn]:")
if(self.chtype(model_type)):
if(self.printAll()):
id = int(input("Choose one model[ID]:"))
if(self.chkID(id)):
self.chname(id)
else:
print('Please try again by typing "chm".')
def chkID(self, id):
if(id < 0 or id >= len(self.models)):
print('No such model ID "%d".' % id)
return False
else:
return True
def chkEmpty(self):
self.getModels()
if(len(self.models) == 0):
print("No model found.")
self.name = ""
self.info = {}
flag = input("Start by training?(y/N):")
if(flag == 'y'):
train(self.type)
self.getModels()
return True
return False
return True
def train(model_type):
if(model_type == "cnn"):
with open(model_path+hpname_cnn, 'r') as f:
hp = json.load(f)
# Dataset
print("Set hyperparameters to begin")
print("[0]Origin MNIST dataset.")
print("[1]Rotation-Expanded MNIST dataset.")
print("[2]Small dataset for test.(5000/1000)")
set_id = input("(1/9)Choose dataset[%d]:" % hp["dataset_id"])
if(set_id != ''):
hp["dataset_id"] = int(set_id)
# Mini-Batch size
mbs = input("(2/9)Mini-Batch size[%d]:" % hp["mini_batch_size"])
if(mbs != ''):
hp["mini_batch_size"] = int(mbs)
# Feature num
fn = input("(3/9)Feature Num%s:" % str(hp["feature_num"]))
if(fn != ''):
hp["feature_num"] = [int(f) for f in fn.split(' ')]
# Kernel1 size
ks1 = input("(4/9)First conv-layer kernel size%s:" %
str(hp["kernel_size1"]))
if(ks1 != ''):
hp["kernel_size1"] = [int(k) for k in ks1.split(' ')]
# Kernel2 size
ks2 = input("(5/9)Second conv-layer kernel size%s:" %
str(hp["kernel_size2"]))
if(ks2 != ''):
hp["kernel_size2"] = [int(k) for k in ks2.split(' ')]
# Epoch
epoch = input("(6/9)Epoch[%d]:" % hp["epoch"])
if(epoch != ''):
hp["epoch"] = int(epoch)
# Eta
eta = input("(7/9)Eta[%f]:" % hp["eta"])
if(eta != ''):
hp["eta"] = float(eta)
# Mu
mu = input("(8/9)Mu[%f]:" % hp["mu"])
if(mu != ''):
hp["mu"] = float(mu)
# Lambda
lmbda = input("(9/9)Lambda[%f]:" % hp["lmbda"])
if(lmbda != ''):
hp["lmbda"] = float(lmbda)
uid = train_cnn.train(hp, model_path)
elif(model_type == "mlp"):
with open(model_path+hpname_mlp, 'r') as f:
hp = json.load(f)
# Dataset
print("Set hyperparameters to begin")
print("[0]Origin MNIST dataset.")
print("[1]Rotation-Expanded MNIST dataset.")
print("[2]Small dataset for test.(5000/1000)")
set_id = input("(1/7)Choose dataset[%d]:" % hp["dataset_id"])
if(set_id != ''):
hp["dataset_id"] = int(set_id)
# Mini-Batch size
mbs = input("(2/7)Mini-Batch size[%d]:" % hp["mini_batch_size"])
if(mbs != ''):
hp["mini_batch_size"] = int(mbs)
# Layers
layer = input("(3/7)Layers[%s]:" % str(hp["layer"]))
if(layer != ''):
hp["layer"] = [int(l) for l in layer.split(' ')]
# Epoch
epoch = input("(4/7)Epoch[%d]:" % hp["epoch"])
if(epoch != ''):
hp["epoch"] = int(epoch)
# Eta
eta = input("(5/7)Eta[%f]:" % hp["eta"])
if(eta != ''):
hp["eta"] = float(eta)
# Mu
mu = input("(6/7)Mu[%f]:" % hp["mu"])
if(mu != ''):
hp["mu"] = float(mu)
# Lambda
lmbda = input("(7/7)Lambda[%f]:" % hp["lmbda"])
if(lmbda != ''):
hp["lmbda"] = float(lmbda)
uid = train_mlp.train(hp, model_path)
info = model.getInfo(uid)
for key, value in info.items():
print(key, value, sep=':')
def printHelp():
print("\nUsage:")
print(" command [options]")
print("\nCommands:")
print(" train\t\tTrain new model.")
print(" ls\t\tList information of currently selected model.")
print(" la\t\tList informations of all model.")
print(" rm [ID]\tRemove specified model. Currently using model will be removed when ignoring parameter.")
print(" sel [ID]\tSelect model to use by specifing model ID. Get all model information by ignoring parameter.")
print(" tst [ID]\tTest specified model by TestSet. Using currently using model when ignoring parameter.")
print(" mnt [ID]\tShow monitor curve of specified model. Show monitor of currently using model when ignoring parameter.")
print(" shw\t\tPrint model conv-kernel and convd images.")
print(" chm\t\tChange model type.")
print(" cam\t\tUsing camera to recognize handwritten digits.")
print(" web\t\tWatch camera frame through web stream.")
print(" type\t\tShow current model type.")
print(" exit\t\tExit manager and save data.")
print(" help\t\tShow help for commands.")
print(" version\tShow version.")
def printHello():
print("Neural Network Model Manager %s" % __version__)
print('Type "help" for more information.')
def save(model):
model.getModels()
with open(model_path+cfg_name, 'wb') as f:
f.write(pickle.dumps(model))
with open(model_path+"index", 'w') as f:
print(model.type, model.name, sep='\n', end='', file=f)
if __name__ == "__main__":
printHello()
while(True):
if(os.path.exists(model_path+cfg_name)):
with open(model_path+cfg_name, 'rb') as f:
model = pickle.load(f)
while(True):
cl = input("$ ")
if(cl):
cmd = cl.split(' ')
if(cmd[0] == "la"):
model.printAll()
elif(cmd[0] == "ls"):
model.printInfo()
elif(cmd[0] == "sel"):
if(len(cmd) == 1):
model.printAll()
id = int(input("Choose one model[ID]:"))
else:
id = int(cmd[1])
if(model.chkID(id)):
model.chname(id)
elif(cmd[0] == "mnt"):
if(len(cmd) == 1):
sel = model.name
else:
id = int(cmd[1])
if(model.chkID(id)):
sel = model.models[id]
else:
continue
print(sel)
path = model_path + model.type + '/'
monite.disp(path, sel)
elif(cmd[0] == "train"):
train(model.type)
save(model)
elif(cmd[0] == "rm"):
if(len(cmd) == 1):
sel = model.name
else:
id = int(cmd[1])
if(model.chkID(id)):
sel = model.models[id]
else:
continue
model.rm(sel)
elif(cmd[0] == "shw"):
if(model.type == "cnn"):
if(len(cmd) == 1):
sel = model.name
else:
id = int(cmd[1])
if(model.chkID(id)):
sel = model.models[id]
show_cnn.showKernel(sel)
show_cnn.showRes(sel)
elif(cmd[0] == "tst"):
if(len(cmd) == 1):
sel = model.name
else:
id = int(cmd[1])
if(model.chkID(id)):
sel = model.models[id]
else:
continue
print(sel)
hits, all = show_cnn.testNN(sel)
print("Accuracy on testset: %d / %d" % (hits, all))
elif(cmd[0] == "web"):
web.app.run(host='0.0.0.0')
elif(cmd[0] == "cam"):
recognition.camera()
elif(cmd[0] == "chm"):
model.chmodel()
elif(cmd[0] == "exit"):
save(model)
exit(0)
elif(cmd[0] == "type"):
print(model.type.upper())
elif(cmd[0] == "help"):
printHelp()
elif(cmd[0] == "version"):
printHello()
else:
print("Invalid input '%s' !" % cl)
printHelp()
else:
print("Configuration not found!")
model = Model("", "", True)
model.chmodel()
save(model)