-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMachineLearningLibrary.py
More file actions
2056 lines (1557 loc) · 99.7 KB
/
MachineLearningLibrary.py
File metadata and controls
2056 lines (1557 loc) · 99.7 KB
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
import os.path
import shutil
import numpy as np
import numpy.matlib
from imageio import imread, imsave
from PIL import Image
import imageio
import scipy
import scipy.stats
import shelve
import sklearn
import sklearn.preprocessing
import sklearn.svm
import sklearn.decomposition
import sklearn.calibration
import sklearn.metrics
import sklearn.feature_selection
from sklearn.feature_selection import SequentialFeatureSelector
from sklearn.feature_selection import SelectKBest, f_classif
import skimage.feature
import skimage.color
import skimage.transform
from skimage import draw
from skimage.transform import resize as imresize
from skimage.util import img_as_ubyte
import xlsxwriter
from openpyxl.utils import get_column_letter, column_index_from_string
import matplotlib.pyplot as plt
class ML(object):
# Initialized all variables describing the folder structure
def __init__(self):
# Folders
self.num = 1
self.resizedImageFolder = 'StandardizedData'
self.lbpFolder = 'LocalBinaryPatterns'
self.vwMatricesFolder_CrossValidation = 'LDAMatrices_CrossValidation'
self.vwMatricesFolder = 'LDAMatrices'
self.featuresFolder_CrossValidation = 'Features_CrossValidation'
self.featuresFolder = 'Features'
self.landmarksFolder = 'Points_GT'
self.resultsFolder = 'Results'
# Files
self.crossValidationModelName = 'CrossValidation'
self.crossValidationExcelName = 'CrossValidation.xlsx'
self.finalLDAMatricesName = 'LDAMatrices'
self.finalModelName = 'Model'
self.finalModelExcelName = 'FinalModelStatistics.xlsx'
# Class names
self.negativeClassName = 'Normal'
self.positiveClassName = 'Syndromic'
# Configuration
self.featureSelector = 'RecursiveElimination' # options = 'MCFS_p' or 'RecursiveElimination'
self.LBP_list = np.array([[16,4],[32,8],[64,12]]) # LBP resolutions [elements, radius]
self.Ws = 5 # Windows size for the LBP calculation
self.numberOfLandmarks = 44
self.threshold = 0.5
self.optimizeThreshold = False
self.verbose = False
self.asymmetry = False
self.finalNumberOfFeatures = 30
#################################################################################
## THE FUNCTIONS BELOW ARE THE CLASS INTERFACE (PUBLIC ACCESS)
#################################################################################
# This will 1) Create the directory tree 2) Create and save standardized images and landmarks, 3) Save local binary patterns
def Initialize(self, negativeClassImageFolder, negativeClassLandmarkFolder, positiveClassImageFolder, positiveClassLandmarkFolder, workingPath, removeExistingFiles=False):
# creating the folder structure
self.createOutputFolderStructure(workingPath, removeExistingFiles=removeExistingFiles)
# Standardizing the negative class
self.rescaleImagesAlignLandmarks(negativeClassImageFolder, negativeClassLandmarkFolder, os.path.join(workingPath, self.resizedImageFolder, self.negativeClassName))
# Standardizing the positive class
self.rescaleImagesAlignLandmarks(positiveClassImageFolder, positiveClassLandmarkFolder, os.path.join(workingPath, self.resizedImageFolder, self.positiveClassName))
# Calculating and saving the local binary patterns
self.SaveLocalBinaryPatterns(workingPath)
# Saves all features for cross validations
def CalculateFeaturesForCrossValidation(self, workingPath):
self.CalculateLDAMatrices_CrossValidation(workingPath)
negativeImageFolder = os.path.join(workingPath, self.resizedImageFolder, self.negativeClassName)
negativeLandmarkFolder = os.path.join(workingPath, self.resizedImageFolder, self.negativeClassName, self.landmarksFolder)
positiveImageFolder = os.path.join(workingPath, self.resizedImageFolder, self.positiveClassName)
positiveLandmarkFolder = os.path.join(workingPath, self.resizedImageFolder, self.positiveClassName, self.landmarksFolder)
listOfImages = []
landmarks = np.ndarray([0, self.numberOfLandmarks, 2], dtype=np.float32)
img_list = sorted(os.listdir(negativeImageFolder))
for f_i in range(len(img_list)):
fileName, fileExtension = os.path.splitext(img_list[f_i])
if fileExtension.lower() == '.jpg':
# Adding the image to the list
image = imread(os.path.join(negativeImageFolder, img_list[f_i]))
# Adding the landmarks
landmarks = np.load(os.path.join(negativeLandmarkFolder, fileName + '.npy'))[:self.numberOfLandmarks, :]
# Read V and W matrices for this patient
vWDictionary = {}
shelveDictionary = shelve.open(os.path.join(workingPath, self.vwMatricesFolder_CrossValidation, self.negativeClassName+'_'+fileName))
for key, value in shelveDictionary.items():
vWDictionary[key] = value
shelveDictionary.close()
features, description = self.GetFeatures([image], landmarks.reshape(1,landmarks.shape[0], landmarks.shape[1]), vWDictionary)
featureDictionary = shelve.open(os.path.join(workingPath, self.featuresFolder_CrossValidation, self.negativeClassName+'_'+fileName))
featureDictionary['features'] = features
featureDictionary['description'] = description
featureDictionary.close()
img_list = sorted(os.listdir(positiveImageFolder))
for f_i in range(len(img_list)):
fileName, fileExtension = os.path.splitext(img_list[f_i])
if fileExtension.lower() == '.jpg':
# Adding the image to the list
image = imread(os.path.join(positiveImageFolder, img_list[f_i]))
# Adding the landmarks
landmarks = np.load(os.path.join(positiveLandmarkFolder, fileName + '.npy'))[:self.numberOfLandmarks, :]
# Read V and W matrices for this patient
vWDictionary = {}
shelveDictionary = shelve.open(os.path.join(workingPath, self.vwMatricesFolder_CrossValidation, self.positiveClassName+'_'+fileName))
for key, value in shelveDictionary.items():
vWDictionary[key] = value
shelveDictionary.close()
features, description = self.GetFeatures([image], landmarks.reshape(1,landmarks.shape[0], landmarks.shape[1]), vWDictionary)
featureDictionary = shelve.open(os.path.join(workingPath, self.featuresFolder_CrossValidation, self.positiveClassName+'_'+fileName))
featureDictionary['features'] = features
featureDictionary['description'] = description
featureDictionary.close()
# Leave-one-out cross validation. The results are saved in the working directory (outputFolder)
def CrossValidate(self, workingPath, maxNumberOfFeatures=30):
# geometricsPath: folder containing the geometric features
# lbpPath: folder containing the local binary patterns
# vwPath: folder containing the V and W matrices to create the texture features from the local binary patterns (different matrices for each case left out)
# savePath: folder to save the cross validation results
# maxNumberOfFeatures: maximum number of features to cross validate
## Load features
featurePath = os.path.join(workingPath, self.featuresFolder_CrossValidation)
savePath = os.path.join(workingPath, self.resultsFolder, self.crossValidationModelName)
patientList = []
img_list = sorted(os.listdir(featurePath))
for f_i in range(len(img_list)):
fileName, fileExtension = os.path.splitext(img_list[f_i])
# Load features
shelveDictionary = shelve.open(os.path.join(featurePath, fileName))
patientFeatures = shelveDictionary['features']
if 'featureDescription' not in locals():
featureDescription = shelveDictionary['description']
shelveDictionary.close()
if not self.asymmetry:
patientFeatures_new = []
featureDescription_new = []
for i in range(len(featureDescription)):
if "Asymmetry" not in featureDescription[i]:
patientFeatures_new += [patientFeatures[0,i]]
featureDescription_new += [featureDescription[i]]
new_num = len(patientFeatures_new)
patientFeatures = np.array(patientFeatures_new)
patientFeatures = np.reshape(patientFeatures, (1,new_num))
# Getting if the patient is normal or syndromic, and his name/ID
parts = fileName.split('_')
type = parts[0]
patientName = parts[1]
patientList += [patientName]
if type==self.negativeClassName:
patientLabel = 0
else:
patientLabel = 1
if 'allLabels' not in locals():
allLabels = np.array([patientLabel], np.int)
allFeatures = patientFeatures
else:
allLabels = np.concatenate([allLabels, np.array([patientLabel], dtype=np.int)], axis=0)
allFeatures = np.concatenate([allFeatures, patientFeatures], axis=0)
###################################################################################
#allFeatures = allFeatures[:,:18] # keeping only the geometric features!
#featureDescription = featureDescription[:18]
###################################################################################
nFeatures = allFeatures.shape[1]
nImages = allFeatures.shape[0]
# We sort so we first have all normals and then all syndromics
sortIndices = np.argsort(allLabels)
allLabels = allLabels[sortIndices]
allFeatures = allFeatures[sortIndices,:]
patientList = [patientList[i] for i in sortIndices]
# Statistics on the features
negativeClassMean = np.mean(allFeatures[np.where(allLabels==0)[0],:], axis=0).ravel()
negativeClassStd = np.std(allFeatures[np.where(allLabels==0)[0],:], axis=0).ravel()
positiveClassMean = np.mean(allFeatures[np.where(allLabels==1)[0],:], axis=0).ravel()
positiveClassStd = np.std(allFeatures[np.where(allLabels==1)[0],:], axis=0).ravel()
pValues = np.zeros([nFeatures], dtype=np.float)
for i in range(nFeatures):
try:
_, pValues[i] = scipy.stats.mannwhitneyu(allFeatures[np.where(allLabels==0)[0],i], allFeatures[np.where(allLabels==1)[0],i], alternative='two-sided')
except:
pValues[i] = 1
statistics = (negativeClassMean, negativeClassStd, positiveClassMean, positiveClassStd, pValues)
# Maximum number of features to try
dim = np.min([nFeatures, nImages, maxNumberOfFeatures])
# Probabilities estimated
probs = np.zeros([nImages, dim], dtype=np.float32)
rocArea = np.zeros([dim], dtype=np.float32)
sensitivity = np.zeros([dim], dtype=np.float32)
specificity = np.zeros([dim], dtype=np.float32)
accuracy = np.zeros([dim], dtype=np.float32)
threshold = np.zeros([dim], dtype=np.float32)
f1 = np.zeros([dim], dtype=np.float32)
selectedFeatures = np.zeros([nFeatures, dim], dtype=np.bool) # Matrix of selected features (True is selected, False otherwise)
for k in range(dim):
if self.verbose:
print('Number of features: {}'.format(str(k+1)))
# Scaling data
scaler = sklearn.preprocessing.StandardScaler()
scaledData = scaler.fit_transform(allFeatures)
# Selecting the k+1 most important features
if self.featureSelector == 'MCFS_p':
options = {}
options['gnd'] = np.zeros(allLabels.shape)
options['gnd'][np.where(allLabels==0)[0]] = 1
options['gnd'][np.where(allLabels==1)[0]] = 2
featureIds = MCFS_p(scaledData, k+1, options)[0].ravel()
elif self.featureSelector == 'RecursiveElimination':
model = sklearn.svm.SVC(kernel='linear', probability=True, class_weight='balanced')
selector = sklearn.feature_selection.RFE(model, k+1, step=1)
selector.fit(scaledData, allLabels)
featureIds = np.argwhere(selector.ranking_==1).ravel()
elif self.featureSelector == 'SequentialSelection':
model = sklearn.svm.SVC(kernel='linear', probability=True, class_weight='balanced')
selector = SequentialFeatureSelector(model, n_features_to_select=k+1, direction="forward")
selector.fit(scaledData, allLabels)
featureIds = np.argwhere(selector.get_support()==1).ravel()
# print(featureIds)
elif self.featureSelector == 'SelectKBest':
selector = SelectKBest(f_classif, k=50)
selector.fit(scaledData, allLabels)
else:
raise Exception('Unknown feature selector')
featureIds = np.sort(featureIds)
# Updating the selected features matrix
selectedFeatures[featureIds,k] = True
# Leave one out
for testId in range(nImages):
train = np.ones([allLabels.size], dtype=bool)
test = np.zeros([allLabels.size], dtype=bool)
train[testId] = False
test[testId] = True
trainClasses = allLabels[train]
testClasses = allLabels[test]
trainData = scaledData[train, :]
trainData = trainData[:, featureIds]
if trainData.ndim == 1: # It means there is only one feature
trainData = np.reshape(trainData, [trainData.size, 1])
testData = scaledData[test, :]
testData = testData[:, featureIds]
if testData.ndim == 1: # It means there is only one feature
testData = np.reshape(testData, [testData.size, 1])
model = sklearn.svm.SVC(kernel='linear', probability=True, class_weight='balanced')
model.fit(trainData, trainClasses)
probs[testId, k] = model.predict_proba(testData)[0, 1] # probability of the second class (syndromic)
rocArea[k] = sklearn.metrics.roc_auc_score(allLabels, probs[:, k])
if self.optimizeThreshold:
fpr, tpr, thresh = sklearn.metrics.roc_curve(allLabels, probs[:, k], pos_label=1, drop_intermediate=False)
optIndex = np.argmax(tpr-fpr)
threshold[k] = thresh[optIndex]
self.threshold = threshold[k]
sensitivity[k] = tpr[optIndex]
specificity[k] = 1-fpr[optIndex]
accuracy[k] = np.mean((probs[:, k] >= threshold[k]) == allLabels.astype(np.bool))
if k==5:
print(accuracy[k])
excelPath = os.path.join(workingPath, self.resultsFolder, 'Prediction_CV.xlsx')
workbook = xlsxwriter.Workbook(excelPath)
worksheet = workbook.add_worksheet('Prediction')
worksheet.write(0, 0, 'GT')
worksheet.write(0, 1, 'Leave 1 out')
for i in range(len(probs)):
worksheet.write(i+1, 0, allLabels[i])
worksheet.write(i+1, 1, probs[:, k][i] >= threshold[k])
workbook.close()
tp = np.sum(np.logical_and((probs[:, k] >= threshold[k]), (allLabels == 1)))
fp = np.sum(np.logical_and((probs[:, k] >= threshold[k]), (allLabels == 0)))
tn = np.sum(np.logical_and((probs[:, k] < threshold[k]), (allLabels == 0)))
fn = np.sum(np.logical_and((probs[:, k] < threshold[k]), (allLabels == 1)))
precision = tp/(tp+fp)
recall = sensitivity[k]
f1[k] = 2 * (precision * recall)/ (precision + recall)
else:
threshold[k] = self.threshold
tp = np.sum(np.logical_and((probs[:, k] >= threshold[k]), (allLabels == 1)))
fp = np.sum(np.logical_and((probs[:, k] >= threshold[k]), (allLabels == 0)))
tn = np.sum(np.logical_and((probs[:, k] < threshold[k]), (allLabels == 0)))
fn = np.sum(np.logical_and((probs[:, k] < threshold[k]), (allLabels == 1)))
sensitivity[k] = tp/(tp+fn)
specificity[k] = tn/(tn+fp)
accuracy[k] = (tp+tn)/(tp+fp+tn+fn)
if self.verbose:
#print(' Feature list: ' + str(listOfFeatures))
print(' AUC: {:.2f}. Accuracy: {:.2f}. Sensitivity: {:.2f}. Specificity: {:.2f}. Threshold: {:.2f}'.format(rocArea[k], accuracy[k], sensitivity[k], specificity[k], threshold[k]))
shelveDictionary = shelve.open(savePath)
shelveDictionary['patientList'] = patientList
shelveDictionary['labels'] = allLabels
shelveDictionary['probs'] = probs
shelveDictionary['rocArea'] = rocArea
shelveDictionary['sensitivity'] = sensitivity
shelveDictionary['specificity'] = specificity
shelveDictionary['accuracy'] = accuracy
shelveDictionary['threshold'] = threshold
shelveDictionary['selectedFeatures'] = selectedFeatures
if not self.asymmetry:
featureDescription = featureDescription_new
shelveDictionary['featureDescription'] = featureDescription
shelveDictionary['statistics'] = statistics
shelveDictionary['configuration'] = vars(self) # Saving the configuration
shelveDictionary['f1'] = f1
shelveDictionary['allFeatures'] = allFeatures
shelveDictionary.close()
# Export cross validation results to an Excel file
def ExportCrossValidationToExcel(self, workingPath):
crossValidationPath = os.path.join(workingPath, self.resultsFolder, self.crossValidationModelName)
excelPath = os.path.join(workingPath, self.resultsFolder, self.crossValidationExcelName)
shelveDictionary = shelve.open(crossValidationPath)
patientList = shelveDictionary['patientList']
allLabels = shelveDictionary['labels']
probs = shelveDictionary['probs']
rocArea = shelveDictionary['rocArea']
sensitivity = shelveDictionary['sensitivity']
specificity = shelveDictionary['specificity']
accuracy = shelveDictionary['accuracy']
threshold = shelveDictionary['threshold']
selectedFeatures = shelveDictionary['selectedFeatures']
featureDescription = shelveDictionary['featureDescription']
f1 = shelveDictionary['f1']
allFeatures = shelveDictionary['allFeatures']
(negativeClassMean, negativeClassStd, positiveClassMean, positiveClassStd, pValues) = shelveDictionary['statistics']
shelveDictionary.close()
# Create a workbook
workbook = xlsxwriter.Workbook(excelPath)
# Formats
boldFormat = workbook.add_format({'bold': True, 'align': 'center'})
decimalFormat = workbook.add_format({'num_format': '0.00', 'align': 'center'})
scientificFormat = workbook.add_format({'num_format': '0.00E+00', 'align': 'center'})
# Sheet 1: Statistics of features
worksheet = workbook.add_worksheet('AllFeatures')
worksheet.write(0, 0, 'Feature', boldFormat)
worksheet.write(0, 1, 'Mean: '+self.negativeClassName, boldFormat)
worksheet.write(0, 2, 'Std: '+self.negativeClassName, boldFormat)
worksheet.write(0, 3, 'Mean: '+self.positiveClassName, boldFormat)
worksheet.write(0, 4, 'Std: '+self.positiveClassName, boldFormat)
worksheet.write(0, 5, 'p-value', boldFormat)
for i in range(len(featureDescription)):
worksheet.write(i+1, 0, featureDescription[i])
worksheet.write(i+1, 1, negativeClassMean[i], decimalFormat)
worksheet.write(i+1, 2, negativeClassStd[i], decimalFormat)
worksheet.write(i+1, 3, positiveClassMean[i], decimalFormat)
worksheet.write(i+1, 4, positiveClassStd[i], decimalFormat)
worksheet.write(i+1, 5, pValues[i], scientificFormat)
# Sheet 2: Cross validation results
worksheet = workbook.add_worksheet('CrossValidation')
worksheet.write(0, 0, '# features', boldFormat)
worksheet.write(0, 1, 'ROC area', boldFormat)
worksheet.write(0, 2, 'Accuracy', boldFormat)
worksheet.write(0, 3, 'Sensitivity', boldFormat)
worksheet.write(0, 4, 'Specificity', boldFormat)
worksheet.write(0, 5, 'Threshold', boldFormat)
worksheet.write(0, 6, 'F1 score', boldFormat)
for i in range(accuracy.size):
worksheet.write(i+1, 0, i+1)
worksheet.write(i+1, 1, rocArea[i], decimalFormat)
worksheet.write(i+1, 2, accuracy[i], decimalFormat)
worksheet.write(i+1, 3, sensitivity[i], decimalFormat)
worksheet.write(i+1, 4, specificity[i], decimalFormat)
worksheet.write(i+1, 5, threshold[i], decimalFormat)
worksheet.write(i+1, 6, f1[i], decimalFormat)
chart = workbook.add_chart({'type': 'line'})
chart.add_series({ 'values': ['CrossValidation', 1, 1, accuracy.size, 1], #[sheetname, first_row, first_col, last_row, last_col]
'categories': ['CrossValidation', 1, 0, accuracy.size, 0],
'line': {'color': 'navy', 'dash_type': 'solid', 'width': 2.5},
'name': 'ROC area'})
chart.add_series({ 'values': ['CrossValidation', 1, 2, accuracy.size, 2], #[sheetname, first_row, first_col, last_row, last_col]
'categories': ['CrossValidation', 1, 0, accuracy.size, 0],
'line': {'color': 'red', 'dash_type': 'solid', 'width': 2.5},
'name': 'Accuracy'})
chart.add_series({ 'values': ['CrossValidation', 1, 3, accuracy.size, 3], #[sheetname, first_row, first_col, last_row, last_col]
'categories': ['CrossValidation', 1, 0, accuracy.size, 0],
'line': {'color': 'purple', 'dash_type': 'solid', 'width': 1.25},
'name': 'Sensitivity'})
chart.add_series({ 'values': ['CrossValidation', 1, 4, accuracy.size, 4], #[sheetname, first_row, first_col, last_row, last_col]
'categories': ['CrossValidation', 1, 0, accuracy.size, 0],
'line': {'color': 'green', 'dash_type': 'solid', 'width': 1.25},
'name': 'Specificity'})
chart.add_series({ 'values': ['CrossValidation', 1, 5, accuracy.size, 5], #[sheetname, first_row, first_col, last_row, last_col]
'categories': ['CrossValidation', 1, 0, accuracy.size, 0],
'line': {'color': 'yellow', 'dash_type': 'dash', 'width': 1.00},
'name': 'Threshold'})
chart.set_x_axis({'name': '# features'})
chart.set_y_axis({'name': '# features', 'min': 0, 'max': 1.05})
worksheet.insert_chart('G1', chart)
# Sheet 3: Selected features
worksheet = workbook.add_worksheet('Selectedfeatures')
worksheet.write(0, 0, 'Feature', boldFormat) # Headers
for i in range(selectedFeatures.shape[1]):
worksheet.write(0, i+1, str(i+1), boldFormat)
worksheet.write(0, selectedFeatures.shape[1]+1, 'SUM', boldFormat)
for i in range(len(featureDescription)): # Data
#print(featureDescription[i])
worksheet.write(i+1, 0, featureDescription[i])
for j in range(selectedFeatures.shape[1]):
worksheet.write(i+1, j+1, selectedFeatures[i,j])
for i in range(len(featureDescription)): # Formula
worksheet.write_formula(i+1, selectedFeatures.shape[1]+1, '=SUM('+get_column_letter(2)+str(i+2)+':'+get_column_letter(selectedFeatures.shape[1]+1)+str(i+2)+')', boldFormat)
# Sheet 4: All feature values
worksheet = workbook.add_worksheet('FeatureValues')
worksheet.write(0, 0, 'Feature', boldFormat) # Headers
print(allFeatures.shape)
for i in range(len(featureDescription)):
worksheet.write(i+1, 0, featureDescription[i])
for i in range(len(patientList)):
worksheet.write(0, i+1, patientList[i])
for j in range(len(featureDescription)):
worksheet.write(j+1, i+1, allFeatures[i,j])
workbook.close()
##################################################################################################
## THE FUNCTIONS BELOW DO NOT HAVE TO BE USED OUTSIDE THE CLASS UNLESS YOU KNOW WHAT YOU ARE DOING
##################################################################################################
# Creates the folder structure within the working (output) folder
def createOutputFolderStructure(self, outputFolder, removeExistingFiles=False):
if removeExistingFiles and os.path.exists(outputFolder):
shutil.rmtree(outputFolder)
if not os.path.exists(os.path.join(outputFolder, self.resizedImageFolder, self.negativeClassName, self.landmarksFolder)):
os.makedirs(os.path.join(outputFolder, self.resizedImageFolder, self.negativeClassName, self.landmarksFolder))
if not os.path.exists(os.path.join(outputFolder, self.resizedImageFolder, self.positiveClassName, self.landmarksFolder)):
os.makedirs(os.path.join(outputFolder, self.resizedImageFolder, self.positiveClassName, self.landmarksFolder))
if not os.path.exists(os.path.join(outputFolder, self.lbpFolder)):
os.makedirs(os.path.join(outputFolder, self.lbpFolder))
if not os.path.exists(os.path.join(outputFolder, self.vwMatricesFolder_CrossValidation)):
os.makedirs(os.path.join(outputFolder, self.vwMatricesFolder_CrossValidation))
# if not os.path.exists(os.path.join(outputFolder, self.vwMatricesFolder)):
# os.makedirs(os.path.join(outputFolder, self.vwMatricesFolder))
if not os.path.exists(os.path.join(outputFolder, self.featuresFolder_CrossValidation)):
os.makedirs(os.path.join(outputFolder, self.featuresFolder_CrossValidation))
# if not os.path.exists(os.path.join(outputFolder, self.featuresFolder)):
# os.makedirs(os.path.join(outputFolder, self.featuresFolder))
if not os.path.exists(os.path.join(outputFolder, self.resultsFolder)):
os.makedirs(os.path.join(outputFolder, self.resultsFolder))
# Standardize the images and landmarks for one case
def normalizeImageAndLandmarks(self, image, landmarks, interPupilDist = 150, orientation = 0, sizeOut = 150, offsetOut = 11):
# image: the image to process
# landmarks: the landmarks to process, shape [nLandmarks, 2]
# sizeOut: size of the output image. (150)
# offsetOut: offset to both sides (rows and columns) in the transformed image
# interPupilDist: distance between pupil landmarks (5 and 10)
# orientation: orientation of the interpupil vector
interPupilVector = landmarks[9, :] - landmarks[4, :]
Or_i, Mag_i = cart2pol(interPupilVector[0], interPupilVector[1]) # Cartesian coordinates of the vector
scalingFactor = interPupilDist / Mag_i
Or_i = -(orientation - Or_i) # using (-) sign b/c Y axis in image space is inverted
center_ldmks = np.array([np.mean(landmarks[:,0]), np.mean(landmarks[:,1]), 1.0], dtype=np.float32)
# Transformation matrix
T_mat = np.array([[scalingFactor*np.cos(Or_i),-scalingFactor *np.sin(Or_i),0],[scalingFactor*np.sin(Or_i), scalingFactor*np.cos(Or_i),0],[0,0,1]],dtype=np.float32)
invT_mat = np.linalg.inv(T_mat) # inverse
landmarks = np.append(landmarks, np.ones([landmarks.shape[0], 1]), axis=1)
# Transformation of landmarks (rotation and scaling)
P_align = np.zeros(landmarks.shape, dtype=np.float32)
for i in range(landmarks.shape[0]):
P_align[i, :] = np.dot( landmarks[i,:]-center_ldmks, T_mat) + center_ldmks
##########################################################
# Now everything is aligned using T_mat wrt center_ldmks
##########################################################
# Box around the inner landmarks
colRange = np.array([np.floor(min(P_align[:33,0])), np.ceil(max(P_align[:33,0]))]).astype(np.int)
rowRange = np.array([np.floor(min(P_align[:33,1])), np.ceil(max(P_align[:33,1]))]).astype(np.int)
colSize = colRange[1] - colRange[0]
rowSize = rowRange[1] - rowRange[0]
totalLength = max(colSize, rowSize) # This is the size of the squared box around the inner landmarks
colOffset = int(np.ceil( (offsetOut * (colSize + 1) )/ (sizeOut - 2 * offsetOut) ) )
rowOffset = int(np.ceil( (offsetOut * (rowSize + 1) )/ (sizeOut - 2 * offsetOut) ) )
offset = max(colOffset, rowOffset) # Offset to add (in the new space of aligned landmarks)
# Extending the ranges to fit the squared box
if colSize <= rowSize:
colRange = np.array([colRange[0]-np.round((rowSize-colSize)/2), colRange[1]+np.round((rowSize-colSize)/2)]).astype(np.int)
else:
rowRange = np.array([rowRange[0]-np.round((colSize-rowSize)/2), rowRange[1]+np.round((colSize-rowSize)/2)]).astype(np.int)
# This are the ranges of the aligned landmarks space to keep
colRange_new = np.array([(colRange[0] - offset), (colRange[1] + offset)])
rowRange_new = np.array([(rowRange[0] - offset), (rowRange[1] + offset)])
# The new image
newImg = np.zeros([rowRange_new[1]-rowRange_new[0] + 1, colRange_new[1]-colRange_new[0] + 1], dtype=np.uint8)
for newX in range(colRange_new[0], colRange_new[1] + 1):
for newY in range(rowRange_new[0], rowRange_new[1] + 1):
# Invert previous transformation to set the interpupilary distance
oCoords = np.dot(np.array([newX, newY, 1.0], dtype=np.float32) - center_ldmks, invT_mat) + center_ldmks
if oCoords[0] < image.shape[1] and oCoords[1] < image.shape[0] and oCoords[0]>=0 and oCoords[1]>=0:
newImg[newY-rowRange_new[0], newX-colRange_new[0]] = image[int(oCoords[1]), int(oCoords[0])]
# Applying the offset to the landmarks
P_align[:,0] -= colRange_new[0]
P_align[:,1] -= rowRange_new[0]
# Scaling image and landmarks
scalingFactor = sizeOut/newImg.shape[1]
P_align[:,0] *= scalingFactor
scalingFactor = sizeOut/newImg.shape[0]
P_align[:,1] *= scalingFactor
newImg = skimage.transform.resize(newImg, (sizeOut, sizeOut))
return newImg, P_align
# Rescales and aligns all images in a data folder
def rescaleImagesAlignLandmarks(self, imPath, landmarkPath, sPath, interPupilDist = 150, orientation = 0, sizeOut = 150, offsetOut = 10):
# imPath -> Folder containing all images. Assumes all images are within the same folder
# sPath-> Folder to save all aligned and rescaled images
# interPupilDist: distance between pupil landmarks (5 and 10)
# orientation: orientation of the interpupil vector
# sizeOut: size of the output image. (150)
# offsetOut: offset to both sides (rows and columns) in the transformed image
img_list = sorted(os.listdir(imPath))
for file in img_list:
fileName, fileExtension = os.path.splitext(file)
if fileExtension.lower() == '.jpg':
# if fileExtension.lower() == '.png':
if self.verbose:
print('Processing: ' + file)
# Grayscale reading
rgb_weights = [0.2989, 0.5870, 0.1140]
I = np.dot(imread(os.path.join(imPath,file))[..., :3], rgb_weights)
# Read pts files to get landmarks
P = np.loadtxt(os.path.join(landmarkPath, fileName + '.pts'), unpack = True).T
# Normalizing
newImg, P_align = self.normalizeImageAndLandmarks(I, P, interPupilDist = interPupilDist, orientation = orientation, sizeOut = sizeOut, offsetOut = offsetOut)
##################################################################
# 4. Save Scaled and Cropped Images/Landmarks
##################################################################
imageio.imsave(os.path.join(sPath, fileName + '.jpg'), img_as_ubyte(newImg))
np.save(os.path.join(sPath, self.landmarksFolder, fileName), P_align[:,:2])
# Returns the local binary patterns for one case
def extractLBP(self, image, landmarks, LBP_list, Ws):
patientDictionary = {}
patientDictionary['FeatureDescriptions'] = ['Texture at columella',
'Texture at nasion',
'Texture at tip of nose',
'Texture at philtrum',
'Texture at center of cupid\'s bow',
'Texture at lower border of upper lip',
'Texture at upper border of lower lip',
'Average texture at lateral canthi',
'Average texture at lower eyelids',
'Average texture at medial canthi',
'Average texture at upper eyelids',
'Average texture at center of the pupil',
'Average texture at lateral of nose root',
'Average texture at alar crease',
'Average texture at center of ala',
'Average texture at bottom of ala',
'Average texture at nostril top', #alar septum junction
'Average texture at oral commissures',
'Average texture at side of cupid\'s bow',
'Average texture at side of lower lip',
'Asymmetry of texture at lateral canthi',
'Asymmetry of texture at lower eyelids',
'Asymmetry of texture at medial canthi',
'Asymmetry of texture at upper eyelids',
'Asymmetry of texture at center of the eyes',
'Asymmetry of texture at lateral of nose root',
'Asymmetry of texture at alar crease',
'Asymmetry of texture at center of ala',
'Asymmetry of texture at bottom of ala',
'Asymmetry of texture at nostril top',
'Asymmetry of texture at oral commissures',
'Asymmetry of texture at side of cupid\'s bow',
'Asymmetry of texture at side of lower lip']
centerIndices = np.array([15, 21, 22, 23, 26, 31, 32], dtype=np.int)
leftIndices = np.array([0, 1, 2, 3, 4, 10, 11, 12, 13, 14, 24, 25, 30], dtype=np.int)
rightIndices = np.array([7, 6, 5, 8, 9, 20, 19, 18, 17, 16, 28, 27, 29], dtype=np.int)
# Normalizing image values between 0 and 1 --> equivalent to MATLAB mat2gray function
min_ = np.min(image)
max_ = np.max(image)
I_norm = (image - min_) / (max_ - min_ + np.spacing(1))
# Expand the image to avoid accessing to the wrong location in case
# the filter on the LBP patch were too big.
P_Extra = np.max(np.array([LBP_list[0,1],LBP_list[1,1],LBP_list[2,1],Ws])) + 5
I_Corner_UL = I_norm[(P_Extra-1)::-1,(P_Extra-1)::-1]
I_Corner_UR = I_norm[(P_Extra-1)::-1,(I_norm.shape[1]-1):(I_norm.shape[1]-1)-(P_Extra+2):-1]
I_Corner_BL = I_norm[(I_norm.shape[1]-1):(I_norm.shape[1]-1)-(P_Extra+2):-1,(P_Extra-1)::-1]
I_Corner_BR = I_norm[(I_norm.shape[1]-1):(I_norm.shape[1]-1)-(P_Extra+2):-1,(I_norm.shape[1]-1):(I_norm.shape[1]-1)-(P_Extra+2):-1]
I_u = I_norm[(P_Extra-1)::-1,:]
I_b = I_norm[(I_norm.shape[1]-1):(I_norm.shape[1]-1)-(P_Extra+2):-1,:]
I_l = I_norm[:,(P_Extra-1)::-1]
I_r = I_norm[:,(I_norm.shape[1]-1):(I_norm.shape[1]-1)-(P_Extra+2):-1]
I_Ext_left = np.vstack((np.hstack((I_Corner_UL,I_u,I_Corner_UR)),np.hstack((I_l,I_norm,I_r)),np.hstack((I_Corner_BL,I_b,I_Corner_BR))))
(Nr,Nc) = I_Ext_left.shape
# Create image filter mask
Mid_r = np.linspace((-((Ws-1)/2)),((Ws-1)/2),int(Ws)).reshape(1,int(Ws))
Mid_c = Mid_r.T
Mid_r = Nr*Mid_r
W_IDs = np.matlib.repmat(Mid_r,Ws,1) + np.matlib.repmat(Mid_c,1,Ws)
W_IDs_vector = np.reshape(W_IDs,(W_IDs.size,1, 1))
x_align_left = landmarks[:33, 0].reshape(1, 33) + P_Extra # This is for left and center indices
y_align_left = landmarks[:33, 1].reshape(1, 33) + P_Extra
# Flipping the image and landmarks
I_Ext_right = np.fliplr(I_Ext_left)
centerX = I_Ext_left.shape[1]/2.0
x_align_right = (x_align_left - centerX)*(-1) + centerX # For right indices
y_align_right = np.copy(y_align_left)
# Pass Landmarks to IDs
Ldmks_IDs_center = np.zeros([centerIndices.size], dtype=np.int)
Ldmks_IDs_left = np.zeros([leftIndices.size], dtype=np.int)
Ldmks_IDs_right = np.zeros([rightIndices.size], dtype=np.int)
for i in range(centerIndices.size):
Ldmks_IDs_center[i] = np.ravel_multi_index((y_align_left[0,centerIndices[i]].astype(int), x_align_left[0,centerIndices[i]].astype(int)), I_Ext_left.shape,mode='raise')
for i in range(leftIndices.size):
Ldmks_IDs_left[i] = np.ravel_multi_index((y_align_left[0,leftIndices[i]].astype(int), x_align_left[0,leftIndices[i]].astype(int)), I_Ext_left.shape,mode='raise')
for i in range(rightIndices.size):
Ldmks_IDs_right[i] = np.ravel_multi_index((y_align_right[0,rightIndices[i]].astype(int), x_align_right[0,rightIndices[i]].astype(int)), I_Ext_left.shape,mode='raise')
Ldmks_IDs_center = np.reshape(Ldmks_IDs_center,(1,1,Ldmks_IDs_center.size))
Ldmks_IDs_left = np.reshape(Ldmks_IDs_left,(1,1,Ldmks_IDs_left.size))
Ldmks_IDs_right = np.reshape(Ldmks_IDs_right,(1,1,Ldmks_IDs_right.size))
# LBP LOOP ---> IN
##################################################################
for l_i in range(LBP_list.shape[0]): # For each LBP resolution: pair [element,radius]
LBP_i = LBP_list[l_i,:].reshape(1,LBP_list.shape[1]) # LBP_i = (# elements x radii)
# Create LBP Pattern
LBP_Pattern = generateRadialFilterLBP(LBP_i[0,0],LBP_i[0,1]) # output is W x W x #elements, where W is 2 x radius + 1
# Create ID-Mask for the Neighborwood LBP patch
W_Ngh = LBP_Pattern.shape[0]
Mid_r = np.arange(-(W_Ngh-1)/2, (W_Ngh-1)/2 + 1).astype(np.int).reshape(1,int(W_Ngh))
Mid_c = Mid_r.T
Mid_r = Nr*Mid_r
Ngh_IDs_aux = np.matlib.repmat(Mid_r,W_Ngh,1) + np.matlib.repmat(Mid_c,1,W_Ngh)
# LBP_diff_vect LOOP ---> IN
##############################################################
for p_i in range(LBP_Pattern.shape[2]): # For each element in the neighborhood (there are #element elements)
LBP_ij = np.copy(LBP_Pattern[:,:,p_i]) # LBP_ij is the WxW window -> As of here, it is independent from the coordinates of the landmarks
# Find neighbors
IDs = np.where(LBP_ij > 0) # Pixels in the window LBP_ij to compare with
IDs_offset = np.insert(np.reshape(Ngh_IDs_aux[IDs], [1,IDs[0].size]), 0, 0, axis=1)
# Find weights
W_lbp = np.insert(np.reshape(LBP_ij[IDs], [1,IDs[0].size]), 0, -1, axis=1)
#Compute the total offset
W_IDs_MAT = np.tile(W_IDs_vector, [1, IDs_offset.size, x_align_left.size])
LBP_ij_IDs_MAT = np.tile(np.reshape(IDs_offset, [IDs_offset.shape[0], IDs_offset.shape[1], 1]),[W_IDs_vector.size, 1, x_align_left.size])
W_lbp_MAT = np.tile(np.reshape(W_lbp, [W_lbp.shape[0], W_lbp.shape[1], 1]), [W_IDs_vector.size, 1, x_align_left.size])
IDs_MAT = W_IDs_MAT + LBP_ij_IDs_MAT
Ldmks_IDs_MAT_center = np.tile(Ldmks_IDs_center, [IDs_MAT.shape[0], IDs_MAT.shape[1], 1])
Ldmks_IDs_MAT_left = np.tile(Ldmks_IDs_left, [IDs_MAT.shape[0], IDs_MAT.shape[1], 1])
Ldmks_IDs_MAT_right = np.tile(Ldmks_IDs_right, [IDs_MAT.shape[0], IDs_MAT.shape[1], 1])
All_IDs_center = Ldmks_IDs_MAT_center + IDs_MAT[:,:,centerIndices]
All_IDs_left = Ldmks_IDs_MAT_left + IDs_MAT[:,:,leftIndices]
All_IDs_right = Ldmks_IDs_MAT_right + IDs_MAT[:,:,rightIndices]
I_all_IDs_int_center = I_Ext_left.ravel()[All_IDs_center.ravel().astype(np.int)].reshape(All_IDs_center.shape)
I_all_IDs_int_left = I_Ext_left.ravel()[All_IDs_left.ravel().astype(np.int)].reshape(All_IDs_left.shape)
I_all_IDs_int_right = I_Ext_right.ravel()[All_IDs_right.ravel().astype(np.int)].reshape(All_IDs_right.shape)
I_all_IDs_int_center = np.sum(I_all_IDs_int_center * W_lbp_MAT[:,:,centerIndices], axis=1, keepdims=True)
I_all_IDs_int_left = np.sum(I_all_IDs_int_left * W_lbp_MAT[:,:, leftIndices], axis=1, keepdims=True)
I_all_IDs_int_right = np.sum(I_all_IDs_int_right * W_lbp_MAT[:,:,rightIndices], axis=1, keepdims=True)
# Appending center and side features (average and difference)
I_all_IDs_int = np.concatenate([I_all_IDs_int_center, (I_all_IDs_int_left+I_all_IDs_int_right)/2, np.abs(I_all_IDs_int_left-I_all_IDs_int_right)], axis=2)
if p_i == 0:
LBP_All_i = np.copy(I_all_IDs_int)
else:
LBP_All_i = np.append(LBP_All_i, I_all_IDs_int, axis=1)
patientDictionary['LBP_'+str(l_i + 1)] = LBP_All_i
return patientDictionary
# Calculates the local binary patterns for all images in imagePath, with landmarks under imagePath/self.landmarksFolder
def SaveLocalBinaryPatterns(self, workingPath):
# imagePath: folder with all the images. The landmarks are under the folder self.landmarksFolder in that directory
# outputPath: folder to save the calculated local binary patterns
# Ws: Window size
outputPath = os.path.join(workingPath, self.lbpFolder)
# Doing it for the negative class
imagePath = os.path.join(workingPath, self.resizedImageFolder, self.negativeClassName)
landmarksPath = os.path.join(imagePath, self.landmarksFolder)
img_list = sorted(os.listdir(imagePath))
for file in img_list:
fileName, fileExtension = os.path.splitext(file)
if fileExtension == '.jpg':
patientDictionary = {}
# Read image
image = imread(os.path.join(imagePath,file))
# Read landmarks
landmarks = np.load(os.path.join(workingPath, self.resizedImageFolder, self.negativeClassName, self.landmarksFolder, fileName+'.npy'))
# Calculate LBP
lbpDictionary = self.extractLBP(image, landmarks, self.LBP_list, self.Ws)
# Saving patient LBPs
shelveDictionary = shelve.open(os.path.join(outputPath, self.negativeClassName + '_' + fileName))
for key, value in lbpDictionary.items():
if key == "FeatureDescriptions":
new_value = []
new_key = []
for i in value:
# print("Asymmetry" in str(i))
if "Asymmetry" not in str(i):
new_value.append(i)
#value.remove(i)
value = new_value
#else:
#
# print(shelveDictionary[key])
shelveDictionary[key] = value
#print(shelveDictionary[key])
#print(shelveDictionary.keys())
shelveDictionary.close()
# Doing it for the positive class
imagePath = os.path.join(workingPath, self.resizedImageFolder, self.positiveClassName)
landmarksPath = os.path.join(imagePath, self.landmarksFolder)
img_list = sorted(os.listdir(imagePath))
for file in img_list:
fileName, fileExtension = os.path.splitext(file)
if fileExtension == '.jpg':
patientDictionary = {}
# Read image
image = imread(os.path.join(imagePath,file))
# Read landmarks
landmarks = np.load(os.path.join(workingPath, self.resizedImageFolder, self.positiveClassName, self.landmarksFolder, fileName+'.npy'))
# Calculate LBP
lbpDictionary = self.extractLBP(image, landmarks, self.LBP_list, self.Ws)
# Saving patient LBPs
shelveDictionary = shelve.open(os.path.join(outputPath, self.positiveClassName + '_' + fileName))
for key, value in lbpDictionary.items():
if key == "FeatureDescriptions":
new_value = []
new_key = []
for i in value:
# print("Asymmetry" in str(i))
if "Asymmetry" not in str(i):
new_value.append(i)
# value.remove(i)
value = new_value
shelveDictionary[key] = value
shelveDictionary.close()
# Creates the W and V matrices used to calculate the texture features from the local binary patterns.
# Since it is used for cross validation, it calculates different matrices for each subject
# Assumes that the local binary patterns are already calculated in their folder
def CalculateLDAMatrices_CrossValidation(self, workingPath):
lbpPath = os.path.join(workingPath, self.lbpFolder)
outputPath = os.path.join(workingPath, self.vwMatricesFolder_CrossValidation)
T = 20 # number of iterations
d1r = 1 # the size of the window filter will be d1 x d1r (where d1 is the original size of the patch)
d2r = 1 # the size of the window filter will be d2 x d2r (where d2 is the size of the LBP difference patch)
# LBP_Loop ---> IN
##########################################################################
fileList = sorted(os.listdir(lbpPath))
for L_i in range(self.LBP_list.shape[0]):
if self.verbose:
print('LBP ',str(L_i+1))
# loop read all cases
######################################################################
fileList_Normal = []
fileList_Syndromic = []
# Separating Normals and Syndromics
for file in fileList:
fileName, fileExtension = os.path.splitext(file)
# if fileExtension == '.dat':
if self.negativeClassName in fileName:
fileList_Normal.append(fileName)
elif self.positiveClassName in fileName:
fileList_Syndromic.append(fileName)
# Normals ------------------------------------------------------------
for f_i in range(len(fileList_Normal)):
#LBP_All_i = np.load(os.path.join(lbpPath,fileList_Normal[f_i]))
shelveDictionary = shelve.open(os.path.join(lbpPath, fileList_Normal[f_i]))
LBP_All_i = shelveDictionary['LBP_' + str(L_i+1)]
shelveDictionary.close()
LBP_All_i = np.reshape(LBP_All_i, (LBP_All_i.shape[0],LBP_All_i.shape[1],1,LBP_All_i.shape[2]))
if f_i == 0:
LBP_ALL_Ldmks = np.copy(LBP_All_i)
else:
LBP_ALL_Ldmks = np.append(LBP_ALL_Ldmks,LBP_All_i,axis=2)
LBP_Normal = LBP_ALL_Ldmks
# Syndromics ---------------------------------------------------------
for f_i in range(len(fileList_Syndromic)):