-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdataSupplier.py
executable file
·1807 lines (1637 loc) · 71.9 KB
/
dataSupplier.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) IEE 2019-2020.
# Created by Hazem FAHMY, [email protected], SNT, 2019.
#
import subprocess as sp
import pathlib as pl
import dnnModels
import HeatmapModule
import testModule
#from searchModule import setX, setNewX, doImage
#import searchModule
#from assignModule import testModule, HeatmapModule
from imports import shutil, random, np, pd, math, glob, json, dlib, cv2, os, torch, Image, Variable, datasets, \
transforms, DataLoader, Dataset, SubsetRandomSampler, setupTransformer, normalize, isfile, join, exists, basename, \
dirname, makedirs, rmtree, subprocess, time
from torchvision import datasets, transforms, models
from torch.utils.data import DataLoader, Dataset, TensorDataset
from torch.utils.data.sampler import SubsetRandomSampler
import config as cfg
components = cfg.components
blenderPath = cfg.blenderPath
nVar = cfg.nVar
globalCounter = random.randint(1, 999999999)
import scipy.misc as sc
import random
import csv
import imageio
# components = ["mouth", "noseridge", "nose", "rightbrow", "righteye", "lefteye", "leftbrow"]
components = ["mouth"]
outputPath = "/Users/hazem.fahmy/Documents/HPD/"
#outputPath = "/home/users/hfahmy/DEEP/HPC/HPD/"
outputPath = "/Users/android/Documents/HPD/"
DIR = "/Users/hazem.fahmy/Documents/HPC/HUDD/runPy/"
#DIR = "/home/users/hfahmy/DEEP/HPC/HUDD/runPy/"
DIR = "/Users/android/Documents/HPC/HUDD/runPy/"
path = join(outputPath, "IEEPackage")
#import pandas as pd
import numpy as np
train_max_num = 8192+4096
test_max_num = 1024+512
real_max_num = 1024+512
total_epoch = 100
best_model_path = "./bst_model/kpmodel.pt"
loss_file_path = "./bst_model/loss.npy"
plot_results = "./results_kaggle"
labels = ["lefteyebrow", "righteyebrow", "lefteye", "righteye", "nose", "mouth"]
target_size = 128
iee_img_width = 376
iee_img_height = 240
cood_num = 27 #FIXME
#cood_num = 36 #FIXME
h_tol = 25
w_tol = 25
validRatio = 0.1
pinMemory = True
width = 128
height = 128
sigma = 5
gaussian_scale = 10.0
n_points = 64 #FIXME
batch_size = 64
data_random_seed = 3
gpu_id = 1
iee_train_data = "./dataset/ieetrain.npy"
iee_test_data = "./dataset/ieetest.npy"
iee_real_data = "./dataset/ieereal.npy"
FILE_EXT = '.jpg'
PATH = './train_model/'
def labelImage(imgPath):
margin1 = 10.0
margin2 = -10.0
margin3 = 10.0
margin4 = -10.0
configPath = join(dirname(imgPath), basename(imgPath).split(".png")[0] + ".npy")
configFile = np.load(configPath, allow_pickle=True)
configFile = configFile.item()
HP1 = configFile['config']['head_pose'][0]
HP2 = configFile['config']['head_pose'][1]
originalDst = None
if HP1 > margin1:
if HP2 > margin3:
originalDst = "BottomRight"
elif HP2 < margin4:
originalDst = "BottomLeft"
elif margin4 <= HP2 <= margin3:
originalDst = "BottomCenter"
elif HP1 < margin2:
if HP2 > margin3:
originalDst = "TopRight"
elif HP2 < margin4:
originalDst = "TopLeft"
elif margin4 <= HP2 <= margin3:
originalDst = "TopCenter"
elif margin2 <= HP1 <= margin1:
if HP2 > margin3:
originalDst = "MiddleRight"
elif HP2 < margin4:
originalDst = "MiddleLeft"
elif margin4 <= HP2 <= margin3:
originalDst = "MiddleCenter"
if originalDst is None:
print("cannot label img:", imgPath)
return originalDst
def getFileList(dirPath):
imgList = []
for src_dir, dirs, files in os.walk(dirPath):
for file_ in files:
if file_.endswith(".pt"):
imgList.append(file_)
return imgList
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
def cleanMake(path, flag):
if not exists(path):
makedirs(path)
else:
if flag:
rmtree(path)
makedirs(path)
def get_all_pngs(folder):
folder_f = folder + "/*.png"
f_list = glob.glob(folder_f)
return f_list
def get_label(file_name):
print("label file_name: ", file_name)
data = np.load(file_name, allow_pickle=True)
data = data.item()
label_value = np.zeros((1, cood_num * 2))
idx = 0
for ky in labels:
coods = np.array(data[ky])
# print("ky: ", ky, "coods: ", coods.shape)
coods = coods[coods[:, 0].argsort()]
for co in coods:
label_value[0, idx] = co[1]
label_value[0, idx + 1] = iee_img_height - co[2]
idx += 2
return label_value
def crop_img_lab(idx, faces, img, kps, evidence_path):
new_label = np.zeros_like(kps)
big_face = -np.inf
mx, my, mw, mh = 0, 0, 0, 0
for face in faces: # we only need to consider one face, fix this later
x = face.rect.left()
y = face.rect.top()
w = face.rect.right() - x
h = face.rect.bottom() - y
if w * h > big_face:
big_face = w * h
mx, my, mw, mh = x, y, w, h
sx_0 = max(mx - w_tol // 2, 0)
sx_1 = min(sx_0 + mw + w_tol, iee_img_width)
sy_0 = max(my - h_tol // 2, 0)
sy_1 = min(sy_0 + mh + h_tol * 2, iee_img_height)
assert sy_1 > sy_0
assert sx_1 > sx_0
new_img = img[sy_0:sy_1, sx_0:sx_1]
tmp_h, tmp_w = new_img.shape
new_label[0, ::2] = kps[0, ::2] - sx_0
new_label[0, 1::2] = kps[0, 1::2] - sy_0
new_label[new_label < 0] = 0
new_img = cv2.resize(new_img, (target_size, target_size), interpolation=cv2.INTER_CUBIC)
width_resc = float(target_size) / tmp_w
height_resc = float(target_size) / tmp_h
new_label[0, ::2] = new_label[0, ::2] * (width_resc)
new_label[0, 1::2] = new_label[0, 1::2] * (height_resc)
# new_label[0, [-4, -3, -2, -1]] = sx_0, sy_0, width_resc, height_resc
# new_img = new_img.reshape(1,int(target_size*target_size))
return new_img, new_label
def get_img(apng):
img = cv2.imread(apng)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
return img
def get_face_detector(weight_path):
face_detector = dlib.cnn_face_detection_model_v1(weight_path)
return face_detector
def get_data_kaggle(f_path, btest=False):
df = pd.read_csv(f_path)
df = df.fillna(-1)
df['Image'] = df['Image'].apply(lambda img: np.fromstring(img, sep=' '))
X = np.vstack(df['Image'].values)
X = X.astype(np.float32)
X = X / 255. # scale pixel values to [0, 1]
X = X.reshape(-1, 1, 96, 96) # return each images as 1 x 96 x 96
if not btest:
y = df[df.columns[:-1]].values
y = y.astype(np.float32)
else:
y = np.zeros((len(X)))
return X, y
def get_data(f_path, btest=False):
data = np.load(f_path, allow_pickle=True)
data = data.item()
X = data["Image"]
X = X.astype(np.float32)
X = X / 255.
X = X.reshape(-1, 1, width, height)
y = data["Label"]
y = y.astype(np.float32)
imageList = data["Origin"]
return X, y, imageList
def loadTestData(testdataPath: str, batchSize, workersCount, datasetName):
testData = torch.utils.data.DataLoader(
datasets.ImageFolder(root=testdataPath, transform=setupTransformer(datasetName)),
batch_size=batchSize, shuffle=True,
num_workers=workersCount)
return testData
def loadTrainData(bagPath, caseFile_, imagesList):
global caseFile
caseFile = caseFile_
trainDataSet = caseFile["trainDataSet"]
datasetName = caseFile["datasetName"]
if not exists(bagPath):
os.makedirs(bagPath)
imgClasses = trainDataSet.dataset.classes
for imgclass in imgClasses:
if not exists(join(bagPath, imgclass)):
os.makedirs(join(bagPath, imgclass))
imgLst = collectData(bagPath, imagesList)
#if retrainMode == "BL1":
# imgLst = BL1_Data(improvSet, bagPath, U, clsPath, net, datasetName)
#elif retrainMode == "BL4":
# imgLst = BL4_Data(improvSet, bagPath, net, datasetName)
ts = datasets.ImageFolder(root=bagPath, transform=setupTransformer(datasetName))
return ts, imgLst, caseFile
def IEE_HUDD(caseFile, outputSet):
components = caseFile["components"]
trainDataNpy = caseFile["trainDataNpy"]
improveDataNpy = caseFile["improveDataNpy"]
unsafeDataSet_X = []
retrainDataSet_X = []
unsafeDataSet_Y = []
retrainDataSet_Y = []
trainDataset = np.load(trainDataNpy, allow_pickle=True)
trainDataset = trainDataset.item()
a_data = trainDataset["data"]
b_data = trainDataset["label"]
for i in range(0, len(a_data)):
retrainDataSet_X.append(a_data[i])
retrainDataSet_Y.append(b_data[i])
ISdataset = np.load(improveDataNpy, allow_pickle=True)
ISdataset = ISdataset.item()
x_data = ISdataset["data"]
y_data = ISdataset["label"]
selected = list()
totalImages = []
numClusters = 0
if "retrainSet" not in caseFile:
for component in components:
newPath = join(caseFile["outputPathOriginal"], component, caseFile["RCC"],
"ClusterAnalysis_" + caseFile["clustMode"], "Assignments",
caseFile["assignMode"], caseFile["selectionMode"])
clsWithAssImages = torch.load(join(newPath, "clusterwithAssignedImages.pt"))
caseFile["assignPTFile"] = join(newPath, "clusterwithAssignedImages.pt")
clusterUCs, totalAssigned, totalUc, totalUb, Ub = getUCs(caseFile, 0.3) #U4/U5
# clusterUCs, totalAssigned, totalUc, totalUb, Ub = getUCs(caseFile, 0.1) #U7/U8
for clusterID in clsWithAssImages['clusters']:
closestClusterName = torch.load(join(newPath, "improveRCCDists", "closestClusterName.pt"))
closestClusterDist = torch.load(join(newPath, "improveRCCDists", "closestClusterDist.pt"))
if 'assigned' in clsWithAssImages['clusters'][clusterID]:
unsafeImages = []
clustLen = len(clsWithAssImages['clusters'][clusterID]['assigned'])
if clustLen > 1:
toNormalize = list()
imagesList = list()
breakFlag = False
for order in range(0, len(clsWithAssImages['clusters'])):
for _ in caseFile["retrainList"]:
candidateImage = min(closestClusterDist[order].keys(),
key=(lambda k: closestClusterDist[order][k]))
candidateClusterID = closestClusterName[order][candidateImage]
dif = closestClusterDist[order][candidateImage]
closestClusterDist[order][candidateImage] = 1e9
fileFullName = basename(candidateImage)
fileIndxName = fileFullName.split(".")[0]
fileIndex = int(fileIndxName.split("I")[1]) - 1
if candidateClusterID == clusterID:
if len(unsafeImages) < clusterUCs[clusterID]:
unsafeDataSet_X.append(x_data[fileIndex])
unsafeDataSet_Y.append(y_data[fileIndex])
retrainDataSet_X.append(x_data[fileIndex])
retrainDataSet_Y.append(y_data[fileIndex])
imagesList.append(fileIndex)
selected.append(fileIndex)
unsafeImages.append(fileIndex)
totalImages.append(fileIndex)
toNormalize.append(dif)
else:
breakFlag = True
if breakFlag:
break
if len(imagesList) > 1:
probList = list()
probList2 = list()
probList3 = list()
for i, val in enumerate(toNormalize):
probList.append(1 - (val / sum(toNormalize)))
for i, val in enumerate(probList):
if i == 0:
offset = 0
else:
offset = probList2[i - 1]
probList2.append(val + offset)
for i, val in enumerate(probList2):
if (max(probList2) - min(probList2)) == 0:
print(unsafeImages, toNormalize, probList, probList2)
probList3.append((val - min(probList2)) / (max(probList2) - min(probList2)))
while len(unsafeImages) < Ub:
randNum = random.uniform(0, 1)
for z in range(0, len(probList)):
if randNum < probList[z]:
if len(unsafeImages) < Ub:
unsafeDataSet_X.append(x_data[imagesList[z]])
unsafeDataSet_Y.append(y_data[imagesList[z]])
retrainDataSet_X.append(x_data[imagesList[z]])
retrainDataSet_Y.append(y_data[imagesList[z]])
unsafeImages.append(imagesList[z])
totalImages.append(imagesList[z])
else:
while len(unsafeImages) < Ub:
fileFullName = basename(clsWithAssImages['clusters'][clusterID]['assigned'][0])
fileIndxName = fileFullName.split(".")[0]
fileIndex = int(fileIndxName.split("I")[1]) - 1
unsafeDataSet_X.append(x_data[fileIndex])
unsafeDataSet_Y.append(y_data[fileIndex])
retrainDataSet_X.append(x_data[fileIndex])
retrainDataSet_Y.append(y_data[fileIndex])
unsafeImages.append(fileIndex)
totalImages.append(fileIndex)
clusterDistrib = list()
for clusterID in clsWithAssImages['clusters']:
if 'assigned' in clsWithAssImages['clusters'][clusterID]:
numClusters += 1
clustLen = len(clsWithAssImages['clusters'][clusterID]['assigned'])
clusterDistrib.append(clustLen)
#print(component, "Assigned Images to Clusters Distribution:", clusterDistrib)
retrainDataSet_X1 = np.array(retrainDataSet_X)
retrainDataSet_Y1 = np.array(retrainDataSet_Y)
print("Total Number of Clusters with Assigned images:", numClusters)
print("Size of UnsafeSet:", len(selected))
print("Size of Bagged UnsafeSet:", len(totalImages))
print("Size of RetrainSet:", str(len(retrainDataSet_X)))
retrainDataSet = {"data": retrainDataSet_X1, "label": retrainDataSet_Y1}
np.save(outputSet, retrainDataSet)
def IEE_BL2(caseFile, outputSet):
components = caseFile["components"]
trainDataNpy = caseFile["trainDataNpy"]
improveDataNpy = caseFile["improveDataNpy"]
retrainDataSet_X = []
retrainDataSet_Y = []
trainDataset = np.load(trainDataNpy, allow_pickle=True)
trainDataset = trainDataset.item()
a_data = trainDataset["data"]
b_data = trainDataset["label"]
for i in range(0, len(a_data)):
retrainDataSet_X.append(a_data[i])
retrainDataSet_Y.append(b_data[i])
ISdataset = np.load(improveDataNpy, allow_pickle=True)
ISdataset = ISdataset.item()
x_data = ISdataset["data"]
y_data = ISdataset["label"]
BLDataSet_X = []
BLDataSet_Y = []
for i in range(0, len(a_data)):
BLDataSet_X.append(a_data[i])
BLDataSet_Y.append(b_data[i])
numClusters = 0
totalSelectedImages = []
selected = []
totalUcCombined = 0
totalUbCombined = 0
for component in components:
newPath = join(caseFile["outputPathOriginal"], component, caseFile["RCC"],
"ClusterAnalysis_" + caseFile["clustMode"], "Assignments",
caseFile["assignMode"], caseFile["selectionMode"])
clsWithAssImages = torch.load(join(newPath, "clusterwithAssignedImages.pt"))
caseFile["assignPTFile"] = join(newPath, "clusterwithAssignedImages.pt")
clusterUCs, totalAssigned, totalUc, totalUb, Ub = getUCs(caseFile, 0.3)
totalUcCombined += totalUc
totalUbCombined += totalUb
clusterDistrib = list()
for clusterID in clsWithAssImages['clusters']:
if 'assigned' in clsWithAssImages['clusters'][clusterID]:
clustLen = len(clsWithAssImages['clusters'][clusterID]['assigned'])
clusterDistrib.append(clustLen)
numClusters += 1
if "retrainSet" not in caseFile:
totalSelectedComponentImages = []
for i in range(0, totalUcCombined):
imgID = random.randint(0, len(x_data) - 1)
BLDataSet_X.append(x_data[imgID])
BLDataSet_Y.append(y_data[imgID])
selected.append(imgID)
totalSelectedImages.append(imgID)
totalSelectedComponentImages.append(imgID)
while len(totalSelectedComponentImages) < totalUbCombined:
imgID = random.randint(0, len(totalSelectedComponentImages) - 1)
BLDataSet_X.append(x_data[totalSelectedComponentImages[imgID]])
BLDataSet_Y.append(y_data[totalSelectedComponentImages[imgID]])
totalSelectedImages.append(totalSelectedComponentImages[imgID])
totalSelectedComponentImages.append(totalSelectedComponentImages[imgID])
print("Total Number of Clusters with Assigned images:", numClusters)
print("Total UnsafeSet:", len(selected))
print("Total Bagged UnsafeSet:", len(totalSelectedImages))
print("Size of RetrainSet:", str(len(BLDataSet_X)))
BLDataSet_X1 = np.array(BLDataSet_X)
BLDataSet_Y1 = np.array(BLDataSet_Y)
BLDataSet = {"data": BLDataSet_X1, "label": BLDataSet_Y1}
np.save(outputSet, BLDataSet)
def IEE_BL1(caseFile, outputSet, errList):
components = caseFile["components"]
trainDataNpy = caseFile["trainDataNpy"]
improveDataNpy = caseFile["improveDataNpy"]
retrainDataSet_X = []
retrainDataSet_Y = []
trainDataset = np.load(trainDataNpy, allow_pickle=True)
trainDataset = trainDataset.item()
a_data = trainDataset["data"]
b_data = trainDataset["label"]
for i in range(0, len(a_data)):
retrainDataSet_X.append(a_data[i])
retrainDataSet_Y.append(b_data[i])
ISdataset = np.load(improveDataNpy, allow_pickle=True)
ISdataset = ISdataset.item()
x_data = ISdataset["data"]
y_data = ISdataset["label"]
BLDataSet_X = []
BLDataSet_Y = []
for i in range(0, len(a_data)):
BLDataSet_X.append(a_data[i])
BLDataSet_Y.append(b_data[i])
numClusters = 0
totalSelectedImages = []
imageListx = pd.read_csv(caseFile["improveCSV"])
imageList = []
selected = []
for index, row in imageListx.iterrows():
result = "Correct"
if row["result"] == "Wrong":
# #if row["worst_component"] == component:
result = "Wrong"
imageList.append(result)
totalUcCombined = 0
totalUbCombined = 0
for component in components:
newPath = join(caseFile["outputPathOriginal"], component, caseFile["RCC"],
"ClusterAnalysis_" + caseFile["clustMode"], "Assignments",
caseFile["assignMode"], caseFile["selectionMode"])
clsWithAssImages = torch.load(join(newPath, "clusterwithAssignedImages.pt"))
caseFile["assignPTFile"] = join(newPath, "clusterwithAssignedImages.pt")
clusterUCs, totalAssigned, totalUc, totalUb, Ub = getUCs(caseFile, 0.3)
totalUcCombined += totalUc
totalUbCombined += totalUb
clusterDistrib = list()
for clusterID in clsWithAssImages['clusters']:
if 'assigned' in clsWithAssImages['clusters'][clusterID]:
clustLen = len(clsWithAssImages['clusters'][clusterID]['assigned'])
clusterDistrib.append(clustLen)
numClusters += 1
if "retrainSet" not in caseFile:
totalSelectedComponentImages = []
totalSelectedComponentImages2 = []
for i in range(0, totalUcCombined):
imgID = random.randint(0, len(imageList) - 1)
totalSelectedComponentImages.append(imgID)
print("Total Selected:", len(totalSelectedComponentImages))
for imgID in totalSelectedComponentImages:
if errList[imgID] == "Wrong":
BLDataSet_X.append(x_data[imgID])
BLDataSet_Y.append(y_data[imgID])
totalSelectedImages.append(imgID)
selected.append(imgID)
totalSelectedComponentImages2.append(imgID)
print("Total Failing:", len(totalSelectedComponentImages2))
if len(totalSelectedComponentImages2) > 0:
while len(totalSelectedComponentImages2) < totalUbCombined:
imgID = random.randint(0, len(totalSelectedComponentImages2) - 1)
BLDataSet_X.append(x_data[imgID])
BLDataSet_Y.append(y_data[imgID])
totalSelectedImages.append(imgID)
totalSelectedComponentImages2.append(imgID)
print("Total Number of Clusters with Assigned images:", numClusters)
print("Total UnsafeSet:", len(totalSelectedImages))
print("Total Bagged UnsafeSet:", len(totalSelectedImages))
print("Size of RetrainSet:", str(len(BLDataSet_X)))
BLDataSet_X1 = np.array(BLDataSet_X)
BLDataSet_Y1 = np.array(BLDataSet_Y)
BLDataSet = {"data": BLDataSet_X1, "label": BLDataSet_Y1}
np.save(outputSet, BLDataSet)
def loadIEETrainData(caseFile, outputSet, errList):
if caseFile["retrainMode"].startswith("HUDD"):
IEE_HUDD(caseFile, outputSet)
elif caseFile["retrainMode"] == "BL2":
IEE_BL2(caseFile, outputSet)
elif caseFile["retrainMode"] == "BL1":
IEE_BL1(caseFile, outputSet, errList)
else:
IEE_fineTune(caseFile, outputSet)
def generateSSEData():
global clsWithAssImages
print("Closest-SSE + Random Bagging")
clusterUCs, totalAssigned, totalUc, totalUb, Ub = getUCs(caseFile, 0.3) #U4/U5
# clusterUCs, totalAssigned, totalUc, totalUb, Ub = getUCs(caseFile, 0.1) #U7/U8
outputPath = caseFile["outputPath"]
selectedLayer = caseFile["selectedLayer"]
area = basename(dirname(outputPath))
npyPath = join(dirname(outputPath), "ieeimprove.npy")
trainHeatmaps = join(caseFile["filesPath"], "trainHeatmaps", selectedLayer)
testHM, _ = HeatmapModule.collectHeatmaps(caseFile["filesPath"], selectedLayer)
totalImages = []
for clusterID in clsWithAssImages['clusters']:
if 'assigned' in clsWithAssImages['clusters'][clusterID]:
unsafeImages = []
selectedSSE = {}
clustLen = len(clsWithAssImages['clusters'][clusterID]['assigned'])
if clustLen > 0:
Uc = clusterUCs[clusterID]
if Uc < clustLen:
for img in clsWithAssImages['clusters'][clusterID]['assigned']:
SSE = 0
imgExt = "." + str(basename(img).split(".")[1])
imgName = str(basename(img).split(".")[0])
imgClass = str(basename(dirname(img)))
HMFile = join(trainHeatmaps, imgName + "_" + imgClass + ".pt")
heatMap = HeatmapModule.safeHM(HMFile, int(selectedLayer.replace("Layer", "")), img, net,
caseFile["datasetName"], outputPath, False, area, npyPath, imgExt, None)
for testImage in clsWithAssImages['clusters'][clusterID]['members']:
SSE += HeatmapModule.doDistance(heatMap, testHM[testImage], caseFile["metric"]) ** 2
selectedSSE[img] = SSE
bestSSEimage = min(selectedSSE.keys(), key=(lambda k: selectedSSE[k]))
unsafeImages.append(bestSSEimage)
totalImages.append(bestSSEimage)
del selectedSSE[bestSSEimage]
return totalImages
def generateSmartBaggingEntropy():
global clsWithAssImages
#print("SmartBagging")
clusterUCs, totalAssigned, totalUc, totalUb, Ub = getUCs(caseFile, 0.3) #U4/U5
#clusterUCs, totalAssigned, totalUc, totalUb, Ub = getUCs(caseFile, 0.1) #U7/U8
totalImages = []
unsafeImages = []
closestClusterDist = torch.load(join(caseFile["improveRCCDists"], "closestClusterDist.pt"))
toNormalize = list()
imagesList = list()
for _ in caseFile["retrainList"]:
candidateImage = max(closestClusterDist, key=closestClusterDist.get)
E = closestClusterDist[candidateImage]
closestClusterDist[candidateImage] = 1e9
if len(unsafeImages) < totalUc:
imagesList.append(candidateImage)
toNormalize.append(E)
totalImages.append(candidateImage)
unsafeImages.append(candidateImage)
else:
break
probList = list()
probList2 = list()
probList3 = list()
for i, val in enumerate(toNormalize):
probList.append(1 - (val/sum(toNormalize)))
for i, val in enumerate(probList):
if i == 0:
offset = 0
else:
offset = probList2[i-1]
probList2.append(val + offset)
for i, val in enumerate(probList2):
if (max(probList2) - min(probList2)) == 0:
print(unsafeImages, toNormalize, probList, probList2)
probList3.append((val - min(probList2)) / (max(probList2) - min(probList2)))
while len(unsafeImages) < Ub:
randNum = random.uniform(0, 1)
for z in range(0, len(probList)):
if randNum < probList[z]:
totalImages.append(imagesList[z])
unsafeImages.append(imagesList[z])
return totalImages
def generateHMEntropy():
#print("Entropy-Bagging")
global clsWithAssImages
clusterUCs, totalAssigned, totalUc, totalUb, Ub = getUCs(caseFile, 0.3)
#print("Ub", math.ceil(Ub))
totalImages = []
a = 0
imagesEntropy = torch.load(join(caseFile["improveRCCDists"], "imagesEntropy.pt"))
for clusterID in clsWithAssImages['clusters']:
a += 1
if 'assigned' in clsWithAssImages['clusters'][clusterID]:
unsafeImages = []
clustLen = len(clsWithAssImages['clusters'][clusterID]['assigned'])
if clustLen > 1:
imagesList = list()
toNormalize = list()
maxi = 0
while maxi > -1e9:
candidateImage = max(imagesEntropy.keys(), key=(lambda k: imagesEntropy[k]))
maxi = imagesEntropy[candidateImage]
imagesEntropy[candidateImage] = -1e9
if len(unsafeImages) < clusterUCs[clusterID]:
if len(unsafeImages) < Ub:
imagesList.append(candidateImage)
toNormalize.append(maxi)
totalImages.append(candidateImage)
unsafeImages.append(candidateImage)
if len(imagesList) > 1:
probList = list()
probList2 = list()
probList3 = list()
for i, val in enumerate(toNormalize):
probList.append(1 - (val/sum(toNormalize)))
for i, val in enumerate(probList):
if i == 0:
offset = 0
else:
offset = probList2[i-1]
probList2.append(val + offset)
for i, val in enumerate(probList2):
if (max(probList2) - min(probList2)) == 0:
print(unsafeImages, toNormalize, probList, probList2)
probList3.append((val - min(probList2)) / (max(probList2) - min(probList2)))
while len(unsafeImages) < Ub:
randNum = random.uniform(0, 1)
for z in range(0, len(probList)):
if randNum < probList[z]:
if len(unsafeImages) < Ub:
totalImages.append(imagesList[z])
unsafeImages.append(imagesList[z])
else:
while len(unsafeImages) < Ub:
totalImages.append(clsWithAssImages['clusters'][clusterID]['assigned'][0])
unsafeImages.append(clsWithAssImages['clusters'][clusterID]['assigned'][0])
totalImages = totalImages[0:math.ceil(totalUb)]
#print("UnsafeSet:", len(totalImages))
return totalImages
def generateTestSet(caseFile, bagPath):
clsWithAssImages = torch.load(caseFile["clsPath"])
csvPath = caseFile["testCSV"]
retrainData = caseFile["testDataSet"]
imgClasses = retrainData.dataset.classes
imgListX = {}
imageList = pd.read_csv(csvPath, names=["image", "result", "expected", "predicted"].append(imgClasses))
for index, row in imageList.iterrows():
imgListX[row["image"]] = 0
totalImages = []
copyImages = []
maxUc = 0
for clusterID in clsWithAssImages['clusters']:
if len(clsWithAssImages['clusters'][clusterID]['members']) > maxUc:
maxUc = len(clsWithAssImages['clusters'][clusterID]['members'])
for clusterID in clsWithAssImages['clusters']:
unsafeImages = []
i = 0
for img in clsWithAssImages['clusters'][clusterID]['members']:
unsafeImages.append(img)
totalImages.append(img)
i += 1
while len(unsafeImages) < maxUc:
index = random.randint(0, len(unsafeImages) - 1)
unsafeImages.append(unsafeImages[index])
totalImages.append(unsafeImages[index])
copyImages.append(unsafeImages[index])
dupCount = 0
imgExt = caseFile["imgExt"]
for img in copyImages:
testImage = basename(img)
imgName = str(testImage.split("_")[1])
imgClass = str(testImage.split("_")[2])
if len(imgName.split("_")) > 2:
imgName = imgName.split("_")[1] + "_" + imgName.split("_")[2]
imgClass = str(testImage.split("_")[3])
dstDir = join(bagPath, imgClass)
if not exists(dstDir):
os.makedirs(dstDir)
dstFile = join(dstDir, testImage)
if exists(dstFile):
dstFile = join(dstDir, imgName + "_" + str(dupCount) + imgExt)
dupCount += 1
if testImage.split("_")[0] == "Test":
srcFile = join(caseFile["testDataPath"], imgClass, imgName + imgExt)
else:
srcFile = join(caseFile["trainDataPath"], imgClass, imgName + imgExt)
if srcFile in imgListX:
del imgListX[srcFile]
shutil.copy(srcFile, dstFile)
#for srcFile in imgListX:
# dstDir = join(bagPath, basename(dirname(srcFile)))
# if not exists(dstDir):
# os.makedirs(dstDir)
# dstFile = join(dstDir, basename(srcFile))
# if exists(dstFile):
# dstFile = join(dstDir, str((basename(srcFile)).split(".")[0]) + "_" + str(dupCount) + imgExt)
# dupCount += 1
# shutil.copy(srcFile, dstFile)
def generateSEDE(clsWithAssImages):
eval_imgs = 50
totalImages = []
for cID in clsWithAssImages['clusters']:
print(cID)
cFile = join(caseFile["filesPath"], "GeneratedImages", str(cID), "config.pt")
csvPath = join(caseFile["filesPath"], "GeneratedImages", str(cID), "results.csv")
if isfile(cFile) and isfile(csvPath):
cPART = torch.load(cFile)
else:
continue
imageList = pd.read_csv(csvPath)
#paramNameList = ["cam_dir0", "cam_dir1", "cam_dir2", "cam_loc0", "cam_loc1", "cam_loc2", "lamp_loc0", "lamp_loc1",
# "lamp_loc2", "lamp_col0", "lamp_col1", "lamp_col2", "lamp_dir0", "lamp_dir1", "lamp_dir2",
# "lamp_eng", "head_pose0", "head_pose1", "head_pose2", "pose"] #IEE V1
paramNameList = ["head0", "head1", "head2", "lampcol0", "lampcol1",
"lampcol2", "lamploc0", "lamploc1", "lamploc2", "lampdir0", "lampdir1", "lampdir2", "cam",
"age", "hue", "iris", "sat", "val", "freckle", "oil", "veins", "eyecol", "gender"] #IEE V2
paramDict = {}
for j in range(0, nVar):
paramDict[paramNameList[j]] = []
for index, row in imageList.iterrows():
if not row["DNNResult"]:
for i in range(0, nVar):
paramDict[paramNameList[i]].append(float(row[paramNameList[i]]))
caseFile["SimDataPath"] = join(caseFile["filesPath"], "Pool")
outDir = join(caseFile["filesPath"], "Evaluation", str(cID))
if not exists(outDir):
makedirs(outDir)
n = 0
for j in range(0, len(cPART['rules'])):
toEval = int(cPART['portions'][j] * int(eval_imgs))
total = 0
while total < toEval:
print(eval_imgs - total, end="\r")
#x = setX(1, "R")
x = setX_2(1, "R")
#x = setNewX(x, paramDict, paramNameList, cPART['rules'][j], cPART['val1x'][j], cPART['val2x'][j])
#imgPath, F = generateAnImage(x, caseFile)
imgPath, F = generateHuman(x, caseFile)
if F:
imgPath += ".png"
N, DNNResult, P, L, D, _ = doImage(imgPath, caseFile, None)
# DNNResult2, pred = testModelForImg(caseFile["DNN2"], L, imgPath, caseFile)
if DNNResult:
n += 1
# if DNNResult2:
# n2 += 1
total += 1
totalImages.append(join(dirname(imgPath), L, basename(imgPath)))
return totalImages
def generateSmartBaggingHM(imgList):
print("HM-Bagging")
global clsWithAssImages
#print("SmartBagging")
clusterUCs, totalAssigned, totalUc, totalUb, Ub = getUCs(caseFile, 1) #U4/U5
#clusterUCs, totalAssigned, totalUc, totalUb, Ub = getUCs(caseFile, 0.1) #U7/U8
if len(imgList) == 0:
totalImages = []
a = 0
for clusterID in clsWithAssImages['clusters']:
a += 1
closestClusterName = torch.load(join(caseFile["improveRCCDists"], "closestClusterName.pt"))
closestClusterDist = torch.load(join(caseFile["improveRCCDists"], "closestClusterDist.pt"))
if 'assigned' in clsWithAssImages['clusters'][clusterID]:
unsafeImages = []
clustLen = len(clsWithAssImages['clusters'][clusterID]['assigned'])
if clustLen > 1:
# Uc = clusterUCs[clusterID]
# i = 0
# while len(unsafeImages) < Uc:
# if i >= len(clsWithAssImages['clusters'][clusterID]['assigned']):
# i = 0
# unsafeImages.append(clsWithAssImages['clusters'][clusterID]['assigned'][i])
# totalImages.append(clsWithAssImages['clusters'][clusterID]['assigned'][i])
# i = 0
# while len(unsafeImages) < Ub:
# if i >= len(clsWithAssImages['clusters'][clusterID]['assigned']):
# i = 0
# unsafeImages.append(clsWithAssImages['clusters'][clusterID]['assigned'][i])
# totalImages.append(clsWithAssImages['clusters'][clusterID]['assigned'][i])
# i += 1
toNormalize = list()
imagesList = list()
breakFlag = False
for order in range(0, len(clsWithAssImages['clusters'])):
print(str(int(100.00*(a/len(clsWithAssImages['clusters'])))) + "%",
str(int(100.00*(order/len(clsWithAssImages['clusters'])))) + "%", end="\r")
for _ in caseFile["retrainList"]:
candidateImage = min(closestClusterDist[order].keys(),
key=(lambda k: closestClusterDist[order][k]))
candidateClusterID = closestClusterName[order][candidateImage]
dif = closestClusterDist[order][candidateImage]
closestClusterDist[order][candidateImage] = 1e9
if candidateClusterID == clusterID:
if len(unsafeImages) < clusterUCs[clusterID]:
imagesList.append(candidateImage)
toNormalize.append(dif)
totalImages.append(candidateImage)
unsafeImages.append(candidateImage)
else:
breakFlag = True
if breakFlag:
break
#if False:
if len(imagesList) > 1:
probList = list()
probList2 = list()
probList3 = list()
for i, val in enumerate(toNormalize):
probList.append(1 - (val/sum(toNormalize)))
for i, val in enumerate(probList):
if i == 0:
offset = 0
else:
offset = probList2[i-1]
probList2.append(val + offset)
for i, val in enumerate(probList2):
if (max(probList2) - min(probList2)) == 0:
print(unsafeImages, toNormalize, probList, probList2)
probList3.append((val - min(probList2)) / (max(probList2) - min(probList2)))
while len(unsafeImages) < Ub:
randNum = random.uniform(0, 1)
for z in range(0, len(probList)):
if randNum < probList[z]:
totalImages.append(imagesList[z])
unsafeImages.append(imagesList[z])
else:
while len(unsafeImages) < Ub:
totalImages.append(clsWithAssImages['clusters'][clusterID]['assigned'][0])
unsafeImages.append(clsWithAssImages['clusters'][clusterID]['assigned'][0])
#print(clusterID, len(unsafeImages), len(totalImages))
else:
totalImages = imgList
totalImages = totalImages[0:math.ceil(totalUb)]
return totalImages
def generateRandomBagging():
global clsWithAssImages
clusterUCs, totalAssigned, totalUc, totalUb, Ub = getUCs(caseFile, 0.3) #U4/U5
#clusterUCs, totalAssigned, totalUc, totalUb, Ub = getUCs(caseFile, 0.1) #U7/U8
totalImages = []
#print("RandomBagging")
for clusterID in clsWithAssImages['clusters']:
if 'assigned' in clsWithAssImages['clusters'][clusterID]:
unsafeImages = []
clustLen = len(clsWithAssImages['clusters'][clusterID]['assigned'])
if clustLen > 0:
Uc = clusterUCs[clusterID]
i = 0
while len(unsafeImages) < Uc:
unsafeImages.append(clsWithAssImages['clusters'][clusterID]['assigned'][i])
totalImages.append(clsWithAssImages['clusters'][clusterID]['assigned'][i])
i += 1
while len(unsafeImages) < Ub:
index = random.randint(0, len(unsafeImages) - 1)
unsafeImages.append(unsafeImages[index])
totalImages.append(unsafeImages[index])
totalImages = totalImages[0:totalUb]
return totalImages
def generateBL2():
totalImages = []
clusterUCs, totalAssigned, totalUc, totalUb, Ub = getUCs(caseFile, 0.3)
improvFiles = caseFile["retrainList"]
while len(totalImages) < math.ceil(totalUc):
index = random.randint(0, len(improvFiles) - 1)
totalImages.append(improvFiles[index])
while len(totalImages) < math.ceil(totalUb):
index = random.randint(0, len(totalImages) - 1)
totalImages.append(totalImages[index])
totalImages = totalImages[0:math.ceil(totalUb)]
return totalImages
def generateBL1():
totalImages = []
clusterUCs, totalAssigned, totalUc, totalUb, Ub = getUCs(caseFile, 0.3)
net = loadDNN(caseFile, caseFile["modelPath"])
net = net.eval()
improvFiles = caseFile["retrainList"]
improvFiles = improvFiles[0:math.ceil(totalUc)]
dumbImages = []
while len(dumbImages) < totalUc:
if len(totalImages) < math.ceil(totalUb):
imgID = random.randint(0, len(improvFiles) - 1)
dumbImages.append(improvFiles[imgID])
fileClass = basename(dirname(improvFiles[imgID]))
if not (testModule.testModelForImg(net, fileClass, improvFiles[imgID], caseFile)):
totalImages.append(improvFiles[imgID])
print("Total Failing:", len(totalImages))
while len(totalImages) < math.ceil(totalUb):
index = random.randint(0, len(totalImages) - 1)
totalImages.append(totalImages[index])
totalImages = totalImages[0:math.ceil(totalUb)]
return totalImages
def generateBLE():
clusterUCs, totalAssigned, totalUc, totalUb, Ub = getUCs(caseFile, 0.3)
imagesEntropy = torch.load(join(caseFile["improveRCCDists"], "imagesEntropy.pt"))
entropyList = list()
for _ in imagesEntropy:
candidateImage = max(imagesEntropy.keys(), key=(lambda k: imagesEntropy[k]))
imagesEntropy[candidateImage] = 0
entropyList.append(candidateImage)
totalImages = entropyList[0:math.ceil(totalUc)]
while len(totalImages) < math.ceil(totalUb):
index = random.randint(0, len(totalImages) - 1)
totalImages.append(totalImages[index])
totalImages = totalImages[0:math.ceil(totalUb)]
return totalImages
def collectData(bagPath, imagesList):
global caseFile
global clsWithAssImages
net = loadDNN(caseFile, caseFile["modelPath"])
net = net.eval()
mode = caseFile["retrainMode"]
clsPath = caseFile["assignPTFile"]
if imagesList is None:
imgLst = list()
else:
imgLst = imagesList
totalImages = []
HUDDUnsafeSet = {}
HUDDPath = join(caseFile["filesPath"], "UnsafeSet.pt")
if mode.startswith("SEDE"):
clsWithAssImages = torch.load(join(caseFile["filesPath"], "ClusterAnalysis_" + str(caseFile["clustMode"]),
caseFile["selectedLayer"] + ".pt"))
totalImages = generateSEDE(clsWithAssImages)
else:
clsWithAssImages = torch.load(clsPath)
if mode.startswith("HUDD"):
#if isfile(HUDDPath):