-
Notifications
You must be signed in to change notification settings - Fork 0
/
retrainModule.py
1166 lines (1077 loc) · 51 KB
/
retrainModule.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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright (c) University of Luxembourg 2019-2020.
# Created by Hazem FAHMY, [email protected], SNT, 2019.
# Modified by Mojtaba Bagherzadeh, [email protected], University of Ottawa, 2019.
#
import testModule
from imports import setupTransformer, os, Image, Variable, argparse, datasets, torch, pd, np, isfile, basename, join
import dataSupplier as dataSupply
#import testModule
#import dnnModels
#import ieepredict
from imports import sys, torch, nn, optim, Variable, np, shutil, os, time, datasets, math, pd, PathImageFolder, \
setupTransformer, exists, join, isfile, isdir, basename, dirname
from dataSupplier import DataSupplier
from imports import np, optim, torch, Variable, math
import time
learning_rate = 0.001
momentum = 0.9
log_schedule = 10
nPoints = 64
def run(caseFile_):
global caseFile
global expIndex
global BaggedUnsafeSet
caseFile = caseFile_
caseFile["DNNsPath"] = join(caseFile["outputPathOriginal"], caseFile["RCC"], "DNNModels_")
caseFile[caseFile["retrainMode"]] = {}
start = time.time()
if caseFile_["Alex"]:
avgImp, maxImp, minImp, avgWor, maxWor, minWor, avgTestSet, DNNModels, dumbDict, clusterDict = retrainAlex()
if caseFile_["KP"]:
#avgImp, maxImp, minImp, avgWor, maxWor, minWor, avgTestSet, DNNModels, dumbDict, clusterDict = retrainKP()
retrainKP()
caseFile[caseFile["retrainMode"]]["failCount"] = caseFile[caseFile["retrainMode"]]["totalFailCount"] = 0
if "retrieveAccuracy" not in caseFile:
failCount = caseFile[caseFile["retrainMode"]]["failCount"] / (caseFile["expNum2"]-caseFile["expNum1"]+1)
failCount_ = 100.00 * (failCount / BaggedUnsafeSet)
totalFailCount = caseFile[caseFile["retrainMode"]]["totalFailCount"] / (caseFile["expNum2"]-caseFile["expNum1"]+1)
totalFailCount_ = 100.00 * (totalFailCount / BaggedUnsafeSet)
else:
dumbDict = torch.load(join(DNNModels, caseFile["retrainMode"] + "_resultDict.pt"))
failCount = dumbDict["failCount"]
failCount_ = dumbDict["fail%"]
caseFile[caseFile["retrainMode"]]["AvgImproved"] = avgImp
caseFile[caseFile["retrainMode"]]["MaxImproved"] = maxImp
caseFile[caseFile["retrainMode"]]["MinImproved"] = minImp
caseFile[caseFile["retrainMode"]]["AvgWorsened"] = avgWor
caseFile[caseFile["retrainMode"]]["MaxWorsened"] = maxWor
caseFile[caseFile["retrainMode"]]["MinWorsened"] = minWor
caseFile[caseFile["retrainMode"]]["AvgTestAccuracy"] = avgTestSet
caseFile[caseFile["retrainMode"]]["failCount"] = failCount
caseFile[caseFile["retrainMode"]]["totalFailCount"] = totalFailCount
print(caseFile["retrainMode"], str(caseFile["expNum2"]-caseFile["expNum1"]+1) + " exp.", str(avgTestSet) + "%")
print("Improved (avg/min/max):", str(avgImp) + "/" + str(minImp) + "/" + str(maxImp))
print("Worsened (avg/min/max):", str(avgWor) + "/" + str(minWor) + "/" + str(maxWor))
#print("Failing% (avg):", str(failCount_))
#print("Total Failing% (avg):", str(totalFailCount_))
clsWithAssImages = torch.load(caseFile["clsPath"])
for clusterID in clusterDict:
if clusterID in clsWithAssImages['clusters']:
clusterDict[clusterID]["Imp"] /= (caseFile["expNum2"]-caseFile["expNum1"]+1)
clusterDict[clusterID]["Imp"] /= len(clsWithAssImages['clusters'][clusterID]['members'])
clusterDict[clusterID]["Imp"] *= 100.00
clusterDict[clusterID]["Wor"] /= (caseFile["expNum2"]-caseFile["expNum1"]+1)
clusterDict[clusterID]["Wor"] /= len(clsWithAssImages['clusters'][clusterID]['members'])
clusterDict[clusterID]["Wor"] *= 100.00
#print("Avg % of Improved Images per Cluster:")
avgImpPerCls = list()
for i in range(1, len(clusterDict)+1):
#print(i, str(clusterDict[i]["Imp"])[0:5])
avgImpPerCls.append(clusterDict[i]["Imp"])
#print("Avg % of Improved Images per Cluster:", sum(avgImpPerCls)/len(avgImpPerCls))
dumbDict["Improved"] = str(avgImp) + "/" + str(minImp) + "/" + str(maxImp)
dumbDict["Worsened"] = str(avgWor) + "/" + str(minWor) + "/" + str(maxWor)
dumbDict["AvgTestAccuracy"] = avgTestSet
dumbDict["failCount"] = failCount
dumbDict["fail%"] = failCount_
torch.save(dumbDict, join(DNNModels, caseFile["retrainMode"] + "_resultDict.pt"))
torch.save(caseFile, caseFile["caseFile"])
newName = str(caseFile["retrainMode"]) + "_" + str(caseFile[caseFile["retrainMode"]]["AvgTestAccuracy"])[0:6]
oldPath = caseFile["DNNsPath"] + str(caseFile["retrainMode"]) + "_" + expIndex
newPath = caseFile["DNNsPath"] + newName
if "retrieveAccuracy" not in caseFile:
shutil.copytree(oldPath, newPath)
shutil.rmtree(oldPath)
torch.save(caseFile, join(newPath, "caseFile.pt"))
print("Total time of batch job is " + str((time.time() - start) / 60.0) + " minutes.")
print("*****************************")
print("*****************************")
print("*****************************")
def retrainKP():
expNumber = caseFile["expNum1"]
expNumber2 = caseFile["expNum2"]
outputPathOriginal = caseFile["outputPathOriginal"]
retrainMode = caseFile["retrainMode"]
batchSize = caseFile["batchSize"]
Epochs = caseFile["Epochs"]
components = caseFile["components"]
modelsPath = join(outputPathOriginal, "DNNModels")
realDataNpy = caseFile["realDataNpy"]
testDataNpy = caseFile["testDataNpy"]
accuList = list()
#if "retrainSet" in caseFile:
# outputSet = join(outputPathOriginal, caseFile["retrainSet"])
#else:
# outputSet = join(outputPathOriginal, str(retrainMode) + str(0) + ".npy")
#dataSupply.loadIEETrainData(caseFile, outputSet)
if "expIndex" not in caseFile:
expIndex = str(int(np.random.randint(100, 100000)))
else:
expIndex = caseFile["expIndex"]
expDir = join(modelsPath, str(retrainMode) + "_" + expIndex)
if not exists(expDir):
os.makedirs(expDir)
errPath = join(caseFile["outputPathOriginal"], "errList.pt")
if exists(errPath):
errList = torch.load(errPath)
else:
improvePredict = predict.IEEPredictor(caseFile["improveDataNpy"], caseFile["modelPath"], 0)
dst2 = join(caseFile["outputPathOriginal"], "improveerror")
improveDataSet, _ = improvePredict.load_data(caseFile["improveDataNpy"])
_, errList = improvePredict.predict(improveDataSet, dst2, caseFile["improveDataPath"], True,
caseFile["improveCSV"], 1, False)
torch.save(errList, errPath)
model = testModule.loadDNN(caseFile["modelPath"], "KPNet", None, False)
model.eval()
for exp in range(expNumber, expNumber2 + 1):
DNN = loadDNN(caseFile, None)
outputModel = join(modelsPath, str(retrainMode) + str(exp) + "_kpmodel.pt")
outputLoss = join(modelsPath, str(retrainMode) + str(exp) + "_loss.npy")
if "retrainSet" in caseFile:
outputSet = join(outputPathOriginal, caseFile["retrainSet"])
else:
outputSet = join(outputPathOriginal, str(retrainMode) + str(exp) + ".npy")
dataSupply.loadIEETrainData(caseFile, outputSet, errList)
trainer = Trainer(outputSet, testDataNpy, realDataNpy, batchSize, False, 0, 0, 0
, False, True, True, 0, outputModel, outputLoss, DNN, Epochs)
trainer.train()
print("Using model:", outputModel)
predictor = predict.IEEPredictor(outputSet, outputModel, 0)
trainDataSet, _ = predictor.load_data(outputSet)
predictor2 = predict.IEEPredictor(testDataNpy, outputModel, 0)
testDataSet, _ = predictor.load_data(testDataNpy)
outputTrainCSV = join(outputPathOriginal,
retrainMode + str(exp) + "_trainResult.csv")
outputTestCSV = join(outputPathOriginal,
retrainMode + str(exp) + "_testResult.csv")
dst = join(outputPathOriginal, "trainerror")
dst2 = join(outputPathOriginal, "testerror")
#counter = predictor.predict(trainDataSet, dst, None, True, outputTrainCSV, 1, False)
predictor2.model = dnnModels.KPNet()
if torch.cuda.is_available():
weights = torch.load(outputModel, map_location=torch.device('cuda:0'))
else:
weights = torch.load(outputModel, map_location=torch.device('cpu'))
predictor2.model.load_state_dict(weights.state_dict())
counter2 = predictor2.predict(testDataSet, dst2, None, True, outputTestCSV, 0, False)
imageList = pd.read_csv(outputTrainCSV)
imageList2 = pd.read_csv(outputTestCSV)
dictResult = {}
cntTot = 0
cntMC = 0
for component in components:
cntComp = 0
cntTot = 0
cntMC = 0
for index, row in imageList.iterrows():
cntTot += 1
if row["result"] == "Wrong":
cntMC += 1
if row["worst_component"] == component:
cntComp += 1
dictResult[component] = cntComp
accuList.append(cntMC / cntTot)
testAccuracy = 100.0*((1 - cntMC) / cntTot)
if "retrainSet" not in caseFile:
shutil.move(outputSet, join(expDir, str(retrainMode) + str(exp) + "_" +
str(testAccuracy)[0:6] + ".npy"))
shutil.move(outputModel, join(expDir, str(retrainMode) + str(exp) + "_" +
str(testAccuracy)[0:6] + "_kpmodel.pt"))
shutil.move(outputLoss, join(expDir, str(retrainMode) + str(exp) + "_" +
str(testAccuracy)[0:6] + "_loss.npy"))
return
def retrainAlex():
global caseFile, eta, etaT, expIndex, BaggedUnsafeSet
if caseFile["retrainMode"] != "SEDE":
clusterUCs, totalAssigned, totalUc, totalUb, Ub = dataSupply.getUCs(caseFile, 0.3) #U4/U5
print("Total Assigned Images:", totalAssigned)
print("US:", math.ceil(totalUc))
print("BLUS:", math.ceil(totalUb))
BaggedUnsafeSet = math.ceil(totalUb)
retrainMode = caseFile["retrainMode"]
if "retrieveAccuracy" in caseFile:
retrieveAccuracy = caseFile["retrieveAccuracy"]
newName = str(retrainMode) + "_" + str(caseFile["retrieveAccuracy"])
DNNModels = caseFile["DNNsPath"] + newName
else:
retrieveAccuracy = None
if "expIndex" not in caseFile:
expIndex = str(int(np.random.randint(100, 100000)))
else:
expIndex = caseFile["expIndex"]
DNNModels = join(caseFile["filesPath"], "DNNModels_" + retrainMode + "_" + expIndex)
eta = etaT = "N/A"
outputPath = caseFile["outputPath"]
modelPath = caseFile["modelPath"]
epochNum = caseFile["Epochs"]
datasetName = caseFile["datasetName"]
expNum = caseFile["expNum1"]
expNum2 = caseFile["expNum2"]
clsPath = caseFile["assignPTFile"]
DataSets = join(outputPath, "DataSets")
testSet = join(DataSets, "TestSet")
if not exists(DNNModels):
os.makedirs(DNNModels)
imgClasses = caseFile["trainDataSet"].dataset.classes
imageList = pd.read_csv(caseFile["testCSV"], names=["image", "result", "expected", "predicted"].append(imgClasses))
cnt1 = 0
resultDict = {}
for index, row in imageList.iterrows():
imagePath = row["image"]
cnt1 += 1
resultDict[imagePath] = {}
resultDict[imagePath]["Old"] = row["result"]
if retrainMode != "SEDE":
clsWithAssImages = torch.load(clsPath)
clusterDistrib = list()
clusterDict = {}
for clusterID in clsWithAssImages['clusters']:
clusterDict[clusterID] = {}
clusterDict[clusterID]["Imp"] = clusterDict[clusterID]["Wor"] = 0
if 'assigned' in clsWithAssImages['clusters'][clusterID]:
clustLen = len(clsWithAssImages['clusters'][clusterID]['assigned'])
if clustLen > 0:
clusterDistrib.append(clustLen)
print("UnsafeSet Distribution", clusterDistrib)
print("Total:", sum(clusterDistrib))
#print("Avg:", sum(clusterDistrib) / len(clusterDistrib))
print("Total Clusters:", len(clsWithAssImages['clusters']))
print("Assigned Clusters:", len(clusterDistrib))
print("UnsafeSet Size:", math.ceil(totalUb))
caseFile[retrainMode]["BaggedUnsafeSetSize"] = math.ceil(totalUb)
print("RetrainMode:", retrainMode)
ts = datasets.ImageFolder(root=caseFile["trainDataPath"], transform=setupTransformer(datasetName))
print("TrainingSet Size:", len(ts))
caseFile[retrainMode]["failCount"] = caseFile[retrainMode]["totalFailCount"] = caseFile[retrainMode]["dupCount"] = 0
#if retrainMode == "HUDD":
# bagPath = join(caseFile["filesPath"], "DataSets", retrainMode + "_" + str(expIndex) + "_toBag/")
# ts2, imagesList, caseFile = dataSupply.loadTrainData(bagPath, caseFile) # UnsafeSet
test = test2 = improvedList = worsenedList = improvedClustersList = list()
expCounter = x = loadBar = 0
dumbDict = {}
numExps = expNum2 + 1 - expNum
start = time.time()
for exp in range(expNum, expNum2 + 1):
bestModelPath = join(DNNModels, retrainMode + "_" + str(exp) + "." +
str(basename(modelPath).split(".")[1]))
if not (retrieveAccuracy is None):
#DNN = loadDNN(caseFile, bestModelPath)
for b in os.listdir(DNNModels):
if b.startswith(join(retrainMode + "_" + str(exp))):
bestModelPath = join(DNNModels, b)
else:
DNN = loadDNN(caseFile, None)
tsList = list()
randomID = int(np.random.randint(100, 100000))
#randomID = 70382
bagPath = join(caseFile["filesPath"], "DataSets",
retrainMode + "_" + str(randomID) + "_toBag/")
print(bagPath)
if "retrainSet" in caseFile:
dumbDict = torch.load(join(caseFile["DNNsPath"] + str(retrainMode) + "_" +
str(caseFile["retrainSet"]).split("_")[1], caseFile["retrainMode"]
+ "_resultDict.pt"))
imagesList = dumbDict["UnsafeSet_" + str(caseFile["retrainSet"]).split("_")[0]]
ts2, imagesList, caseFile = dataSupply.loadTrainData(bagPath, caseFile, imagesList)
else:
ts2, imagesList, caseFile = dataSupply.loadTrainData(bagPath, caseFile, None) # UnsafeSet
dumbDict["UnsafeSet_" + retrainMode + str(exp)] = imagesList
tsList.append(ts)
tsList.append(ts2)
concatList = torch.utils.data.ConcatDataset(tsList)
newTrainDataSet = torch.utils.data.DataLoader(concatList, batch_size=caseFile["batchSize"], shuffle=True,
num_workers=caseFile["workersCount"])
_, DNN = alexTrain(caseFile, epochNum, newTrainDataSet, bestModelPath, DNN, None)
#shutil.rmtree(bagPath)
DNN = loadDNN(caseFile, bestModelPath)
testAccuracy, resultDictNew = alexTest(bestModelPath, testSet, resultDict, datasetName, DNN, False, None)
print("R:",testAccuracy.item())
test.append(testAccuracy.item())
testAccuracy, resultDictNew = alexTest(bestModelPath, testSet+"_R", resultDict, datasetName, DNN, False, None)
print("S:",testAccuracy.item())
bagPath = join(caseFile["filesPath"], "DataSets", retrainMode + "_" +
str(int(np.random.randint(100, 100000))) + "_toBag/")
#dataSupply.generateTestSet(caseFile, bagPath)
#tsList2 = list()
#ts3 = PathImageFolder(root=bagPath, transform=setupTransformer(datasetName))
#ts4 = PathImageFolder(root=caseFile["testDataPath"], transform=setupTransformer(datasetName))
#tsList2.append(ts3)
#tsList2.append(ts4)
#concatList = torch.utils.data.ConcatDataset(tsList2)
#newTestDataSet = torch.utils.data.DataLoader(concatList, batch_size=caseFile["batchSize"], shuffle=True,
# num_workers=caseFile["workersCount"])
#testAccuracy2, _ = alexTest(bestModelPath, newTestDataSet, None, datasetName, DNN, False, None)
#test2.append(testAccuracy2.item())
#print(testAccuracy2.item())
shutil.rmtree(bagPath)
improvedImages, worsenedImages, clusterDict = collectImprovedData(resultDictNew, clusterDict)
improvedList.append(improvedImages)
worsenedList.append(worsenedImages)
expCounter += 1
x += 1
if int(x / (numExps * 0.1)) == 1:
loadBar += 10.0
spentTime = ((time.time() - start) / 60.0)
timePerLoadBar = spentTime/loadBar
spentTime = timePerLoadBar * loadBar
fullTime = timePerLoadBar * 100
remTime = math.ceil(fullTime - spentTime)
if remTime > 60:
etaT = str(remTime/60)[0:4] + "hs."
else:
etaT = str(remTime) + " mins."
x = 0
eta = str(int(100.0 * exp / (numExps)))
if retrieveAccuracy is None:
shutil.move(join(DNNModels, retrainMode + "_" + str(exp) + "." +
str(basename(modelPath).split(".")[1])),
join(DNNModels, retrainMode + "_" + str(exp) + "_" + str(testAccuracy.item())[0:6] +
"." + str(basename(modelPath).split(".")[1])))
print(test)
print(sum(test)/len(test))
print(test2)
print(sum(test2)/len(test2))
return sum(improvedList) / len(improvedList), max(improvedList), min(improvedList), \
sum(worsenedList) / len(worsenedList), max(worsenedList), min(worsenedList), sum(test)/len(test), \
DNNModels, dumbDict, clusterDict
def loadAlexRetrainDataSet():
return
def updateCaseFile():
return
def collectImprovedData(resultDictNew, clusterDict):
global clsWithAssImages
global caseFile
clsWithAssImages = torch.load(caseFile["clsPath"])
worsenedImages = 0
improvedImages = 0
for img in resultDictNew:
if resultDictNew[img]["Old"] == "Correct":
if resultDictNew[img]["New"] == "Wrong":
worsenedImages += 1
if resultDictNew[img]["Old"] == "Wrong":
if resultDictNew[img]["New"] == "Correct":
imgClass = basename(dirname(img))
imgName = "Test_" + str(basename(img)).split(".")[0] + "_" + imgClass
improvedImages += 1
for clusterID in clsWithAssImages['clusters']:
if clsWithAssImages['clusters'][clusterID]['members'].count(imgName) > 0:
clusterDict[clusterID]["Imp"] += 1
for clusterID in clusterDict:
print(clusterID, clusterDict[clusterID]["Imp"])
print("Worsened:", worsenedImages)
return improvedImages, worsenedImages, clusterDict
def writeFile(textPath, input, text):
file = open(textPath, "a")
if text is not None:
file.write(text + "\n")
for i in input:
file.write(str(i) + "\n")
file.close()
def loadDNN(caseFile, modelPath):
if modelPath is None:
modelPath = caseFile["modelPath"]
Alex = caseFile["Alex"]
KP = caseFile["KP"]
datasetName = caseFile["datasetName"]
numClass = caseFile["numClass"]
scratchFlag = caseFile["scratchFlag"]
if Alex:
if datasetName.startswith("HPD"):
net = dnnModels.AlexNetIEE(numClass)
else:
net = dnnModels.AlexNet(numClass)
elif KP:
net = dnnModels.KPNet()
if torch.cuda.is_available():
if not scratchFlag:
weights = torch.load(modelPath)
if Alex:
net.load_state_dict(weights)
elif KP:
net.load_state_dict(weights.state_dict())
net = net.to('cuda')
net.cuda()
net.eval()
DNN = net
else:
if not scratchFlag:
weights = torch.load(modelPath, map_location=torch.device('cpu'))
if Alex:
net.load_state_dict(weights)
elif KP:
net.load_state_dict(weights.state_dict())
net.eval()
DNN = net
return DNN
def alexTrain(caseFile, epochNum, trainData, bestModelPath, net, validationSet):
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=learning_rate, momentum=momentum, weight_decay=5e-4)
best_loss = 0
x = 0
ETA1 = 0
ETA2 = 0
x = 0
trainAccuracy = list()
print(len(trainData.dataset))
torch.save(net.state_dict(), bestModelPath)
for i in range(1, epochNum + 1):
totalCounter = 0
start1 = time.time()
correct = 0
net.train()
# print(trainData)
retrainLength = len(trainData)
for b_idx, (data, classes) in enumerate(trainData):
start1 = time.time()
totalCounter += 1
if torch.cuda.is_available():
net.cuda()
data, classes = data.cuda(), classes.cuda()
else:
data = data.cpu()
classes = classes.cpu()
data, classes = Variable(data), Variable(classes)
optimizer.zero_grad()
scores = net.forward(data)
scores = scores.view(data.size()[0], caseFile["numClass"])
_, prediction = torch.max(scores.data, 1)
correct += torch.sum(prediction == classes.data).float()
loss = criterion(scores, classes)
loss.backward()
optimizer.step()
# if b_idx % log_schedule == 0:
# print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
# i, (b_idx + 1) * len(data), len(trainData.dataset),
# 100. * (b_idx + 1) * len(data) / len(trainData.dataset), loss.item()), end="\r")
if x == 0:
end = time.time()
ETA1 = int((((end - start1) / 60.0) * retrainLength))
ETA2 = int((ETA1 * epochNum))
x += 1
#if eta is not None:
# print("Checked:", str(totalCounter) + "/" + str(retrainLength) + " " +
# str(int(100.0 * totalCounter / retrainLength)) + "%",
# str(int(100.0 * i / epochNum)) + "%",
# eta + "%", "ETA:" + str(etaT), end="\r")
#else:
print("Checked:", str(totalCounter) + "/" + str(retrainLength) + " " +
str(int(100.0 * totalCounter / retrainLength)) + "%",
str(int(100.0 * i / epochNum)) + "%", end="\r")
print(i)
if validationSet is None:
avg_loss = correct / len(trainData.dataset) * 100
else:
avg_loss, _ = alexTest(bestModelPath, validationSet, None, caseFile["datasetName"], net, False, None)
print("loss:", avg_loss)
if (avg_loss > best_loss):
torch.save(net.state_dict(), bestModelPath)
best_loss = avg_loss
dataTransform = setupTransformer(caseFile["datasetName"])
transformedData2 = PathImageFolder(root=caseFile["testDataPath"] , transform=dataTransform)
testData2 = torch.utils.data.DataLoader(transformedData2, batch_size=caseFile["batchSize"], shuffle=True,
num_workers=caseFile["workersCount"])
testAccuracy2, resultDictNew = alexTest(bestModelPath, testData2, None, caseFile["datasetName"],
net, False, None)
print(testAccuracy2.item())
# print("training accuracy ({:.2f}%)".format(avg_loss))
trainAccuracy.append(avg_loss)
return trainAccuracy, net
def alexTrain_Original(caseFile, epochNum, trainData, bestModelPath, net, validationSet):
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=learning_rate, momentum=momentum, weight_decay=5e-4)
best_loss = 0
x = 0
ETA1 = 0
ETA2 = 0
bestNet = net
best_t_loss = 0
test_loss = 0
x = 0
trainAccuracy = list()
print(len(trainData.dataset))
torch.save(net.state_dict(), bestModelPath)
for i in range(1, epochNum + 1):
totalCounter = 0
start1 = time.time()
correct = 0
bestNet.train()
# print(trainData)
retrainLength = len(trainData)
for b_idx, (data, classes) in enumerate(trainData):
start1 = time.time()
totalCounter += 1
if torch.cuda.is_available():
bestNet.cuda()
data, classes = data.cuda(), classes.cuda()
else:
data = data.cpu()
classes = classes.cpu()
data, classes = Variable(data), Variable(classes)
optimizer.zero_grad()
scores = bestNet.forward(data)
scores = scores.view(data.size()[0], caseFile["numClass"])
_, prediction = torch.max(scores.data, 1)
correct += torch.sum(prediction == classes.data).float()
loss = criterion(scores, classes)
loss.backward()
optimizer.step()
# if b_idx % log_schedule == 0:
# print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
# i, (b_idx + 1) * len(data), len(trainData.dataset),
# 100. * (b_idx + 1) * len(data) / len(trainData.dataset), loss.item()), end="\r")
if x == 0:
end = time.time()
ETA1 = int((((end - start1) / 60.0) * retrainLength))
ETA2 = int((ETA1 * epochNum))
x += 1
#if eta is not None:
# print("Checked:", str(totalCounter) + "/" + str(retrainLength) + " " +
# str(int(100.0 * totalCounter / retrainLength)) + "%",
# str(int(100.0 * i / epochNum)) + "%",
# eta + "%", "ETA:" + str(etaT), end="\r")
#else:
print("Checked:", str(totalCounter) + "/" + str(retrainLength) + " " +
str(int(100.0 * totalCounter / retrainLength)) + "%",
str(int(100.0 * i / epochNum)) + "%", end="\r")
train_loss = correct / len(trainData.dataset) * 100
print("train loss:", train_loss)
if (train_loss > best_loss):
#if test_loss > best_t_loss:
torch.save(net.state_dict(), bestModelPath)
bestNet = net
best_loss = train_loss
print("model saved")
if validationSet is not None:
test_loss, _ = alexTest(bestModelPath, validationSet, None, caseFile["datasetName"], bestNet, False, None)
# print("training accuracy ({:.2f}%)".format(avg_loss))
trainAccuracy.append(train_loss)
print("test loss:", test_loss)
return trainAccuracy, net
def alexTest(bestModelPath, testSet, resultDict, datasetName, net, saveFlag, outPutFile):
global best_accuracy
global exp
global epoch
global caseFile
correct = 0
if exists(bestModelPath):
if torch.cuda.is_available():
weights = torch.load(bestModelPath)
else:
weights = torch.load(bestModelPath, map_location=torch.device('cpu'))
net.load_state_dict(weights)
net.eval()
if resultDict is None:
testData = testSet
else:
dataTransformer = setupTransformer(datasetName)
transformedData = PathImageFolder(root=testSet, transform=dataTransformer)
testData = torch.utils.data.DataLoader(transformedData, batch_size=caseFile["batchSize"], shuffle=True,
num_workers=caseFile["workersCount"])
classesStr = ','.join(str(class_) for class_ in testData.dataset.classes)
if saveFlag:
outFile = open(outPutFile, 'w')
outFile.writelines("image,result,expected,predicted," + classesStr + "\r\n")
totalInputs = 0
for idx, (data, classes, paths) in enumerate(testData):
if torch.cuda.is_available():
data, classes = data.cuda(), classes.cuda()
totalInputs += len(data)
data, classes = Variable(data), Variable(classes)
scores = net.forward(data)
pred = scores.data.max(1)[1]
correct += torch.sum(pred == classes.data).float()
for i in range(len(data)):
if (classes.data[i].eq(pred[i])):
outcome = "Correct"
else:
outcome = "Wrong"
# imageFileName = basename(paths[i])
if resultDict is not None:
resultDict[paths[i]]["New"] = outcome
strExpected = testData.dataset.classes[classes[i]]
strPred = testData.dataset.classes[pred[i].item()]
scoreStr = ','.join([str(score) for score in scores[i].data.tolist()])
if saveFlag:
outFile.writelines(paths[i] + "," + outcome + "," + strExpected + "," + strPred + "," + scoreStr[1:len(
scoreStr) -
2] +
"\r\n")
print("Predicted {} out of {} correctly".format(correct, totalInputs))
print("The average accuracy is: {} %".format(100.0 * correct / (float(totalInputs))))
print("Total erronous" + str(totalInputs - correct))
if saveFlag:
outFile.close()
#print("predicted {} out of {}".format(correct, len(testData.dataset)))
val_accuracy = (correct / float(totalInputs)) * 100
#print(val_accuracy)
# now save the model if it has better accuracy than the best model seen so forward
return val_accuracy, resultDict
def getSize(outputPath, bagSize, clsPath):
labelDataSize = 0
numClusters = 0
bagSizeperCluster = bagSize
clusterwithAssignedImages = torch.load(clsPath)
for clusterID in clusterwithAssignedImages['clusters']:
numClusters = numClusters + 1
for image in clusterwithAssignedImages['clusters'][clusterID]['assigned']:
labelDataSize = labelDataSize + 1
toBag = (bagSizeperCluster * numClusters) - labelDataSize
totalUnbaggedSize = labelDataSize
totalBaggedSize = bagSizeperCluster * numClusters
return numClusters, toBag, totalUnbaggedSize, totalBaggedSize
def testImage(model, inputs, labels, thresholdPixels, area):
if torch.cuda.is_available():
model = model.cuda()
inputs = Variable(inputs.cuda())
else:
inputs = Variable(inputs)
predict = model(inputs)
predict_cpu = predict.cpu()
predict_cpu = predict_cpu.detach().numpy()
errorList = testModule.ieeError(predict_cpu, labels, area, thresholdPixels)
return errorList[0]
from imports import os, torch, datasets, transforms, Variable, nn, optim, setupTransformer
import dnnModels
import testModule
learning_rate = 0.001
momentum = 0.9
log_schedule = 10
def genericTrain(outputPath, datasetName, epochNum):
# outputPath = "/home/users/hfahmy/DEEP/HPC/FR"
# outputPath = "/scratch/users/fpastore/DEEP/gazedetectionandanalysisdnn/Learning/HUDD/OD/"
testData = join(outputPath, "DataSets", "TestSet")
trainData = join(outputPath, "DataSets", "TrainingSet")
validationData = join(outputPath, "DataSets", "ValidationSet")
improvementData = join(outputPath, "DataSets", "ImprovementSet")
_, unityData, _ = loadData(trainData, datasetName, 4, 128, None, None)
_, testData, _ = loadData(testData, datasetName, 4, 128, None, None)
print(len(unityData.dataset.classes))
net = loadDNNX(None, "AlexNet", len(unityData.dataset.classes), scratchFlag=True)
# print(unityData.dataset)
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=learning_rate, momentum=momentum, weight_decay=5e-4)
best_loss = 0
trainAccuracy = list()
validAccuracy = list()
# classes = torch.FloatTensor(unityData.dataset.classes)
for i in range(1, epochNum + 1):
print("Epoch", i)
##TRAIN
correct = 0
net = net.train()
for b_idx, (data, classes, imgs) in enumerate(unityData):
if torch.cuda.is_available():
net.cuda()
data, classes = data.cuda(), classes.cuda()
# print(data.shape)
data, classes = Variable(data), Variable(classes)
optimizer.zero_grad()
scores = net.forward(data)
scores = scores.view(data.size()[0], len(unityData.dataset.classes))
_, prediction = torch.max(scores.data, 1)
correct += torch.sum(prediction == classes.data).float()
loss = criterion(scores, classes)
loss.backward()
optimizer.step()
if b_idx % log_schedule == 0:
print('Train Epoch: {} [{}\{} ({:.0f}%)]\tLoss: {:.6f}'.format(
i, (b_idx + 1) * len(data), len(unityData.dataset),
100. * (b_idx + 1) * len(data) / len(unityData.dataset), loss.item()), end='\r')
avg_loss = correct / len(unityData.dataset) * 100
print("training accuracy ({:.2f}%)".format(avg_loss))
if (avg_loss > best_loss):
net = net.eval()
torch.save(net.state_dict(), join(outputPath, str(i) + "_pretrainedModel.pth"))
best_loss = avg_loss
##TEST
model = loadDNNX(join(outputPath, str(i) + "_pretrainedModel.pth"), "AlexNet",
len(unityData.dataset.classes), scratchFlag=False)
model = model.eval()
testModule.testErrorAlexNet(model, testData, False, None)
def loadDNNX(modelPath, modelArch: str, numClasses, scratchFlag):
if modelArch == "AlexNet":
net = dnnModels.AlexNetIEE(numClasses) ### HPD
#net = dnnModels.AlexNet(numClasses) ### GD - OC - ASL - TS - AC - OD
if torch.cuda.is_available():
if not scratchFlag:
weights = torch.load(modelPath)
net.load_state_dict(weights)
net = net.to('cuda')
net.cuda()
else:
if not scratchFlag:
weights = torch.load(modelPath, map_location=torch.device('cpu'))
net.load_state_dict(weights)
net.eval()
elif modelArch == "KPNet":
print(modelArch)
net = dnnModels.KPNet()
if torch.cuda.is_available():
if not scratchFlag:
weights = torch.load(modelPath)
net.load_state_dict(weights.state_dict())
net = net.to('cuda')
net.cuda()
else:
if not scratchFlag:
weights = torch.load(modelPath, map_location=torch.device('cpu'))
net.load_state_dict(weights.state_dict())
net.eval()
else:
net = dnnModels.AlexNet(8) # Default is GD
return net
def loadData(dataPath: str, dataSetName: str, workersCount: int, batchSize: int, outputPath, weightPath):
dataSet = 0
train_di = 0
imagesList = 0
if dataSetName == "IEETEST":
x=0
#ds = DataSupply.DataSupplier(using_gm=False)
#if not isfile(outputPath):
# DataSupply.createData(dataPath, outputPath, weightPath)
#train_di, valid_di, imagesList = ds.get_test_iter(outputPath) # for test data
#elif dataSetName == "IEETRAIN":
# ds = DataSupply.DataSupplier(using_gm=False)
# if not isfile(outputPath):
# DataSupply.createData(dataPath, outputPath)
# train_di = ds.get_train_iter(outputPath) # for test data
else:
dataTransformer = setupTransformer(dataSetName)
transformedData = PathImageFolder(root=dataPath, transform=dataTransformer)
dataSet = torch.utils.data.DataLoader(transformedData, batch_size=batchSize, shuffle=True,
num_workers=workersCount)
return train_di, dataSet, imagesList
class PathImageFolder(datasets.ImageFolder):
def __getitem__(self, index):
# this is what ImageFolder normally returns
original_tuple = super(PathImageFolder, self).__getitem__(index)
# the image file path
path = self.imgs[index][0]
# make a new tuple that includes original and the path
tuple_with_path = (original_tuple + (path,))
return tuple_with_path
class Trainer(object):
def __init__(self, iee_train_data, iee_test_data, iee_real_data, batch_size, pin_memory, train_max_num,
test_max_num, real_max_num, multi_gpu, use_gpu_test, use_gpu_train, gpu_id, best_model_path,
loss_file_path, DNN, total_epoch):
self.model = DNN
self.iee_train_data = iee_train_data
self.iee_test_data = iee_test_data
self.iee_real_data = iee_real_data
self.batch_size = batch_size
self.pin_memory = pin_memory
self.train_max_num = train_max_num
self.test_max_num = test_max_num
self.real_max_num = real_max_num
self.multi_gpu = multi_gpu
self.use_gpu_test = use_gpu_test
self.gpu_id = gpu_id
self.use_gpu_train = use_gpu_train
self.best_model_path = best_model_path
self.loss_file_path = loss_file_path
self.total_epoch = total_epoch
if self.multi_gpu:
self.model = torch.nn.DataParallel(self.model)
print("switch to DataParallel mode")
self.optimizer = optim.RMSprop(self.model.parameters(), lr=1e-3)
self.lowest_mse = np.inf
def get_train_data(self):
data_supplier = DataSupplier(self.iee_train_data, self.batch_size, True, self.pin_memory, self.train_max_num)
return data_supplier.get_data_iters()
def get_test_data(self):
data_supplier = DataSupplier(self.iee_test_data, self.batch_size, True, self.pin_memory, self.test_max_num)
return data_supplier.get_data_iters()
def get_real_data(self):
data_supplier = DataSupplier(self.iee_real_data, self.batch_size, True, self.pin_memory, self.real_max_num)
return data_supplier.get_data_iters()
def loss_fn(self, predict, label):
loss = torch.nn.MSELoss()
# if weight:
# predict = predict*weight
return loss(predict, label)
def validate(self, data_batches):
with torch.no_grad():
loss_valid = []
for idx, (inputs, labels) in enumerate(data_batches):
labels = labels["gm"]
if self.use_gpu_test:
if not self.multi_gpu:
self.model = self.model.cuda(self.gpu_id)
inputs, labels = Variable(inputs.cuda(self.gpu_id)), Variable(labels.cuda(self.gpu_id))
else:
self.model = self.model.cuda()
inputs, labels = Variable(inputs.cuda()), Variable(labels.cuda())
else:
inputs, labels = Variable(inputs), Variable(labels)
predict = self.model(inputs.float())
loss = self.loss_fn(predict, labels.float())
loss_valid.append(loss.data.item())
return loss_valid
def save_best(self, train_loss, test_loss, real_loss):
# v_mse = np.mean(test_loss)
v_mse = np.mean(train_loss)
if v_mse < self.lowest_mse:
self.lowest_mse = v_mse
torch.save(self.model, self.best_model_path)
loss = {"train": train_loss, "test": test_loss, "real": real_loss}
np.save(self.loss_file_path, loss)
# print("INFO: save model to: ", self.best_model_path, "save loss data to: ", self.loss_file_path)
def train(self):
print("INFO: loading training data...")
train_data = self.get_train_data()
print("INFO: loading test data...")
test_data = self.get_test_data()
print("INFO: loading kaggle data...")
real_data = self.get_real_data()
print("INFO: starting training ...")
start = time.time()
ETA1 = 0
ETA2 = 0
x = 0
for epoch in range(self.total_epoch):
loss_train = []
totalCounter = 0
retrainLength = len(train_data)
t_s = time.time()
for idx, (inputs, labels) in enumerate(train_data):
start1 = time.time()
totalCounter += 1
labels = labels["gm"]
# print("input shape: ", inputs.shape, "labels shape: ", labels.shape)
if self.use_gpu_train:
if not self.multi_gpu:
self.model = self.model.cuda(self.gpu_id)
inputs, labels = Variable(inputs.cuda(self.gpu_id)), Variable(labels.cuda(self.gpu_id))
else:
self.model = self.model.cuda()
inputs, labels = Variable(inputs.cuda()), Variable(labels.cuda())
else:
inputs, labels = Variable(inputs), Variable(labels)
predict = self.model(inputs.float())
loss = self.loss_fn(predict, labels.float())
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
loss_train.append(loss.data.item())
if x == 0:
end = time.time()
ETA1 = int((((end - start1) / 60.0) * retrainLength))
ETA2 = int((ETA1 * self.total_epoch))
x += 1
print("Checked:", str(totalCounter) + "/" + str(retrainLength) + " " +
str(int(100.0 * totalCounter / retrainLength)) + "%", " ETA1: <" +
str(ETA1 - math.ceil(ETA1 * (totalCounter / retrainLength))) + "m. " + " ETA2: <" +
str(math.ceil((ETA2 - int(ETA2 * (epoch / self.total_epoch))) / 60.0)) + "h. " +
str(int(100.0 * epoch / self.total_epoch)) + "%", end="\r")
loss_test = self.validate(test_data)
loss_real = self.validate(real_data)
t_e = time.time()
# print('\nEpoch: {} Loss Train: {}, Loss Test: {}, Loss Real: {}, time: {} seconds '.format(epoch, np.mean(loss_train),
# np.mean(loss_test), np.mean(loss_real), int(t_e-t_s)), end='\n')
self.save_best(loss_train, loss_test, loss_real)
def reportAvgImages(testDataPath, retrainMode, counter1, counter2, outputPath, datasetName, modelExtension, modelArch,
numClass, unimprovedList):
modelPath = join(outputPath, "DNNModels")
worsened = 0
improved = 0
maxWorsened = 0
minWorsened = 50000000
maxImproved = 0
minImproved = 50000000
#unimprovImagesX = open(unimprovedList, "r")
#unimprovedImages = list()
#for line in unimprovImagesX:
# unimprovedImages.append(line.split("\n")[0])
#for line in f:
#print(line)
#print("Total images to skip", str(len(unimprovedImages)))
ieeData, unityData, imgList = testModule.loadData(testDataPath, datasetName, 4, 128, None, None)
testResultPath = join(outputPath, "testResult.csv")
imgClasses = unityData.dataset.classes
imageList = pd.read_csv(testResultPath,
names=["image", "result", "expected", "predicted"].append(imgClasses))
cnt1 = 0
resultDict = {}
accuList = list()
expirement = int(np.random.randint(100, 100000))
textReport = join(modelPath, "Report_" + retrainMode + "_" + str(expirement) + ".txt")
for index, row in imageList.iterrows():
imagePath = row["image"]
imageFileName = basename(imagePath)
#if unimprovedImages.count(imageFileName)<1:
cnt1 = cnt1 + 1
if cnt1 % 100 == 0:
print("Image checked: " + str(cnt1) + "/" + str(len(imageList)), end="\r")
resultDict[imageFileName] = {}
resultDict[imageFileName]["Old"] = row["result"]
for i in range(counter1, counter2 + 1):
file = open(textReport, "a")
print(join(modelPath, retrainMode + "_" + str(i) + "." + modelExtension))
w, i, accu = reportImages(datasetName, join(modelPath, retrainMode + "_" + str(i) + "." + modelExtension),
resultDict, testDataPath, modelArch, numClass, None)
accuList.append(accu)
file.write(str(accuList))
file.close()
worsened += w
improved += i
if (w > maxWorsened):
maxWorsened = w
if (w < minWorsened):
minWorsened = w
if (i > maxImproved):
maxImproved = i
if (i < minImproved):
minImproved = i
total = counter2 - counter1 + 1
print("Avg worsened: ", str((worsened / total)))
print("Max worsened: ", str((maxWorsened)))
print("Min worsened: ", str((minWorsened)))
print("Avg improved: ", str((improved / total)))
print("Max improved: ", str((maxImproved)))
print("Min improved: ", str((minImproved)))