-
Notifications
You must be signed in to change notification settings - Fork 0
/
Helper.py
1209 lines (1153 loc) · 62.2 KB
/
Helper.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
from __future__ import print_function
#import SEDE_DJ.SEDE_main
import searchModule
from imports import PathImageFolder, torch, os, argparse, setupTransformer, np, Variable, cv2, pd, random, shutil, \
itemgetter, math, stat, datasets, imageio, join, isfile, exists, basename, Image, tqdm, hashlib, makedirs, tf
import IEE_V1.ieedatavendor as ieeDV
import testModule, dnnModels, HeatmapModule, clusterModule, assignModule, retrainModule, IEE_V1.ieepredict as ieepredict, dataSupplier
import config
from IEE_V1 import model
#import conceptModule
#import train_cnn
#import anchors
#from pulp import *
#import pulp
#from data_reader import DataReader
components = ["noseridge", "nose", "mouth", "rightbrow", "righteye", "lefteye"]
class Helper(object):
def KPNet(self, faceSubset): # IEE
#self.faceSubset = faceSubset
#self.outputPath = self.outputPathOriginal
self.saveResult()
#self.outputPath = join(self.outputPathOriginal, faceSubset)
#print("here")
#if not exists(self.outputPath):
# os.mkdir(self.outputPath)
self.generateHeatmaps()
self.generateHMDistances()
self.generateClusters()
self.selectLayer()
self.generateConcepts()
if self.RQ1A:
self.updateCaseFile()
RQ1.IEERQ1(self.caseFile)
return
self.simParam = False
if self.simParam:
self.updateCaseFile()
self.generateImages()
else:
self.assignImages()
return self.ResultDict, self.assignMode
def AlexNet(self): # GD - OC - ASL - TS - AC - HPD - OD
srcPath = join(self.outputPathOriginal, "IEEPackage", "Data")
# mmod = join(self.outputPathOriginal, "IEEPackage", "clsdata/mmod_human_face_detector.dat")
# print(srcPath)
# ieeDV.generate_data(srcPath, "./kaggledata/training.csv", mmod, srcPath)
# predictor = ieepredict.IEEPredictor(join(srcPath, "ieetest.npy"), self.modelPath, True, self.numClass, 0)
# npPath = join(srcPath, "ieetest.npy")
# simDataSet, _ = predictor.load_data(npPath)
# counter, _ = predictor.predict(simDataSet, None, srcPath, False, None, 1, False, None)
# ieeDV.labelHPDimages(npPath, simDataSet, join(srcPath, "Labeled"), "H", 1)
# return
# testModule.testErrorAlexNet(self.DNN, self.caseFile, self.improveDataSet, True, self.improveCSV)
# self.improveDataNpy = self.improveDataSet
# self.updateCaseFile()
# HeatmapModule.saveHeatmaps(self.caseFile, "I")
# self.generateHMDistances()
# for layer in self.layers:
# testModule.testErrorAlexNet(self.DNN, self.caseFile, self.improveDataSet, True, self.improveCSV)
# self.DNN.lrp([], 'simple', 1.0)
#self.DNN = dnnModels.ConvModel()
#R = self.DNN.forward(None)
#self.DNN.relprob(self.DNN.y)
# train_cnn.main()
# print()
# return
#anchors.getAnchor(self.caseFile)
#return
#ieeDV.exportIEEImages(self.realDataSet, join(self.realDataPath), "R", 1)
#return
#self.saveResult()
#self.generateHeatmaps()
#self.generateHMDistances()
#self.generateClusters()
self.selectLayer()
self.assignImages()
return
dstPath = join(self.DataSetsPath, "BIWI", "all")
dstPath2 = join(self.DataSetsPath, "BIWI", "config")
dict_ = {'data': [], 'config': []}
list_ = ["01", "02", "03", "04", "05"]
counter = 1
for s in list_:
for src_dir, dirs, files in os.walk(join(self.DataSetsPath, "BIWI", s)):
for file_ in files:
if (file_.endswith(".jpg")) or (file_.endswith(".png")) or (file_.endswith(".ppm")):
print(counter, end="\r")
imgPath = join(src_dir, file_)
fileName = file_.split(".png")[0]
poseName = fileName.split("_")
txtFile = poseName[0] + "_" + poseName[1] + "_pose.txt"
posePath = join(src_dir, txtFile)
lab = searchModule.labelBIWI(posePath)
shutil.copy(posePath, join(dstPath2, str(counter) + ".txt"))
if not exists(join(dstPath, lab)):
os.makedirs(join(dstPath, lab))
newimgPath = join(dstPath, lab, str(counter) + ".png")
faceFound = searchModule.processBIWI(imgPath, self.dlibPath, newimgPath)
if not faceFound:
print("failed")
# shutil.copy(imgPath, join(dstPath, lab, str(counter)+".png"))
# dict_['data'].append()
# dict_['config'].append()
counter += 1
# self.generateClusters()
# clusterModule.twoPass(self.caseFile, "Layer15", False, join(self.caseFile["filesPath"], "Layer15" + "HMDistance.xlsx"), join(self.caseFile["filesPath"]))
# self.selectLayer()
ieeDV.exportIEEImages(self.realDataSet, join(self.realDataPath), "R", 1)
return
self.selectLayer()
# self.saveResult()
# self.generateHeatmaps()
# self.generateHMDistances()
# self.generateClusters()
# self.selectLayer()
# self.searchImages()
if self.RQ1A:
if self.datasetName.startswith("HPD"):
RQ1.IEERQ1(self.caseFile)
else:
RQ1.UnityRQ1(self.caseFile)
return
self.simParam = False
if self.simParam:
self.generateImages()
else:
self.assignImages()
return self.ResultDict, self.assignMode
def __init__(self, outputPath, modelName, workersCount, batchSize, metric, clustFlag, assignFlag, retrainFlag,
retrainMode, retrainApproach, expNumber, expNumber2, bagSize, clustMode, assMode,
overWrite, selectionMode, FLD, cleanFlag, RCC, scratchFlag, retrieveAccuracy, RQ1A, retrainSet,
drawClustFlag, ieeVersion, clustNum):
self.ResultDict = {}
self.clustNum = int(clustNum) if (clustNum is not None) else 1
datasetName = basename(outputPath)
if isfile(join(outputPath, "caseFile.pt")):
self.caseFile = torch.load(join(outputPath, "caseFile.pt"))
else:
self.caseFile = {}
if RCC == "TT":
self.saveHMTrainFlag = True
self.saveHMTestFlag = True
self.RCC = RCC
else:
self.saveHMTrainFlag = False
self.saveHMTestFlag = True
self.RCC = "T"
if ieeVersion:
self.iee_version = ieeVersion
print("Using IEE Simulator V", self.iee_version)
else:
self.iee_version = 1
if self.iee_version == 1:
config.nVar = 13
else:
config.nVar = 23
self.calcFlag = False
self.faceSubset = "None_RCC"
self.trainDataNpy = None
self.testDataNpy = None
self.improveDataNpy = None
self.outputPath = outputPath
self.outputPathOriginal = self.outputPath
self.DataSetsPath = join(self.outputPath, "DataSets")
self.trainDataPath = join(self.DataSetsPath, "TrainingSet")
self.testDataPath = join(self.DataSetsPath, "TestSet")
self.improveDataPath = join(self.DataSetsPath, "ImprovementSet", "ImprovementSet")
self.realDataPath = join(self.DataSetsPath, "ImprovementSet", "ImprovementSet_Real")
self.trainCSV = join(self.outputPath, "trainResult.csv")
self.testCSV = join(self.outputPath, "testResult.csv")
self.improveCSV = join(self.outputPath, "improveResult.csv")
self.selectedLayer = None
self.maxClust = 150
self.batchSize = batchSize if (batchSize is not None) else 128
self.workersCount = workersCount if (workersCount is not None) else 2
if datasetName == "FLD":
self.modelName = modelName if (modelName is not None) else "kpmodel.pt"
self.numClass = 0
self.simParam = True
self.modelArch = "KPNet"
self.Alex = False
self.KP = True
self.CN = False
self.layers = ['Layer0', 'Layer1', 'Layer2', 'Layer3', 'Layer4', 'Layer5', 'Layer6', 'Layer7', 'Layer8',
'Layer9']
self.datasetName = datasetName
self.FLD = 2 if (FLD is None) else FLD
self.imgExt = ".png"
self.modelPath = join(self.outputPath, "DNNModels", self.modelName)
net = dnnModels.KPNet()
#self.scratchFlag = False
#self.loadDNN(net)
#fout = open(join(self.outputPath, "DNNModels", "kpmodel_pytorch.pt"), 'w')
#for k, v in self.DNN.state_dict().items():
# fout.write(str(k) + '\n')
# fout.write(str(v.tolist()) + '\n')
#fout.close()
#exit(0)
self.trainDataNpy = join(self.outputPath, "IEEPackage", "ieetrain.npy")
self.testDataNpy = join(self.outputPath, "IEEPackage", "ieetest.npy")
self.improveDataNpy = join(self.outputPath, "IEEPackage", "ieeimprove.npy")
self.realDataNpy = join(self.outputPath, "IEEPackage", "ieereal.npy")
self.trainPredict = ieepredict.IEEPredictor(self.trainDataNpy, self.modelPath, False, 0, 0)
self.trainDataSet, _ = self.trainPredict.load_data(self.trainDataNpy)
self.testPredict = ieepredict.IEEPredictor(self.testDataNpy, self.modelPath, False, 0, 0)
self.testDataSet, _ = self.testPredict.load_data(self.testDataNpy)
if not exists(self.testDataPath):
self.testPredict.predict(self.testDataSet, self.testDataPath, self.testDataPath, True, self.testCSV, 0, True, None)
ieepredict.ensure_folder(self.trainDataPath)
ieepredict.ensure_folder(self.testDataPath)
ieepredict.ensure_folder(self.improveDataPath)
self.improvePredict = ieepredict.IEEPredictor(self.improveDataNpy, self.modelPath, False, 0, 0)
self.improveDataSet, _ = self.improvePredict.load_data(self.improveDataNpy)
self.realPredict = ieepredict.IEEPredictor(self.realDataNpy, self.modelPath, False, 0, 0)
self.realDataSet, _ = self.realPredict.load_data(self.realDataNpy)
self.Epochs = 50
elif datasetName == "SAP":
if modelName is not None:
self.modelName = modelName
else:
self.modelName = "model-step-2900-val-0.0718435.ckpt"
self.numClass = 1
self.simParam = False
self.modelArch = "ConvNet"
self.Alex = False
self.KP = False
self.CN = True
self.layers = ['Layer0', 'Layer1', 'Layer2', 'Layer3', 'Layer4', 'Layer5', 'Layer6', 'Layer7', 'Layer8',
'Layer9']
self.datasetName = datasetName
self.imgExt = ".png"
self.modelPath = join(self.outputPath, "DNNModels", self.modelName)
net = dnnModels.ConvModel()
#data_reader_train = dataSupplier.DataReader(data_dir=join(outputPath, "DataSets", "TrainingSet"))
#data_reader_test = dataSupplier.DataReader(data_dir=join(outputPath, "DataSets", "TrainingSet"))
#self.trainDataSet, Train_SA, Train_FID = data_reader_train.load_all()
#self.testDataSet, Test_SA, Test_FID = data_reader_test.load_all()
self.Epochs = 1e5
else:
self.modelArch = "AlexNet"
self.Alex = True
self.KP = False
self.CN = False
self.FLD = 0
self.datasetName = datasetName
print(datasetName)
if datasetName == "GD":
self.simParam = True
self.numClass = 8
self.Epochs = 10
self.imgExt = ".jpg"
self.modelName = modelName if (modelName is not None) else "pretrainedModel.pth"
net = dnnModels.AlexNet(self.numClass)
elif datasetName == "OC":
self.simParam = True
self.numClass = 2
self.Epochs = 10
self.imgExt = ".jpg"
self.modelName = modelName if (modelName is not None) else "pretrainedModel.pth"
net = dnnModels.AlexNet(self.numClass)
elif datasetName == "ASL":
self.simParam = True
self.numClass = 29
self.Epochs = 13
self.imgExt = ".jpg"
self.modelName = modelName if (modelName is not None) else "pretrainedModel.pth"
net = dnnModels.AlexNet(self.numClass)
elif datasetName == "TS":
self.simParam = False
self.numClass = 43
self.Epochs = 12
self.imgExt = ".ppm"
self.modelName = modelName if (modelName is not None) else "pretrainedModel.pty"
net = dnnModels.AlexNet(self.numClass)
elif datasetName == "OD":
self.simParam = False
self.numClass = 2
self.Epochs = 13
self.imgExt = ".jpg"
self.modelName = modelName if (modelName is not None) else "13_pretrainedModel.pth"
net = dnnModels.AlexNet(self.numClass)
elif datasetName == "AC":
self.simParam = False
self.numClass = 8
self.Epochs = 20
self.imgExt = ".jpg"
self.modelName = modelName if (modelName is not None) else "pretrainedModel.pth"
net = dnnModels.AlexNet(self.numClass)
# genericTrain.train(self.outputPath, self.datasetName, self.Epochs)
# return
elif datasetName == "HPD":
self.simParam = True
self.numClass = 9
self.Epochs = 10
#self.Epochs = 18 #HPD1
#self.Epochs = 25 #HPD2
#self.Epochs = 17
self.datasetName = datasetName
self.modelName = modelName if (modelName is not None) else "25_pretrainedModel.pth"
# self.modelName_S = "16_finetunedModel.pth" #"25_pretrainedModel.pth
# self.modelName_S = "9_finetunedModel.pth" #"18_pretrainedModel.pth"
# self.modelName_S = "18_pretrainedModel.pth" #"18_pretrainedModel.pth"
# self.modelName_S = "28_finetunedModel.pth" #"18_pretrainedModel.pth"
self.modelName_S = "25_pretrainedModel.pth" #HPD2
#self.modelName_S = "18_pretrainedModel.pth" #HPD1
# self.modelName = "16_finetunedModel.pth" #"25_pretrainedModel.pth
# self.modelName = "9_finetunedModel.pth" #"18_pretrainedModel.pth"
#self.modelName = "25_pretrainedModel.pth" #HPD2
#self.modelName = "18_pretrainedModel.pth" #HPD2
#self.modelName = "28_finetunedModel.pth" #HPD2
self.modelName = "pretrainedModel.pth" #HPD_TR
#self.modelName = "30_pretrainedModel_.pth" #HPD_HSM
#self.modelName = "9_finetunedModel.pth" #HPD1
# self.modelName_R = "16_finetunedModel.pth" #"25_pretrainedModel.pth
# self.modelName_R = "9_finetunedModel.pth" #"18_pretrainedModel.pth"
# self.modelName_R = "25_pretrainedModel.pth" #"18_pretrainedModel.pth"
# self.modelName_R = "18_pretrainedModel.pth" #"18_pretrainedModel.pth"
self.modelName_R = "28_finetunedModel.pth" #"18_pretrainedModel.pth"
#self.modelName_R = "9_finetunedModel.pth" #HPD1 #"18_pretrainedModel.pth"
net = dnnModels.AlexNetIEE(self.numClass)
self.imgExt = ".png"
self.testDataNpy = join(self.outputPath, "IEEPackage", "ieetest.npy")
self.trainDataNpy = join(self.outputPath, "IEEPackage", "ieetrain.npy")
self.improveDataNpy = join(self.outputPath, "IEEPackage", "ieeimprove.npy")
self.realDataNpy = join(self.outputPath, "IEEPackage", "ieereal.npy")
self.modelPath = join(self.outputPath, "DNNModels", self.modelName)
self.trainPredict = ieepredict.IEEPredictor(self.trainDataNpy, self.modelPath, True, 9, 0)
self.trainDataSet, _ = self.trainPredict.load_data(self.trainDataNpy)
self.testPredict = ieepredict.IEEPredictor(self.testDataNpy, self.modelPath, True, 9, 0)
self.testDataSet, _ = self.testPredict.load_data(self.testDataNpy)
#self.testPredict.predict(self.testDataSet, dst, originalDst, saveFlag, saveImgs, mainCounter)
self.improvePredict = ieepredict.IEEPredictor(self.improveDataNpy, self.modelPath, True, 9, 0)
self.improveDataSet, _ = self.improvePredict.load_data(self.improveDataNpy)
self.realPredict = ieepredict.IEEPredictor(self.realDataNpy, self.modelPath, True, 9, 0)
self.realDataSet, _ = self.realPredict.load_data(self.realDataNpy)
# genericTrain.train(self.outputPath, self.datasetName, self.Epochs)
# return
self.modelPath = join(self.outputPath, "DNNModels", self.modelName)
self.layers = ['Layer0', 'Layer1', 'Layer3', 'Layer4', 'Layer6', 'Layer7', 'Layer9', 'Layer11', 'Layer13',
'Layer15', 'Layer18']
dataTransformer = setupTransformer(self.datasetName)
transformedData = PathImageFolder(root=self.trainDataPath, transform=dataTransformer)
self.trainDataSet = torch.utils.data.DataLoader(transformedData, batch_size=self.batchSize, shuffle=True,
num_workers=self.workersCount)
transformedData = PathImageFolder(root=self.testDataPath, transform=dataTransformer)
self.testDataSet = torch.utils.data.DataLoader(transformedData, batch_size=self.batchSize, shuffle=True,
num_workers=self.workersCount)
#transformedData = PathImageFolder(root=join(self.improveDataPath),
# transform=dataTransformer)
#self.improveDataSet = torch.utils.data.DataLoader(transformedData, batch_size=self.batchSize, shuffle=True,
# num_workers=self.workersCount)
self.scratchFlag = scratchFlag if (scratchFlag is not None) else False
self.loadDNN(net)
#params = net.state_dict()
#print(net.state_dict)
#for key in net.features.parameters():
# key.requires_grad = False ##Freeze
#print(params.keys())
self.saveHMFlag = True
self.computeFlag = True
self.metric = metric if (metric is not None) else "Euc" #"Man"
self.clustFlag = clustFlag if (clustFlag is not None) else True
self.drawClustFlag = drawClustFlag if (drawClustFlag is not None) else True
self.RQ1A = RQ1A if (RQ1A is not None) else False
self.retrainFlag = retrainFlag if (retrainFlag is not None) else True
self.retrainMode = retrainMode if (retrainMode is not None) else "None"
self.overWrite = overWrite if (overWrite is not None) else False
self.retrainApproach = retrainApproach if (retrainApproach is not None) else "A"
self.expNumber = int(expNumber) if (expNumber is not None) else 1
self.expNumber2 = int(expNumber2) if (expNumber2 is not None) else 10
self.bagSize = int(bagSize) if (bagSize is not None) else 0
self.selectionMode = selectionMode if (selectionMode is not None) else "WICD"
self.clustMode = clustMode if (clustMode is not None) else "WICDWard"
self.assignMode = assMode if (assMode is not None) else "ClosestU" #Entropy
self.assignFlag = assignFlag if (assignFlag is not None) else True
self.cleanFlag = cleanFlag if (cleanFlag is not None) else True
self.saveTrainFlag = False if (exists(self.trainCSV)) else True
self.saveTestFlag = False if (exists(self.testCSV)) else True
self.saveImproveFlag = False if (exists(self.improveCSV)) else True
self.saveImproveFlag = False
if self.assignFlag:
assignPath = join(self.outputPath, "ClusterAnalysis_" + str(self.clustMode), "Assignments",
self.assignMode, self.selectionMode, "clusterwithAssignedImages.pt")
if self.overWrite:
if exists(assignPath):
shutil.rmtree(join(self.outputPath, "ClusterAnalysis_" + str(self.clustMode),
"Assignments", self.assignMode, self.selectionMode))
if exists(assignPath):
self.assignFlag = False
self.retrieveAccuracy = retrieveAccuracy
self.retrainSet = retrainSet
self.caseFile["retrainList"] = []
#print(self.improveDataPath)
for src_dir, dirs, files in os.walk(self.improveDataPath):
for file_ in files:
#print(file_)
if (file_.endswith(".jpg")) or (file_.endswith(".png")) or (file_.endswith(".ppm")):
self.caseFile["retrainList"].append(join(src_dir, file_))
self.updateCaseFile()
print("Case Study Initialization Completed..")
def cleanDirectories(self):
setsPath = join(str(self.caseFile["filesPath"]), "DataSets")
if not exists(setsPath):
os.makedirs(setsPath)
setsList = os.listdir(setsPath)
for set in setsList:
if set.startswith(self.retrainMode):
shutil.rmtree(join(setsPath, set))
modelsPath = join(str(self.caseFile["filesPath"]), "DNNModels_" + str(self.retrainMode))
if not exists(modelsPath):
os.makedirs(modelsPath)
modelsList = os.listdir(modelsPath)
for set in modelsList:
if set.startswith(self.retrainMode):
os.remove(join(modelsPath, set))
if set.startswith("Report_" + self.retrainMode):
os.remove(join(modelsPath, set))
def explain(self):
self.RCC = "TR"
self.updateCaseFile()
self.selectLayer()
xplainModule.run(self.caseFile)
def generateDataSet(self):
srcPath = join(self.outputPathOriginal, "IEEPackage", "Data")
# searchModule.generateRandomImage(srcPath)
# self.caseFile["SimDataPath"] = join(self.caseFile["filesPath"], "NewTestSet")
# x = 0
# for i in range(0, 2799):
# print(i, end="\r")
# imgPath, faceFound = searchModule.generateAnImage(searchModule.setX(1, "R"), self.caseFile)
# N, DNNResult, P, L, D, _ = searchModule.doImage(imgPath+".png", self.caseFile, None)
# if DNNResult:
# x += 1
# print(100* x/2800)
# return
# mmod = join(self.outputPathOriginal, "IEEPackage", "clsdata/mmod_human_face_detector.dat")
# ieeDV.generate_data(srcPath, "./kaggledata/training.csv", mmod, srcPath)
ieeDV.generate_data(srcPath, "./kaggledata/training.csv", mmod, srcPath)
# predictor = ieepredict.IEEPredictor(join(srcPath, "ieetest.npy"), self.modelPath, True, self.numClass, 0)
# npPath = join(srcPath, "ieetest.npy")
# simDataSet, _ = predictor.load_data(npPath)
# counter, _ = predictor.predict(simDataSet, None, srcPath, False, None, 1, False, None)
# ieeDV.labelHPDimages(npPath, simDataSet, join(srcPath, "Labeled"), "H", 1)
labeledPath = join(srcPath, "Labeled")
dataSupplier.labelImages(labeledPath)
def generateConcepts(self):
if self.datasetName == "FLD":
self.caseFile["selectedLayer"] = "Layer9"
self.selectedLayer = "Layer9"
else:
# self.caseFile["selectedLayer"] = "Layer15"
# self.caseFile["selectedLayer"] = "Layer13"
# self.selectedLayer = "Layer15"
# self.selectedLayer = "Layer13"
self.selectLayer()
# UnsafeSpace = {'clusters': {1: {'members': []}}}
UnsafeSpace = {'clusters': {}}
if self.Alex:
if self.faceSubset == "CC":
# imageList = pd.read_csv(self.testCSV)
imageList = pd.read_csv(self.improveCSV)
imageList2 = pd.read_csv(self.trainCSV)
classes = ['BottomLeft', 'BottomRight', 'MiddleCenter',
'BottomCenter', 'MiddleRight', 'MiddleLeft']
# , 'TopLeft', 'TopRight', 'TopCenter']
# classes = ['Opened', 'Closed']
UnsafeSpace['clusters'] = {}
for classA in classes:
UnsafeSpace['clusters'][classA] = {'members': []}
num = 0
numA = 0
for index, row in imageList.iterrows():
if row["result"] == "Correct":
if row["expected"] == classA:
numA += 1
if num < 150:
UnsafeSpace['clusters'][classA]['members'].append(
"Test_" + basename(row["image"]).split(".")[0] + "_" + str(row["expected"]))
num += 1
# num = 0
# numA = 0
# for index, row in imageList2.iterrows():
# if row["result"] == "Correct":
# if row["expected"] == classA:
# numA += 1
# if num < 75:
# UnsafeSpace['clusters'][classA]['members'].append("Train_"+basename(row["image"]).split(".")[0]+"_"+str(row["expected"]))
# num += 1
print(classA, num, numA)
# clsWithAssImages = UnsafeSpace
elif self.faceSubset == "HOF":
for img in os.listdir(join(self.caseFile["filesPath"], "Heatmaps", "Layer15")):
UnsafeSpace['clusters'][1]['members'].append(img.split(".")[0])
clsWithAssImages = UnsafeSpace
else:
self.caseFile["clsPath"] = join(self.outputPathOriginal, self.RCC, "ClusterAnalysis_" +
str(self.clustMode), self.selectedLayer + ".pt")
print(self.selectedLayer)
clsWithAssImages = torch.load(self.caseFile["clsPath"], map_location=torch.device('cpu'))
for clusterID in clsWithAssImages['clusters']:
UnsafeSpace['clusters'][1] = {'members': []}
for img in clsWithAssImages['clusters'][clusterID]['members']:
UnsafeSpace['clusters'][1]['members'].append(img)
if self.faceSubset == "None":
clsWithAssImages = UnsafeSpace
else:
if not self.faceSubset == "all":
self.caseFile["clsPath"] = join(self.outputPath, self.RCC, "ClusterAnalysis_" +
str(self.clustMode), self.selectedLayer + ".pt")
clsWithAssImages = torch.load(self.caseFile["clsPath"], map_location=torch.device('cpu'))
else:
for subset in self.caseFile["components"]:
self.caseFile["clsPath"] = join(self.outputPathOriginal, subset, self.RCC, "ClusterAnalysis_" +
str(self.clustMode), self.selectedLayer + ".pt")
clsWithAssImages = torch.load(self.caseFile["clsPath"], map_location=torch.device('cpu'))
for clusterID in clsWithAssImages['clusters']:
for img in clsWithAssImages['clusters'][clusterID]['members']:
UnsafeSpace['clusters'][1]['members'].append(img)
clsWithAssImages = torch.load(self.caseFile["clsPath"], map_location=torch.device('cpu'))
self.caseFile["faceSubset"] = "None_RCC"
if not exists(join(self.caseFile["outputPathOriginal"], "None_RCC", "clsData.pt")):
clsData = conceptModule.generateConcepts(clsWithAssImages, self.caseFile)
torch.save(clsData, join(self.caseFile["outputPathOriginal"], "None_RCC", "clsData.pt"))
else:
clsData = torch.load(join(self.caseFile["outputPathOriginal"], "None_RCC", "clsData.pt"))
# self.caseFile["faceSubset"] = "CC"
# conceptModule.generateConcepts(UnsafeSpace, self.caseFile)
# clsWithAssImages = UnsafeSpace
# return
for clusterID in clsWithAssImages['clusters']:
print("**** CLUSTER ****", clusterID)
dict_ = {}
newList = []
conceptRadius = torch.load(
join(self.caseFile["outputPathOriginal"], "None_RCC", "ConceptsData", "ConceptsClusters",
# str(clusterID), "conceptsDia.pt"))
str(clusterID), "conceptsRadius.pt"))
conceptCentroid = torch.load(
join(self.caseFile["outputPathOriginal"], "None_RCC", "ConceptsData", "ConceptsClusters",
str(clusterID), "conceptsCentroids.pt"))
for clusterID2 in UnsafeSpace['clusters']:
conceptRadius2 = torch.load(
join(self.caseFile["outputPathOriginal"], "CC", "ConceptsData", "ConceptsClusters",
# str(clusterID2), "conceptsDia.pt"))
str(clusterID2), "conceptsRadius.pt"))
conceptCentroid2 = torch.load(
join(self.caseFile["outputPathOriginal"], "CC", "ConceptsData", "ConceptsClusters",
str(clusterID2), "conceptsCentroids.pt"))
_, _, exclusiveConcepts = conceptModule.analyzeConcepts2(conceptRadius, conceptCentroid, conceptRadius2,
conceptCentroid2)
for concept in exclusiveConcepts:
if concept not in dict_:
dict_[concept] = 1
else:
dict_[concept] += 1
for concept in dict_:
if dict_[concept] == len(UnsafeSpace['clusters']):
newList.append(concept)
conceptRadius = torch.load(
join(self.caseFile["outputPathOriginal"], "None_RCC", "ConceptsData", "ConceptsClusters",
str(clusterID), "conceptsRadius.pt"))
conceptModule.analyzeConcepts(conceptRadius, conceptCentroid, newList, join(
join(self.caseFile["outputPathOriginal"], "None_RCC", "ConceptsData", "ConceptsClusters",
str(clusterID))), clsData['all'][clusterID])
def getParams(self):
self.selectLayer()
# self.selectedLayer = "Layer9"
# clsData = torch.load(join(self.outputPathOriginal, self.faceSubset, self.RCC, "ClusterAnalysis_" +
# self.clustMode, self.selectedLayer + ".pt"), map_location=torch.device('cpu'))
clsData = torch.load(
join(self.outputPathOriginal, self.RCC, "ClusterAnalysis_" + self.clustMode, self.selectedLayer + ".pt"),
map_location=torch.device('cpu'))
# clsParam = np.load(join(self.outputPathOriginal, self.faceSubset, "clustersParamData.npy"), allow_pickle=True)
# print(clsParam)
# return
#paramsModule.getParams(self.testCSV, self.testDataNpy, join(self.caseFile["outputPathOriginal"], self.faceSubset, self.RCC, self.selectedLayer+"_WICD"), clsData, join(self.caseFile["filesPath"], "DT_MC_RCC.csv"))
# paramsModule.getParams(self.improveCSV,join(self.outputPath, "IEEPackage", "ieeimprove.npy"), join(self.outputPathOriginal, self.RCC, self.selectedLayer+"_WICD"), clsData, join(self.caseFile["filesPath"], "DT.csv"))
paramsModule.getParams(self.testCSV, self.testDataNpy,
join(self.outputPathOriginal, self.RCC, self.selectedLayer + "_WICD"), clsData,
join(self.caseFile["filesPath"], "DT_MC_CC.csv"))
# paramsModule.getParams(self.trainCSV,self.trainDataNpy, join(self.outputPathOriginal, self.RCC, self.selectedLayer+"_WICD"), clsData, join(self.caseFile["filesPath"], "DT.csv"))
def SEDE(self):
self.RCC = "TR" #HPD-H
#self.RCC = "TR1" #HPD-F
self.updateCaseFile()
#searchModule.evaluateResults(self.caseFile)
#return
self.selectLayer()
print("Loading HM distance file for the selected layer.")
HMDistFile = join(str(self.caseFile["filesPath"]), str(self.caseFile["selectedLayer"]) + "HMDistance.xlsx")
clusterRadius, centroidHM, testHM = assignModule.getClusterData(self.caseFile, HMDistFile)
#clusters = clsData['clusters']
#clusters = [8, 9, 10, 11, 12, 13, 14, 15, 16, 17]
#clusters = [1, 2, 4, 5, 6, 8, 10] #HPD-F
#clusters = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] #HPD-H
clusters = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] #FLD/HPD-H
clusters = [self.clustNum]
#SEDE_DJ.SEDE_main.runSEDE(self.caseFile, clusters, centroidHM, clusterRadius)
popSize = [25, 25, 25]
nGen = [200, 100, 100]
searchModule.search(self.caseFile, clusters, centroidHM, clusterRadius, popSize, nGen)
return
#clusters = [self.clustNum]
#searchModule.search(self.caseFile, clusters, centroidHM, clusterRadius, popSize, nGen)
#SEDE_RQ1.compareReal(self.caseFile, centroidHM)
#SEDE_RQ1.RQ1_1(clusters, self.caseFile)
dictLabel_S, SEDE_imgs = SEDE_RQ1.RQ1_1(clusters, self.caseFile)
SEDE_RQ1.RQ1_2(centroidHM, SEDE_imgs, self.caseFile)
#SEDE_RQ1.RQ1_2(clusters, self.caseFile)
return
#T_path = self.caseFile["filesPath"]
#if not exists(self.caseFile["filesPath"]):
# shutil.copy(T_path, self.caseFile["filesPath"])
#layerClust = join(str(self.caseFile["filesPath"]), "ClusterAnalysis_" + str(self.clustMode),
# str(self.caseFile["selectedLayer"]) + ".pt")
#clsData = torch.load(layerClust, map_location=torch.device('cpu'))
heatMapDistanceExecl = pd.read_excel(HMDistFile)
heatMapDistanceExecl.drop(heatMapDistanceExecl.columns[heatMapDistanceExecl.columns.str.contains('unnamed',
case=False)],
axis=1, inplace=True)
clusterMembersName = heatMapDistanceExecl.columns
model = LpProblem("test", LpMinimize)
from scipy.optimize import linprog
for clusterID in clsData['clusters']:
clusterMembers = clsData['clusters'][clusterID]['members']
cost = []
variables = []
bound = []
for m1 in range(0, len(clusterMembers)):
for m2 in range(m1 + 1, len(clusterMembers)):
index1 = clusterMembersName.get_loc(clusterMembers[m1])
index2 = clusterMembersName.get_loc(clusterMembers[m2])
dist = float(heatMapDistanceExecl.values[index1][index2])
variables.append(str(index1) + str(index2))
cost.append(dist)
bound.append((1, 1))
cost_matrix = np.array(cost)
res = linprog(cost, bounds=bound)
print(res)
return
DV_variables = LpVariable.matrix("X", variables, cat="Integer", lowBound=0.0)
print(DV_variables)
for variable in DV_variables:
variable.setInitialValue(1.0)
variable.upBound = 1.0
allocation = np.array(DV_variables).reshape(1, len(variables))
# print(allocation)
# print(cost_matrix)
obj_func = lpSum(allocation * cost_matrix)
# print(obj_func)
model += obj_func
# print(model)
model.solve(solver=PULP_CBC_CMD())
print(clusterID)
print("Total Cost:", model.objective.value())
# for v in model.variables():
# try:
# print(v.name, "=", v.value())
# except:
# print("error couldnt find value")
print(len(clusterMembers))
print(len(cost))
return
return
# layerDistances = pd.DataFrame()
# for member in testHM:
# inList = list()
# inList2 = list()
# inList3 = list()
# for clusterID in clsData['clusters']:
# inList2.append(clusterID)
# inList3.append(clusterRadius[clusterID])
# dist = HeatmapModule.doDistance(centroidHM[clusterID], testHM[member], "Euc")
# if member in clsData['clusters'][clusterID]['members']:
# inList.append("B_"+str(dist)[0:4])
# elif dist < clusterRadius[clusterID]:
# inList.append("I_"+str(dist)[0:4])
# else:
# inList.append("O_"+str(dist)[0:4])
# layerDistances['clusters'] = inList2
# layerDistances['cluster-radius'] = inList3
# layerDistances[member] = inList
# writer = pd.ExcelWriter(join(self.caseFile["filesPath"], self.caseFile["selectedLayer"]
# + "HMDistance_Clustered.xlsx"), engine='xlsxwriter')
# writer.book.use_zip64()
# layerDistances.to_excel(writer)
# writer.close()
# for clusterID1 in clsData['clusters']:
# insideImages = 0
# outsideImages = 0
# inList = list()
# for clusterID2 in clsData['clusters']:
# if clusterID1 != clusterID2:
# for member in clsData['clusters'][clusterID2]['members']:
# dist = HeatmapModule.doDistance(centroidHM[clusterID1], testHM[member], "Euc")
# if dist < clusterRadius[clusterID1]:
# insideImages += 1
# inList.append(True)
# else:
# outsideImages += 1
# print(clusterID1, str(100*insideImages/(insideImages+outsideImages))[0:5],
# str(100*outsideImages/(insideImages+outsideImages))[0:5])
# centroidHM = {}
# clusterRadius = {}
# for clusterID in clsData['clusters']:
# centroidHM[clusterID] = []
# clusterRadius[clusterID] = 0.2
def updateCaseFile(self):
if self.datasetName != "SAP":
if self.iee_version:
self.caseFile["iee_version"] = self.iee_version
else:
self.caseFile["iee_version"] = 0
self.caseFile["KP"] = self.KP
self.caseFile["FLD"] = self.FLD
self.caseFile["RCC"] = self.RCC
if "DNN" not in self.caseFile:
self.caseFile["DNN"] = self.DNN
#if "DNN2" not in self.caseFile:
# self.modelPath = join(self.outputPath, "DNNModels", self.modelName_S)
#print("DNN2", self.modelPath)
# self.loadDNN(dnnModels.AlexNetIEE(self.numClass))
# self.caseFile["DNN2"] = self.DNN
#self.modelPath = join(self.outputPath, "DNNModels", self.modelName_R)
#print("DNN1", self.modelPath)
if self.datasetName == "HPD":
self.loadDNN(dnnModels.AlexNetIEE(self.numClass))
if self.datasetName == "FLD":
self.loadDNN(dnnModels.KPNet())
self.caseFile["Alex"] = self.Alex
self.caseFile["Epochs"] = self.Epochs
self.caseFile["imgExt"] = self.imgExt
self.caseFile["metric"] = self.metric
self.caseFile["layers"] = self.layers
self.caseFile["testCSV"] = self.testCSV
self.caseFile["trainCSV"] = self.trainCSV
self.caseFile["improveCSV"] = self.improveCSV
self.caseFile["expNum1"] = self.expNumber
self.caseFile["numClass"] = self.numClass
self.caseFile["expNum2"] = self.expNumber2
self.caseFile["modelPath"] = self.modelPath
self.caseFile["maxCluster"] = self.maxClust
self.caseFile["batchSize"] = self.batchSize
self.caseFile["outputPath"] = self.outputPath
self.caseFile["faceSubset"] = self.faceSubset
self.caseFile["clustMode"] = self.clustMode
self.caseFile["assignMode"] = self.assignMode
self.caseFile["datasetName"] = self.datasetName
self.caseFile["retrainMode"] = self.retrainMode
self.caseFile["retrainMode"] = self.retrainMode
self.caseFile["testFlag"] = self.saveHMTestFlag
self.caseFile["testDataSet"] = self.testDataSet
self.caseFile["testDataNpy"] = self.testDataNpy
self.caseFile["DataSetsPath"] = self.DataSetsPath
self.caseFile["scratchFlag"] = self.scratchFlag
self.caseFile["workersCount"] = self.workersCount
self.caseFile["trainDataNpy"] = self.trainDataNpy
self.caseFile["trainDataSet"] = self.trainDataSet
self.caseFile["trainFlag"] = self.saveHMTrainFlag
self.caseFile["testDataPath"] = self.testDataPath
self.caseFile["drawClustFlag"] = self.drawClustFlag
self.caseFile["selectedLayer"] = self.selectedLayer
self.caseFile["selectionMode"] = self.selectionMode
self.caseFile["trainDataPath"] = self.trainDataPath
self.caseFile["improveDataNpy"] = self.improveDataNpy
#self.caseFile["realDataNpy"] = self.realDataNpy
#self.caseFile["improveDataSet"] = self.improveDataSet
self.caseFile["improveDataPath"] = self.improveDataPath
self.caseFile["retrainApproach"] = self.retrainApproach
self.caseFile["outputPathOriginal"] = self.outputPathOriginal
self.caseFile["filesPath"] = join(self.outputPath, self.RCC)
self.dlibPath = join(self.caseFile["outputPath"], "IEEPackage/clsdata/mmod_human_face_detector.dat")
self.filesPath = self.caseFile["filesPath"]
self.caseFile["components"] = ["noseridge", "nose", "mouth", "rightbrow", "righteye", "lefteye", "leftbrow"]
self.caseFile["caseFile"] = join(str(self.caseFile["filesPath"]),
"caseFile_" + self.retrainMode + ".pt")
assignPath = join(str(self.caseFile["filesPath"]), "ClusterAnalysis_" + self.clustMode, "Assignments",
self.assignMode, self.selectionMode)
if isfile(self.improveCSV):
# print(self.improveCSV, "exists")
self.saveImproveFlag = False
else:
# print(self.improveCSV, "doesn't exist")
self.saveImproveFlag = True
self.saveImproveFlag = False
if not exists(assignPath):
os.makedirs(assignPath)
self.caseFile["assignPTFile"] = join(assignPath, "clusterwithAssignedImages.pt")
self.caseFile["assignXLFile"] = join(assignPath, "clusterwithAssignedImages.xlsx")
self.caseFile["improveRCCDists"] = join(assignPath, "improveRCCDists")
if not exists(self.caseFile["improveRCCDists"]):
os.makedirs(self.caseFile["improveRCCDists"])
torch.save(self.caseFile, self.caseFile["caseFile"])
def generateImages(self):
filePath = join(self.outputPath, "clustersParamData.npy")
if isfile(filePath):
clustersData = np.load(filePath, allow_pickle=True)
clusterData = clustersData.item()
trainHashList = list()
for src_dir, dirs, files in os.walk(self.trainDataPath):
for file_ in files:
if (file_.endswith(".jpg")) or (file_.endswith(".png")) or (file_.endswith(".ppm")):
imgPath = join(src_dir, file_)
img = Image.open(imgPath)
img.save(join(self.outputPath, "1.PNG"), 'PNG')
m = hashlib.md5()
data = open(join(self.outputPath, "1.PNG"), 'rb').read()
m.update(data)
trainHashList.append(m)
os.remove(join(self.outputPath, "1.PNG"))
for clusterID in clusterData:
i = 0
k = 0
srcPath = join(self.outputPath, "SimData", "SimulatorData", "Cluster_" + str(clusterID))
mmod = join(self.outputPathOriginal, "IEEPackage", "clsdata/mmod_human_face_detector.dat")
print(srcPath)
if not isfile(join(srcPath, "ieetest.npy")):
ieeDV.generate_data(srcPath, "./kaggledata/training.csv", mmod, srcPath)
predictor = ieepredict.IEEPredictor(join(srcPath, "ieetest.npy"), self.modelPath, 0)
simDataSet, _ = predictor.load_data(join(srcPath, "ieetest.npy"))
counter, _ = predictor.predict(simDataSet, None, srcPath, False, None, 1, False, None)
for src_dir, dirs, files in os.walk(join(srcPath, "0_Data")):
for file_ in files:
if (file_.endswith(".jpg")) or (file_.endswith(".png")) or (file_.endswith(".ppm")):
imgPath = join(src_dir, file_)
img = Image.open(imgPath)
img.save(join(self.outputPath, "1.PNG"), 'PNG')
m = hashlib.md5()
data = open(join(self.outputPath, "1.PNG"), 'rb').read()
m.update(data)
i += 1
for hashi in trainHashList:
if m == hashi:
k += 1
print((k / i) * 100, " images are included in the TrainingSet")
os.remove(join(self.outputPath, "1.PNG"))
else:
if self.KP:
clustersData = RQ1.IEERQ1(self.caseFile)
else:
if self.datasetName == "IEE":
clustersData = RQ1.IEERQ1(self.caseFile)
else:
clustersData = RQ1.UnityRQ1(self.caseFile)
np.save(filePath, clustersData)
def loadDNN(self, net):
if self.CN:
saver = tf.compat.v1.train.Saver()
sess = tf.compat.v1.Session()
print(self.modelPath)
#sess.run(tf.compat.v1.global_variables_initializer())
saver.restore(sess, self.modelPath)
#self.DNN = dnnModels.ConvModel()
else:
if torch.cuda.is_available():
if not self.scratchFlag:
weights = torch.load(self.modelPath)
#print("Loaded", self.modelPath)
if self.Alex:
net.load_state_dict(weights)
elif self.KP:
net.load_state_dict(weights.state_dict())
net = net.to('cuda')
net.cuda()
net.eval()
self.DNN = net
else:
if not self.scratchFlag:
weights = torch.load(self.modelPath, map_location=torch.device('cpu'))
#print("Loaded", self.modelPath)
if self.Alex:
net.load_state_dict(weights)
elif self.KP:
net.load_state_dict(weights.state_dict())
net.eval()
self.DNN = net
def selectLayer(self):
self.selectedLayer = None
minAvgWICD = [0] * len(self.layers)
i = 0
clsPath = join(self.caseFile["filesPath"], "ClusterAnalysis_" + str(self.clustMode))
for layerX in self.layers:
clsFile = join(clsPath, layerX + ".pt")
if torch.cuda.is_available():
clsData = torch.load(clsFile)
else:
clsData = torch.load(clsFile, map_location=torch.device('cpu'))
# minAvgICD[i] = clsData["avgLayer"]
minAvgWICD[i] = clsData["WeightedavgLayer"]
minAvgWICD[0] = 1e9
i += 1
indxW = min(enumerate(minAvgWICD), key=itemgetter(1))[0]
self.selectedLayer = self.layers[indxW]
print("Selected Layer based on ", self.selectionMode, " is ", str(self.selectedLayer))
# print(minAvgWICD[indxW])
# print(minAvgWICD)
selectedClsFile = join(clsPath, self.selectedLayer + ".pt")
self.caseFile["clsPath"] = str(selectedClsFile)
self.caseFile["layerIndex"] = int(self.selectedLayer.replace("Layer", ""))
self.caseFile["selectedLayer"] = self.selectedLayer
# dirPath = join(str(self.caseFile["filesPath"]), str(self.selectedLayer) + "_" + str(self.selectionMode))
# if exists(dirPath):
# shutil.rmtree(dirPath)
# shutil.copytree(join(clsPath, self.selectedLayer), dirPath)
self.updateCaseFile()
def TLDNN(self):
retrainModule.fineTune(self.modelPath, self.outputPath, self.datasetName, 10, self.caseFile)
return
if self.datasetName != "SAP":
modelPath = join(self.caseFile["filesPath"], "DNNModels_" + "TL")
if not exists(modelPath):
makedirs(modelPath)
bestModelPath = join(modelPath,"TL." + str(basename(self.modelPath).split(".")[1]))
dataTransform = setupTransformer(self.datasetName)
transformedData2 = PathImageFolder(root=self.caseFile["testDataPath"]+"_S", transform=dataTransform)
testData2 = torch.utils.data.DataLoader(transformedData2, batch_size=self.batchSize, shuffle=True,
num_workers=self.workersCount)
print(self.modelPath)
testAccuracy2, resultDictNew = retrainModule.alexTest(self.modelPath, testData2, None, self.datasetName, self.DNN, False, None)
print(testAccuracy2.item())
ts = datasets.ImageFolder(root=self.caseFile["trainDataPath"], transform=dataTransform)
#tsList.append(ts2)
#concatList = torch.utils.data.ConcatDataset(tsList)
newTrainDataSet = torch.utils.data.DataLoader(ts, batch_size=self.batchSize, shuffle=True,
num_workers=self.workersCount)
DNN = retrainModule.fineTune(self.modelPath, self.outputPath, self.datasetName, 100, self.caseFile)
if self.datasetName != "SAP":
#_, DNN = retrainModule.alexTrain(self.caseFile, 100, newTrainDataSet, bestModelPath, self.DNN, None)
#DNN = retrainModule.loadDNN(self.caseFile, bestModelPath)
transformedData = PathImageFolder(root=self.caseFile["testDataPath"], transform=dataTransform)
testData = torch.utils.data.DataLoader(transformedData, batch_size=self.batchSize, shuffle=True,
num_workers=self.workersCount)
testAccuracy, resultDictNew = retrainModule.alexTest(bestModelPath, testData, None, self.datasetName, DNN, False, None)
print(testAccuracy.item())
transformedData2 = PathImageFolder(root=self.caseFile["testDataPath"]+"_S", transform=dataTransform)
testData2 = torch.utils.data.DataLoader(transformedData2, batch_size=self.batchSize, shuffle=True,
num_workers=self.workersCount)
testAccuracy2, resultDictNew = retrainModule.alexTest(bestModelPath, testData2, None, self.datasetName, DNN, False, None)
print(testAccuracy2.item())
transformedData2 = PathImageFolder(root=self.caseFile["testDataPath"]+"_R", transform=dataTransform)
testData2 = torch.utils.data.DataLoader(transformedData2, batch_size=self.batchSize, shuffle=True,
num_workers=self.workersCount)
print(self.modelPath)
testAccuracy2, resultDictNew = retrainModule.alexTest(bestModelPath, testData2, None, self.datasetName, self.DNN, False, None)
print(testAccuracy2.item())
def retrainDNN(self):
if self.retrainFlag:
if self.retrieveAccuracy is not None:
self.caseFile["retrieveAccuracy"] = self.retrieveAccuracy
if self.retrainSet is not None:
self.caseFile["retrainSet"] = self.retrainSet
self.updateCaseFile()
retrainModule.run(self.caseFile)
self.caseFile = torch.load(self.caseFile["caseFile"])