-
Notifications
You must be signed in to change notification settings - Fork 0
/
Classifier.py
2010 lines (1400 loc) · 73.6 KB
/
Classifier.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
"""
James Quintero
Created: 2019
"""
#Local files
from DICOM_reader import DICOMReader
from DataHandler import DataHandler
from ImagePreprocessor import *
from DataGenerator import DataGenerator
import sys
import os
import random
import json
import scipy
import imageio
from datetime import datetime
#ML libraries
import numpy as np
#Sklearn
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.model_selection import KFold
from sklearn.utils import resample
#Scipy
from scipy.optimize import differential_evolution
import keras
from keras import backend as K
#Layers
from keras.layers import Input
from keras.layers import *
#Models
from keras.models import Sequential
from keras.models import Model
from keras.models import load_model
#Callback methods
from keras.callbacks import EarlyStopping
from keras.callbacks import ModelCheckpoint
#Regularizers
from keras.regularizers import l2
from keras.regularizers import l1
#constraints
from keras.constraints import max_norm
from keras.utils import np_utils
from keras.preprocessing.image import ImageDataGenerator
from keras.optimizers import Adam
#For my windows machine
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
"""
Handles differen types (binary, segmentation) classification training, validation, and testing
"""
class Classifier(ABC):
project = ""
image_width = 512
image_height = 512
model_archs = {"cnn": "cnn", "unet": "unet"}
dicom_reader = None
data_handler = None
image_preprocessor = None
hyperparameters = {}
def __init__(self, project):
self.dicom_reader = DICOMReader()
self.data_handler = DataHandler()
self.project = project.lower()
if self.project=="chest_radiograph":
self.image_preprocessor = ChestRadiograph()
self.hyperparameters = self.data_handler.load_hyperparameters()
#returns proper filename prefix for specified model_arch, e.x: "cnn" returns "cnn" for use in "./cnn_model.h5"
def get_model_arch_filename_prefix(self, model_arch):
try:
return self.model_archs[model_arch.lower()]
except Exception as error:
return ""
"""
returns list of paths to processed image files
dataset_type = {"train", "test"}
label_type = {"binary", "segmentation"}
"""
def get_processed_image_paths(self, dataset_type="train", label_type="binary", balanced=False, max_num=None):
if dataset_type.lower() == "train":
image_paths = self.dicom_reader.load_filtered_dicom_train_paths()
elif dataset_type.lower() == "test":
image_paths = self.dicom_reader.load_filtered_dicom_test_paths()
#if user wants paths where it's 50% positive, and 50% negative
if balanced:
print("Loading balanced amount of positive and negative targets")
new_image_paths = []
negative = []
positive = []
for i in range(0, len(image_paths)):
image_path = image_paths[i]
#extracts image_id from the file path
image_id = self.dicom_reader.extract_image_id(image_paths[i], self.image_preprocessor.preprocessed_ext)
#finds positive mask associated with the image
masks = self.data_handler.find_masks(image_id=image_id)
#if Negative
if len(masks)==0:
#makes sure haven't added too many negative labels
if (max_num==None and len(negative)<int(len(image_paths)/2)) or (max_num!=None and len(negative)<int(max_num/2)):
negative.append(image_path)
#if Positive
else:
#makes sure haven't added too many positive labels
if (max_num==None and len(positive)<int(len(image_paths)/2)) or (max_num!=None and len(positive)<int(max_num/2)):
positive.append(image_path)
#if found enough of both positive and negative
if max_num!=None and len(positive)+len(negative)>=max_num:
break
#resize negative and positive arrays to match each other
if len(positive)>len(negative):
positive = positive[:len(negative)]
elif len(positive)<len(negative):
negative = negative[:len(positive)]
#shuffles positives and negatives
image_paths = []
image_paths.extend(positive)
image_paths.extend(negative)
random.seed(12345)
random.shuffle(image_paths)
#if user doesn't want an explicit balance of positive and negative signals
else:
#if no max, set max to the number of train items
if max_num!=None and max_num<=len(image_paths) and max_num>0:
image_paths = image_paths[:max_num]
return image_paths
"""
returns statistical measures related to confusion matrix
confusion_matrix is in the following format
[TN FP]
[FN TP]
"""
def calculate_statistical_measures(self, confusion_matrix):
statistical_measures = {}
try:
#True Negative
TN = confusion_matrix[0][0]
statistical_measures['TN'] = TN
#False Positive
FP = confusion_matrix[0][1]
statistical_measures['FP'] = FP
#False Negative
FN = confusion_matrix[1][0]
statistical_measures['FN'] = FN
#True Positive
TP = confusion_matrix[1][1]
statistical_measures['TP'] = TP
except Exception as error:
print("Mishapen confusion matrix")
return {}
#https://en.wikipedia.org/wiki/Confusion_matrix
if (TN+FP+FN+TP)>0:
accuracy = (TN+TP)/(TN+FP+FN+TP)
else:
accuracy = 0
statistical_measures['accuracy'] = accuracy
if TP>0:
precision = TP/(FP+TP)
else:
precision = 0
statistical_measures['precision'] = precision
if TN>0:
negative_predictive_value = TN/(TN+FN)
else:
negative_predictive_value = 0
statistical_measures['NPV'] = negative_predictive_value
if TP>0:
F1 = (2*TP) / (2*TP + FP + FN)
else:
F1 = 0
statistical_measures['F1'] = F1
if TP > 0:
sensitivity = TP/(TP+FN)
else:
sensitivity = 0
statistical_measures['sensitivity'] = sensitivity
#Matthews correlation coefficient (great for binary classification)
#https://en.wikipedia.org/wiki/Matthews_correlation_coefficient
try:
MCC = (TP*TN - FP*FN)/np.sqrt((TP+FP)*(TP+FN)*(TN+FP)*(TN+FN))
except Exception as error:
MCC = 0
statistical_measures['MCC'] = MCC
#when it's a downmove, how often does model predict a downmove?
if TN>0:
specificity = TN/(TN+FP)
else:
specificity = 0
statistical_measures['specificity'] = specificity
#False Positive Rate (FPR) (Fall-Out)
FPR = 1 - specificity
statistical_measures['FPR'] = FPR
#False Negative Rate (FNR)
FNR = 1 - sensitivity
statistical_measures['FNR'] = FNR
#both TPR (sensitivity) and FPR (100-Specificity) are used to plot the ROC (Receiver Operating Characteristic) curve
#https://www.medcalc.org/manual/roc-curves.php
ROC = sensitivity - FPR
statistical_measures['ROC'] = ROC
#want to get 200%, 100% for sensitivity and 100% for specificity
#https://en.wikipedia.org/wiki/Youden%27s_J_statistic
total = sensitivity + specificity
statistical_measures['total'] = total
return statistical_measures
def dice_coef(self, y_true, y_pred):
smooth = 1.
y_true_f = K.flatten(y_true)
y_pred_f = K.flatten(y_pred)
intersection = K.sum(y_true_f * y_pred_f)
return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)
def dice_coef_loss(self, y_true, y_pred):
return 1-self.dice_coef(y_true, y_pred)
"""
Returns simple default CNN architecture
"""
@abstractmethod
def create_CNN(self):
# Initialising the CNN
classifier = Sequential()
CNN_size = 16
pool_size = (3,3)
filter_size = (3,3)
CNN_activation = "selu"
dense_activation = "selu"
output_activation = "linear"
loss = "mean_squared_error"
classifier.add(Convolution2D(CNN_size, filter_size, input_shape = (self.image_width, self.image_height, 1), padding="same", activation = CNN_activation))
# Step 2 - Pooling
#pooling uses a 2x2 or something grid (most of the time is 2x2), goes over the feature maps, and the largest values as its going over become the values in the pooled map
#slides with a stride of 2. At the end, the pool map should be (length/2)x(width/2)
classifier.add(MaxPooling2D(pool_size = pool_size))
classifier.add(Dropout(0.25))
# Adding a second convolutional layer
classifier.add(Convolution2D(CNN_size, filter_size, padding="same", activation = CNN_activation))
classifier.add(MaxPooling2D(pool_size = pool_size))
classifier.add(Dropout(0.25))
# Adding a second convolutional layer
classifier.add(Convolution2D(CNN_size, filter_size, padding="same", activation = CNN_activation))
classifier.add(MaxPooling2D(pool_size = pool_size))
classifier.add(Dropout(0.25))
# Adding a second convolutional layer
classifier.add(Convolution2D(CNN_size, filter_size, padding="same", activation = CNN_activation))
classifier.add(MaxPooling2D(pool_size = pool_size))
classifier.add(Dropout(0.25))
#flattents the layers
classifier.add(Flatten())
#128 is an arbitrary number that can be decreased to lower computation time, and increased for better accuracy
classifier.add(Dense(units = 128, activation = dense_activation))
classifier.add(Dropout(0.25))
classifier.add(Dense(units = 1, activation = output_activation))
classifier.compile(optimizer = 'adam', loss = loss, metrics = ['accuracy'])
# classifier.compile(optimizer = 'adam', loss=self.dice_coef_loss, metrics=[self.dice_coef])
classifier.summary()
return classifier
"""
returns very simple U-net
architecture source: https://github.com/yihui-he/u-net
and https://github.com/jocicmarko/ultrasound-nerve-segmentation/
"""
@abstractmethod
def create_Unet(self):
start_size = 16
pool_size = (2,2)
filter_size = (3,3)
conv_activation = "selu"
dense_activation = "selu"
output_activation = "sigmoid"
inputs = Input((self.image_width, self.image_height, 1))
conv1 = Conv2D(start_size*1, filter_size, activation=conv_activation, padding='same')(inputs)
conv1 = Conv2D(start_size*1, filter_size, activation=conv_activation, padding='same')(conv1)
conv1 = BatchNormalization()(conv1)
pool1 = MaxPooling2D(pool_size=pool_size)(conv1)
conv2 = Conv2D(start_size*2, filter_size, activation=conv_activation, padding='same')(pool1)
conv2 = Conv2D(start_size*2, filter_size, activation=conv_activation, padding='same')(conv2)
conv2 = BatchNormalization()(conv2)
pool2 = MaxPooling2D(pool_size=pool_size)(conv2)
conv3 = Conv2D(start_size*4, filter_size, activation=conv_activation, padding='same')(pool2)
conv3 = Conv2D(start_size*4, filter_size, activation=conv_activation, padding='same')(conv3)
conv3 = BatchNormalization()(conv3)
up8 = concatenate([Conv2D(start_size*2, pool_size, activation=conv_activation, padding='same')(UpSampling2D(size=pool_size)(conv3)), conv2], axis=3)
conv8 = Conv2D(start_size*2, filter_size, activation=conv_activation, padding='same')(up8)
conv8 = Conv2D(start_size*2, filter_size, activation=conv_activation, padding='same')(conv8)
conv8 = BatchNormalization()(conv8)
up9 = concatenate([Conv2D(start_size*1, pool_size,activation=conv_activation, padding='same')(UpSampling2D(size=pool_size)(conv8)), conv1], axis=3)
conv9 = Conv2D(start_size*1, filter_size, activation=conv_activation, padding='same')(up9)
conv9 = Conv2D(start_size*1, filter_size, activation=conv_activation, padding='same')(conv9)
conv9 = BatchNormalization()(conv9)
conv10 = Convolution2D(1, (1, 1), activation=conv_activation)(conv9)
# model = Model(inputs=inputs, outputs=conv10)
dense1 = Flatten()(conv10)
dense2 = Dense(units = 1, activation = output_activation)(dense1)
model = Model(inputs=inputs, outputs=dense2)
model.compile(optimizer=Adam(lr=1e-5), loss="mean_squared_error", metrics=["accuracy"])
model.summary()
return model
"""
returns parameters for the data generator depending on what procress of teh model creation we are in
"""
def get_data_generator_params(self, step="train"):
# Parameters
params = {'dim': (self.image_height,self.image_width,1),
'augment': True,
'shuffle': True}
if step.lower() == "train":
params['augment'] = True
params['shuffle'] = True
elif step.lower() == "test":
params['augment'] = False
params['shuffle'] = False
return params
"""
returns Data Generator
"""
@abstractmethod
def create_data_generator(self, feature_dataset, label_dataset, batch_size, step="train"):
params = self.get_data_generator_params(step=step)
data_generator = DataGenerator(feature_dataset, label_dataset, batch_size, "binary", **params)
return data_generator
"""
returns list of individual confusion matrices if segmentation, and list of size 1 for binary
"""
@abstractmethod
def calculate_confusion_matrices(self, target_data, prediction_data):
#calculates confusion matrix
conf_matrix = confusion_matrix(y_non_category, y_predict_non_category)
return conf_matrix
def print_statistical_measures(self, stats):
print("----------------------------------")
confusion_matrix = [[stats['TN'], stats['FP']], [stats['FN'], stats['TP']]]
self.print_confusion_matrix(confusion_matrix)
print("----------------------------------")
print("Accuracy: "+str(stats['accuracy']))
print("----------------------------------")
print("False Positive Rate: "+str(stats['FPR']))
print("False Negative Rate: "+str(stats['FNR']))
print("PPV (Precision): "+str(stats['precision']))
print("----------------------------------")
print("Specificity: "+str(stats['specificity']))
print("Sensitivity: "+str(stats['sensitivity']))
print("Total (spec + sens): "+str(stats['total']))
print("----------------------------------")
print("ROC: "+str(stats['ROC']))
print("F1: "+str(stats['F1']))
print("MCC: "+str(stats['MCC']))
print("----------------------------------")
# print()
"""
prints confusion matrix in format
[ TN, FP]
[ FN, TP]
"""
def print_confusion_matrix(self, confusion_matrix):
print("[{0:5d}, {1:5d}]".format(int(confusion_matrix[0][0]), int(confusion_matrix[0][1])))
print("[{0:5d}, {1:5d}]".format(int(confusion_matrix[1][0]), int(confusion_matrix[1][1])))
"""
Calculates statistical measures for each image in target_data
Aggregates confusion matrices and statistical measures
"""
def statistical_analysis(self, target_data, prediction_data, verbose=False):
if verbose:
print("Target data: "+str(len(target_data)))
print("Prediction data: "+str(len(prediction_data)))
#calculates confusion matrix
conf_matrices = self.calculate_confusion_matrices(target_data, prediction_data)
agg_conf_matrices = np.zeros(conf_matrices[0].shape)
all_stats = []
for x in range(0, len(conf_matrices)):
conf_matrix = conf_matrices[x]
stats = self.calculate_statistical_measures(conf_matrix)
if verbose:
print("Confusion matrix "+str(x)+": ")
print(conf_matrix)
self.print_statistical_measures(stats)
agg_conf_matrices += conf_matrix
all_stats.append(stats)
agg_stats = self.calculate_statistical_measures(agg_conf_matrices)
if verbose:
print("Aggregate confusion matrix: ")
print(agg_conf_matrices)
self.print_statistical_measures(agg_stats)
average_stats = {}
#iterates through all statistical metrics
for stat in all_stats[0]:
average_stats[stat] = 0
#iterates through all confusion matrices' states
for x in range(0, len(all_stats)):
try:
average_stats[stat] += all_stats[x][stat]
except Exception as error:
continue
average_stats[stat] /= len(all_stats)
if verbose:
print()
print()
print("Average stats: ")
self.print_statistical_measures(average_stats)
return (all_stats, agg_stats)
"""
predicts on the dataset, and prints a confusion matrix of the results
Returns a 2 item tuple where 0th item is all stats, and 1st item is aggregate stats
"""
def prediction_analysis(self, classifier, feature_dataset, full_label_dataset, batch_size=1, verbose=False):
generator = self.create_data_generator(feature_dataset, full_label_dataset, batch_size, "test")
print("Predicting...")
preds = classifier.predict_generator(generator, steps=int(len(feature_dataset)/batch_size))
try:
print("Feature dataset: "+str(feature_dataset.shape))
print("predictions: "+str(preds.shape))
except Exception as ex:
pass
#gets actual labels
X_images, y_non_category = generator.get_processed_images(start=0, end=len(feature_dataset))
#gets predicted labels
y_predict_non_category = [ t>0.5 for t in preds]
return self.statistical_analysis(y_non_category, y_predict_non_category, verbose)
"""
Ensemble prediction for multi-class classification
Returns weighted predicted determined by the weight of the model making those predictions
params:
models are a list of keras models
weights are a 2D list of lists of weights
X_test is a single test dataset
"""
def ensemble_predictions(self, models, weights, X_test):
# make predictions
predictions = []
for model in models:
generator = self.create_data_generator(X_test, [], 1, "test")
preds = model.predict_generator(generator, steps=len(X_test))
predictions.append(preds)
predictions = np.array(predictions)
# weighted sum of all predictions
summed = np.tensordot(predictions, weights, axes=((0),(0)))
# argmax across classes
# result = np.argmax(summed, axis=1)
# result = summed/len(models)
result = summed
return result
"""
Loss function for optimization process, designed to be minimized
Should be used in differential evolution algorithm
"""
def weighted_averaging_loss_function(self, weights, models, X_test, Y_test):
# normalize weights
normalized_weights = self.normalize(weights)
# calculate error rate
error_rate = 1.0 - self.evaluate_ensemble(models, normalized_weights, X_test, Y_test)
return error_rate
"""
normalize a vector to have unit norm
"""
def normalize(self, weights):
#calculate l1 vector norm
result = np.linalg.norm(weights, 1)
#prevents division by zero
if result == 0.0:
return weights
#returns normalized vector
return weights / result
"""
Evaluates a specific number of models in a weighted ensemble
"""
def evaluate_ensemble(self, models, weights, X_validate, y_validate):
predictions = self.ensemble_predictions(models, weights, X_validate)
y_validate = np.array(y_validate.copy())
predictions = np.array(predictions)
#self.prediction_analysis?
#converts to binary
predictions = [ t>0.5 for t in predictions]
#determines accuracy of the predictions
accuracy = accuracy_score(y_validate, predictions)
print("Weights: "+str(weights)+" | Accuracy: "+str(accuracy))
# print()
return accuracy
"""
Performs weight optimization to find the optimal weights for each model to optimize performance on the provided validation dataset
"""
def get_optimal_weights(self, models, X_validate, Y_validate):
#averaging ensemble (equal weights)
initial_weights = [1.0/len(models) for weight in range(len(models))]
score = self.evaluate_ensemble(models, initial_weights, X_validate, Y_validate)
print('Equal Weights Score: %.3f' % score)
# define bounds on each weight
weight_bounds = [(0.0, 1.0) for model in range(len(models))]
# arguments to the loss function
search_arg = (models, X_validate, Y_validate)
#Performs an optimization function in regards to the provided loss function to get optimal weights
print("Performing Differential Evolution to calculate optimal weights")
result = differential_evolution(func = self.weighted_averaging_loss_function,
bounds = weight_bounds,
args = search_arg,
maxiter = 1, #standard could be 1000
tol = 1e-7,
disp = True)
# get the chosen weights
weights = self.normalize(result['x'])
print('Optimized Weights: %s' % weights)
# evaluate chosen weights
score = self.evaluate_ensemble(models, weights, X_validate, Y_validate)
print('Optimized Weights Score: %.3f' % score)
return weights
"""
Uses a pre-trained model on similar radiographs or data, and uses it as a starting point for this model.
This allows for features already learned to be a starting point, and for hidden layer weights to be the initial weights.
Transfer learning benefits by having much better generalization, meaning less standard deviation, and higher accuracy overall.
"""
def transfer_learning(self):
pass
"""
Iterates through many combinations of hyperparameters and returns the best performing model along with its hyperparameters
Used to determine best hyperparameters instead of manually manipulation
"""
def grid_search(self):
hyperparameters = {}
"""
A resampling technique used to estimate statistics on a population by sampling a dataset with replacement.
Also known as Bootstrapping or Bootstrap Aggregation
Can keep adding ensemble members since bagging does not overfit
https://machinelearningmastery.com/a-gentle-introduction-to-the-bootstrap-method/
"""
def bagging(self, num_models = 1, **train_args):
print("Train arguments: "+str(train_args))
dataset_size = train_args['dataset_size']
X = self.get_processed_image_paths(balanced=train_args['balanced'], max_num=dataset_size)
Y = self.data_handler.read_train_labels() #don't limit, because will use this for finding masks to train_dicom_paths
print("Dataset size: "+str(dataset_size))
print("num models: "+str(num_models))
print()
#list of indices running the length of X
indices = [i for i in range(len(X))]
classifiers = []
X_trains = []
X_validates = []
X_tests = []
Ys = []
Y_validates = []
results = []
for section in range(0, num_models):
## Performes the resampling with replacement ##
train_indices = resample(indices, replace=True, n_samples=int(len(indices)*0.8))
validation_indices = [x for x in indices if x not in train_indices]
# select data
trainX = [X[x] for x in train_indices]
validationX = [X[x] for x in validation_indices]
print("Train X len: "+str(len(trainX)))
print("Validate X len: "+str(len(validationX)))
train_args['X'] = trainX
train_args['Y'] = Y
classifier, X_train_section, X_validate_section, X_test_section, Y_section = self.train(**train_args)
classifiers.append(classifier)
X_trains.append(X_train_section)
X_validates.append(validationX)
X_tests.append(X_test_section)
Ys.append(Y_section)
#gets output validation data
generator = self.create_data_generator(X_validates[-1], Y, len(X_validates[-1]), "test")
X_images, y_non_category = generator.get_processed_images(start=0, end=len(X_validates[-1]))
Y_validates.append(y_non_category)
print("Len X_Validate: "+str(len(X_validates[-1])))
print("Len Y_validate: "+str(len(y_non_category)))
print()
#prints performance on the validation dataset
self.prediction_analysis(classifier, X_validates[-1], Y, batch_size=1, verbose=True)
#also returns the optimal weights
return classifiers, X_trains, X_validates, X_tests, Ys
"""
Creates an ensemble from the models contained in the training history of a single model's training session
Useful if there's high variance during the model training, or if training multiple models
in other ensemble methods in infeasable due to the model's size and training timeframe.
"""
def horizontal_voting_ensemble(self, num_models = 1, **train_args):
pass
"""
Snapshot ensemble involves using an aggressive learning rate during training to get a
diverse collection of models to ensemble during a training session
The aggressive learning rate allows for models in the same training session over close epochs to not be so similar to each other
Useful for deep learning where the computation cost of training is extremely high
"""
def snapshot_ensemble(self):
pass
"""
Incorporates the technique of model-averaging ensembling, which is the process of training multiple of the same neural networks on the same training set,
then averaging their predictions.
This ensembling method can also be weighted, where different models have different weights depending on their performing on a validation dataset
"""
def weighted_model_averaging(self, num_models = 1, **train_args):
print("Train arguments: "+str(train_args))
dataset_size = train_args['dataset_size']
X = self.get_processed_image_paths(balanced=train_args['balanced'], max_num=dataset_size)
Y = self.data_handler.read_train_labels() #don't limit, because will use this for finding masks to train_dicom_paths
print("Dataset size: "+str(dataset_size))
print("num models: "+str(num_models))
print()
classifiers = []
X_trains = []
X_validates = []
X_tests = []
Ys = []
Y_validates = []
results = []
for section in range(0, num_models):
train_args['X'] = X
train_args['Y'] = Y
classifier, X_train_section, X_validate_section, X_test_section, Y_section = self.train(**train_args)
classifiers.append(classifier)
X_trains.append(X_train_section)
X_validates.append(X_validate_section)
X_tests.append(X_test_section)
Ys.append(Y_section)
#gets output validation data
generator = self.create_data_generator(X_validate_section, Y, len(X_validate_section), "test")
X_images, y_non_category = generator.get_processed_images(start=0, end=len(X_validate_section))
Y_validates.append(y_non_category)
print("Len X_Validate: "+str(len(X_validate_section)))
print("Len Y_validate: "+str(len(y_non_category)))
print()
#prints performance on the validation dataset
self.prediction_analysis(classifier, X_validates[-1], Y, batch_size=1, verbose=True)
print("-- Start Weight Optimization --")
weights = self.get_optimal_weights(classifiers, X_validates[0], Y_validates[0])
# weights = [0.39759092, 0.13496959, 0.46743949] #debugging
print("-- End of Weight Optimization --")
#also returns the optimal weights
return classifiers, X_trains, X_validates, X_tests, Ys, weights
"""
takes a dataset, splits into n_splits+1 sections, then split each of those into train and test sections,
then trains a model on each section and ensembles them together to hopefully have one better model that's more stable
than each model together
https://www.sciencedirect.com/science/article/pii/S0925231214007644
Used as an ensemble since a bunch of smaller models might be able to predict better than a large model.
"""
# *args are the important arguments for calling train
def resampling_ensemble(self, n_splits = 0, **train_args):
dataset_size = train_args['dataset_size']
X = self.get_processed_image_paths(balanced=train_args['balanced'], max_num=dataset_size)
Y = self.data_handler.read_train_labels() #don't limit, because will use this for finding masks to train_dicom_paths
print("Dataset size: "+str(dataset_size))
print("n_splits: "+str(n_splits))
section_size = int(dataset_size/(n_splits+1))
print("Section size: "+str(section_size))
print()
classifiers = []
X_trains = []
X_validates = []
X_tests = []
Ys = []
results = []
for section in range(0, n_splits+1):
print("Section: "+str(section+1)+"/"+str(n_splits+1))
start = section*section_size
end = min((section+1)*section_size, len(X))
print("Start: "+str(start)+" : "+str(end))
X_section = X[start:end]
#trains on this section
train_args['X'] = X_section
train_args['Y'] = Y
classifier, X_train_section, X_validate_section, X_test_section, Y_section = self.train(**train_args)
classifiers.append(classifier)
X_trains.append(X_train_section)
X_validates.append(X_validate_section)
X_tests.append(X_test_section)
Ys.append(Y_section)
#performs prediction analysis on results
prediction_analysis = self.prediction_analysis(classifier=classifier,
feature_dataset=X_validate_section,
full_label_dataset=Y_section,
batch_size=train_args['batch_size'])
results.append(prediction_analysis)
return classifiers, X_trains, X_validates, X_tests, Ys
"""
takes a dataset, gets k_folds so that 0.8 of the dataset is for training, 0.2 is for testing, and this portion moves
throughout the dataset so that by the end, each portion of the dataset got a chance to be the test portion.
https://en.wikipedia.org/wiki/Cross-validation_(statistics)
Used to judge performance of a model arch on a dataset
"""
def kfold_cross_validation(self, k_folds = 0, **train_args):
if k_folds<2:
print("Error, K-folds must have at least 2 folds. Please change hyperparameters and reflect that. ")
return None, None, None, None, None
print("Train arguments: "+str(train_args))
dataset_size = train_args['dataset_size']
X = self.get_processed_image_paths(balanced=train_args['balanced'], max_num=dataset_size)
Y = self.data_handler.read_train_labels() #don't limit, because will use this for finding masks to train_dicom_paths
print("Total Feature size: "+str(len(X)))
seed = 12345
#creates keras Kfold object
kfold = KFold(n_splits=k_folds, shuffle=True, random_state=seed)
classifiers = []
X_trains = []
X_validates = []
X_tests = []
Ys = []
results = []
fold_index = 1
for train_indices, test_indices in kfold.split(X):
print()
print("Split "+str(fold_index)+"/"+str(k_folds))
print("Split Train size: "+str(len(train_indices)))
print("Split Test size: "+str(len(test_indices)))
#converts train array into numpy array in order to split by list of indices,
#then converts back to list to be compatible during train method
train_args['X'] = list(np.array(X)[train_indices])
train_args['Y'] = Y
#Be careful of using easly stopping while performing k-fold cross validation
classifier, X_train, X_validate, X_test, Y_section = self.train(**train_args)
classifiers.append(classifier)
X_trains.append(X_train)
X_validates.append(X_validate)
X_tests.append(X_test)
Ys.append(Y_section)
#performs prediction analysis on results
prediction_analysis = self.prediction_analysis(classifier=classifier,
feature_dataset=X_validate_section,
full_label_dataset=Y,
batch_size=train_args['batch_size'])
fold_index += 1
return classifiers, X_trains, X_validates, X_tests, Ys