-
Notifications
You must be signed in to change notification settings - Fork 1
/
train_test_classifier.py
1444 lines (1325 loc) · 75.3 KB
/
train_test_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
import argparse
import json
import logging
import os
from dataclasses import asdict
from datetime import datetime
from pathlib import Path
import copy
import cv2
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.optim as optim
import torch.multiprocessing
torch.multiprocessing.set_sharing_strategy('file_system')
import torchvision.transforms as transforms
from dacite import from_dict
from torch.utils.data import DataLoader, WeightedRandomSampler
from torch.utils.data.dataset import ConcatDataset
from tqdm import tqdm
from gan_compare.constants import get_classifier, make_private_with_epsilon, only_use_opacus_supported_layers
from gan_compare.data_utils.utils import init_seed, setup_logger
from gan_compare.dataset.mammo_dataset import MammographyDataset
from gan_compare.dataset.synthetic_dataset import SyntheticDataset
from gan_compare.dataset.directory_dataset import DirectoryDataset
#from gan_compare.scripts.embedder import get_top_k_from_image, get_index_from_dataloader, get_nn_dataloader, load_embedding_model
from gan_compare.scripts.metrics import (
calc_all_scores,
calc_AUPRC,
calc_AUROC,
calc_loss,
from_logits_to_probs,
output_ROC_curve,
)
from gan_compare.training.classifier_config import ClassifierConfig
from gan_compare.training.io import load_yaml
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--config_path",
type=str,
default="gan_compare/configs/classification_config.yaml",
help="Path to a yaml model config file",
)
parser.add_argument(
"--dataset_path",
type=str,
default=None,
help="If this is set, the paths/metadata in the config.yaml will be ignored. "
"Instead the images in the herein provided dataset_path will be used to create dataloaders."
" Path to a dir containing train/val/test images.",
)
parser.add_argument(
"--only_get_metrics",
action="store_true",
help="Whether to skip training and just evaluate the model saved in the default location.",
)
parser.add_argument(
"--in_checkpoint_path",
type=str,
nargs='+',
default=["model_checkpoints/classifier/classifier.pt"],
help="Only required if --only_get_metrics is set. Path to checkpoint to be loaded.",
)
parser.add_argument(
"--out_checkpoint_path",
type=str,
default=None,
help="Overwrites config.out_checkpoint_path if not None.",
)
parser.add_argument(
"--save_dataset",
action="store_true",
help="Whether to save image patches to images_classifier dir",
)
parser.add_argument(
"--save_per_epoch",
action="store_true",
help="Whether to store the model after each epoch.",
)
parser.add_argument(
"--save_each_n_epochs",
default=299,
type=int,
help="If the model is not stored each epoch, then store it each n_th epoch.",
)
parser.add_argument(
"--device",
type=str,
default="gpu",
help="Device to be used for training/testing",
)
parser.add_argument(
"--seed",
type=int,
default=42,
help="Global random seed.",
)
parser.add_argument(
"--train_sampling_proportion",
type=float,
default=None,
help="The proportion of the images in the training dataset that are actually used during training.",
)
parser.add_argument(
"--use_dp",
action="store_true",
help="The switch that decides whether DP should be enabled or not during training.",
)
parser.add_argument(
"--density_filter",
action="store_true",
help="The switch that starts breast density specific lesion filtering during training (only 1+2) and separate tests per density class group (e.g. 1+2 vs 3+4).",
)
parser.add_argument(
"--train_densities",
type=list,
default=[1, 2],
help="The density types used for training and splitted in testing.",
)
parser.add_argument(
"--all_densities",
type=list,
default=[1, 2, 3, 4],
help="All possible density types used for training, validation and testing.",
)
parser.add_argument(
"--mass_margin_filter",
action="store_true",
help="The switch that starts mass margin specific lesion filtering during training (e.g. only 1+2) and separate tests per class group (e.g. 1+2 vs 3+4).",
)
parser.add_argument(
"--train_mass_margins", # everything but these are used for training
type=list,
default=["obscured", "ill_defined"],
help="The mass margin types used for training and splitted in testing.",
)
parser.add_argument(
"--mass_subtlety_filter",
action="store_true",
help="The switch that starts mass susceptibility specific lesion filtering during training (e.g. only 1+2) and separate tests per class group (e.g. 1+2 vs 3+4).",
)
parser.add_argument(
"--train_subtleties", # everything but these are used for training
type=list,
default=[5], # [0,1,2,3],
help="The mass susceptibility (e.g. 1 to 5) used for training and splitted in testing.",
)
parser.add_argument(
"--all_subtleties",
type=list,
default=[0, 1, 2, 3, 4, 5],
help="All possible subtlety types used for training, validation and testing.",
)
parser.add_argument(
"--ensemble_strategies",
type=list,
default=["1"],
help="1=Voting as average of model predictions, 2=Voting as weighted average of model predictions weighted by metric on validation set, 3=Majority voting where all models have equal voting weight, 4=Majority voting where each model's vote is weighted by validation loss, 5=Voting as weighted average of model predictions weighted by metric over the top k validation set nearest neighbors of each test sample.",
)
parser.add_argument(
"--ensemble_weight_multiplier",
type=str,
default="val_loss",
help="The validation set metric for weighting models in ensemble. One of: [val_loss, val_loss^2, val_acc, val_auroc, val_auprc, val_auprc",
)
parser.add_argument(
"--weighting_by_rank",
action="store_true",
help="If the ensemble is weighted, we can either weight by model rank (e.g. best val_acc => rank 1 => weight multipler = 10*num_models), or, without ranking directly multiply by validation metric (e.g. val_acc = weight multipler)",
)
parser.add_argument(
"--validation_set",
action="store_true",
help="If this flag is set to true and only_get_metrics is also true, we evaluate on the validation set instead of on the test set.",
)
parser.add_argument(
"--embedding_model_type",
type=str,
default="inceptionv3",
help="In case embeddings are generated (e.g. to weight ensembles via ANN), then this model is used to create embeddings. Choose from: 'config' 'swin' 'inceptionv3' 'vgg16' 'resnet50'.",
)
parser.add_argument(
"--top_k",
type=str,
default="10",
help="Number of returned indices in approx nn search.",
)
parser.add_argument(
"--remove_all_but_l_models",
type=str,
default=None,
help="Number l (e.g. set to '10') of remaining models. models are removed with strategy 5.",
)
parser.add_argument(
"--use_training_in_ann",
action="store_true",
help="Use the training dataset instead of the validation dataset to select/weight best models",
)
parser.add_argument(
"--num_models_to_remove",
type=int,
default=None,
help="Number of models in the ensemble to be removed in each batch when iterating over test set batches.",
)
parser.add_argument(
"--min_num_models",
type=int,
default=10,
help="If models are to be removed, then the number of models in the ensemble cannot be less than min_num_models.",
)
parser.set_defaults(use_dp=False)
args = parser.parse_args()
return args
def main():
args = parse_args()
# Parse config file
try:
config_dict = load_yaml(path=args.config_path)
except:
full_config_path = os.path.join(os.getcwd(),
args.config_path) # in case relative paths are given and don't work
config_dict = load_yaml(path=full_config_path)
config = from_dict(ClassifierConfig, config_dict)
config.logfile_path = config.logfile_path.replace(".", f"_seed{args.seed}.")
logfilename, logfile_path = setup_logger(logfile_path=config.logfile_path, log_level=config.log_level)
# FIXME For fast testing:
#config.num_epochs = 1
if args.out_checkpoint_path is not None:
config.out_checkpoint_path = args.out_checkpoint_path
if not config.out_checkpoint_path.endswith(".pt"):
if args.save_each_n_epochs is None and not args.save_per_epoch:
config.out_checkpoint_path += (
f'{datetime.now().strftime("%m-%d-%Y_%H-%M-%S")}/classifier.pt'
)
else:
config.out_checkpoint_path = os.path.join(config.out_checkpoint_path, f'classifier.pt')
logging.info(str(asdict(config)))
# logging.info("Classifier LR: "+ str(config.clf_lr))
logging.info(str(args))
logging.info(
"Loading dataset..."
) # When we have more datasets implemented, we can specify which one(s) to load in config.
init_seed(args.seed) # setting the seed from the args
device = torch.device(
"cuda" if (torch.cuda.is_available() and config.ngpu > 0 and args.device != "cpu") else "cpu"
)
logging.info(f"Device: {device}")
criterion = get_criterion(config)
logging.info(f"Loss function: {criterion}")
net = get_classifier(config, device=device).to(device)
net.to(device)
if config.use_synthetic:
assert (
config.synthetic_data_dir is not None
), "If you want to use synthetic data, you must provide a diretory with the patches in config.synthetic_data_dir."
if config.no_transforms:
train_transform = transforms.Compose(
[
transforms.Normalize((0.5), (0.5)),
]
)
else:
train_transform = transforms.Compose(
[
# transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.RandomVerticalFlip(),
transforms.Normalize((0.5), (0.5)),
]
)
val_transform = transforms.Compose(
[
transforms.Normalize((0.5), (0.5)),
]
)
test_transform = transforms.Compose(
[
transforms.Normalize((0.5), (0.5)),
]
)
if args.train_sampling_proportion is not None:
# overriding config value if function argument train_sampling_proportion is received.
logging.warning(
f"config.train_sampling_ratio ({config.train_sampling_ratio}) is overwritten with args.train_sampling_proportion ({args.train_sampling_proportion}).")
config.train_sampling_ratio = args.train_sampling_proportion
density_filter_train = None
density_filter_test1 = None
density_filter_test2 = None
mass_margin_filter_train = None
mass_margin_filter_test1 = None
mass_margin_filter_test2 = None
mass_subtlety_filter_train = None
mass_subtlety_filter_test1 = None
mass_subtlety_filter_test2 = None
if args.density_filter:
args.train_densities = [int(density) for density in args.train_densities if str(density).isnumeric()]
density_filter_train = args.train_densities
density_filter_test1 = args.train_densities
density_filter_test2 = [int(density) for density in args.all_densities if
int(density) not in args.train_densities]
if args.mass_margin_filter:
mass_margin_filter_train = copy.deepcopy(args.train_mass_margins)
# mass_margin_filter_train.append("!")
mass_margin_filter_test1 = copy.deepcopy(args.train_mass_margins)
# mass_margin_filter_test1.append("!")
mass_margin_filter_test2 = copy.deepcopy(args.train_mass_margins)
mass_margin_filter_test2.append("!")
if args.mass_subtlety_filter:
args.train_subtleties = [int(subtlety) for subtlety in args.train_subtleties if str(subtlety).isnumeric()]
mass_subtlety_filter_train = args.train_subtleties
mass_subtlety_filter_test1 = args.train_subtleties
mass_subtlety_filter_test2 = [int(subtlety) for subtlety in args.all_subtleties if
int(subtlety) not in args.train_subtleties]
#If we want to load the dataset from a directory instead of the config file, we do it here.
if args.dataset_path is not None:
logging.info(f"Loading dataset from directory rather than metadata. Directory root: {args.dataset_path}")
train_dataset = DirectoryDataset(
config=config, # e.g. used to determine which dataset to use (e.g. cbis-ddsm, bcdr), and image size
subset="train",
transform = train_transform,
dataset_path = args.dataset_path,
)
val_dataset = DirectoryDataset(
config=config, # e.g. used to determine which dataset to use (e.g. cbis-ddsm, bcdr), and image size
subset="val",
transform = val_transform,
dataset_path = args.dataset_path,
)
test_dataset1 = DirectoryDataset(
config=config, # e.g. used to determine which dataset to use (e.g. cbis-ddsm, bcdr), and image size
subset="test",
transform = test_transform,
dataset_path = args.dataset_path,
dataset_name="cbis-ddsm" # overrides the dataset specified in the config
)
test_dataset2 = DirectoryDataset(
config=config, # e.g. used to determine which dataset to use (e.g. cbis-ddsm, bcdr), and image size
subset="test",
transform = test_transform,
dataset_path = args.dataset_path,
dataset_name="bcdr" # overrides the dataset specified in the config
)
else:
train_dataset = MammographyDataset(
metadata_path=config.metadata_path,
split_path=config.split_path,
subset="train",
config=config,
sampling_ratio=config.train_sampling_ratio,
transform=train_transform,
density_filter=density_filter_train,
mass_margin_filter=mass_margin_filter_train,
mass_subtlety_filter=mass_subtlety_filter_train,
)
val_dataset = MammographyDataset(
metadata_path=config.metadata_path,
split_path=config.split_path,
subset="val",
config=config,
transform=val_transform,
density_filter=density_filter_train,
mass_margin_filter=mass_margin_filter_train,
mass_subtlety_filter=mass_subtlety_filter_train,
)
if args.density_filter or args.mass_margin_filter or args.mass_subtlety_filter:
test_dataset1 = MammographyDataset(
metadata_path=config.metadata_path,
split_path=config.split_path,
subset="test",
config=config,
transform=test_transform,
density_filter=density_filter_test1,
mass_margin_filter=mass_margin_filter_test1,
mass_subtlety_filter=mass_subtlety_filter_test1,
return_indices=str(5) in args.ensemble_strategies,
)
test_dataset2 = MammographyDataset(
metadata_path=config.metadata_path,
split_path=config.split_path,
subset="test",
config=config,
transform=test_transform,
density_filter=density_filter_test2,
mass_margin_filter=mass_margin_filter_test2,
mass_subtlety_filter=mass_subtlety_filter_test2,
return_indices=str(5) in args.ensemble_strategies,
)
else:
test_dataset = MammographyDataset(
metadata_path=config.metadata_path,
split_path=config.split_path,
subset="test",
config=config,
transform=test_transform,
return_indices=str(5) in args.ensemble_strategies,
)
train_dataset_no_synth = train_dataset
if config.use_synthetic:
# APPEND SYNTHETIC DATA
synth_train_images = SyntheticDataset(
transform=train_transform,
config=config,
)
train_dataset = ConcatDataset([train_dataset, synth_train_images])
logging.info(
f"Number of synthetic patches added to training set: {len(synth_train_images)}"
)
if config.binary_classification and False: # and False:
num_train_negative, num_train_positive = get_label_balance_info(train_dataset, "train",
config) # needed for WeightedRandomSampler
# num_val_negative, num_val_positive = get_label_balance_info(val_dataset, "val", config) # just for printing info
# num_test_negative, num_test_positive = get_label_balance_info(test_dataset, "test", config) # just for printing info
# Compute the weights for the WeightedRandomSampler for the training set:
# Example: labels of training set: [true, true, false] => weight_true = 3/2; weight_false = 3/1
weight_negative = len(train_dataset) / num_train_negative
weight_positive = len(train_dataset) / num_train_positive
train_weights = []
if config.classes == "is_healthy":
train_weights.extend(
train_dataset_no_synth.arrange_weights_healthy(weight_negative, weight_positive)
)
else:
train_weights.extend(
arrange_weights(weight_class_positive=weight_positive, weight_class_negative=weight_negative,
dataset=train_dataset)
)
train_sampler = WeightedRandomSampler(train_weights, len(train_dataset))
else:
train_sampler = None
# We don't want any sample weights in validation and test sets, so we stick with shuffle=True below.
if len(train_dataset) > 0:
train_dataloader = DataLoader(
train_dataset,
batch_size=config.batch_size,
num_workers=config.workers,
sampler=train_sampler,
shuffle=True,
)
if len(val_dataset) > 0:
val_dataloader = DataLoader(
val_dataset,
batch_size=config.batch_size,
num_workers=config.workers,
shuffle=False,
)
test_dataloaders = []
if test_dataset1 is not None and test_dataset2 is not None and args.dataset_path is not None:
test_dataloaders.append(
DataLoader(
test_dataset1,
batch_size=config.batch_size,
num_workers=config.workers,
shuffle=False,
)
)
test_dataloaders.append(
DataLoader(
test_dataset2,
batch_size=config.batch_size,
num_workers=config.workers,
shuffle=False,
)
)
elif args.density_filter or args.mass_margin_filter or args.mass_subtlety_filter:
test_dataloaders.append(
DataLoader(
test_dataset1,
batch_size=config.batch_size if not str(5) in args.ensemble_strategies else 1,
num_workers=config.workers,
shuffle=False,
)
)
test_dataloaders.append(
DataLoader(
test_dataset2,
batch_size=config.batch_size if not str(5) in args.ensemble_strategies else 1,
num_workers=config.workers,
shuffle=False,
)
)
else:
test_dataloaders.append(
DataLoader(
test_dataset,
batch_size=config.batch_size if not str(5) in args.ensemble_strategies else 1,
num_workers=config.workers,
shuffle=False,
)
)
if not Path(config.out_checkpoint_path).parent.exists():
os.makedirs(Path(config.out_checkpoint_path).parent.resolve(), exist_ok=True)
if args.save_dataset:
# This code section is only for saving patches as image files and further info about the patch if needed.
# The program stops execution after this section and performs no training.
# TODO: state_dict name should probably be in config yaml instead of hardcoded.
net.load_state_dict(
torch.load("model_checkpoints/classifier 50 no synth/classifier.pt", map_location=device)
)
net.eval()
# TODO refactor (make optional & parametrize) or remove saving dataset
save_data_path = Path("save_dataset")
with open(save_data_path / "validation.txt", "w") as f:
f.write("index, y_prob\n")
cnt = 0
metapoints = []
for data in tqdm(
test_dataset
): # this has built-in shuffling; if not shuffled, only lesion-containing patches will be output first
sample, label, image, r, d = data
outputs = net(sample[np.newaxis, ...])
# for y_prob_logit, label, image, r, d in zip(outputs.data, labels, images, rs, ds):
y_prob_logit = outputs.data
y_prob = from_logits_to_probs(y_prob_logit)
metapoint = {
"label": label,
"roi_type": r,
"dataset": d,
"cnt": cnt,
"y_prob": y_prob.numpy().tolist(),
}
metapoints.append(metapoint)
# with open(save_data_path / "validation.txt", "a") as f:
# f.write(f'{cnt}, {y_prob}\n')
label = "healthy" if int(label) == 1 else "with_lesions"
out_image_dir = save_data_path / "validation" / str(label)
out_image_dir.mkdir(parents=True, exist_ok=True)
out_image_path = out_image_dir / f"{cnt}.png"
cv2.imwrite(str(out_image_path), np.array(image))
cnt += 1
with open(save_data_path / "validation.json", "w") as f:
f.write(json.dumps(metapoints))
logging.info(f"Saved data samples to {save_data_path.resolve()}")
exit()
if args.use_dp or config.use_dp: # for ease of use, we want to allow activating DP both via args as well as via config. Both have default=False
net = only_use_opacus_supported_layers(net=net)
if not args.only_get_metrics:
# Inputting the seed information into the checkpoint saving path.
config.out_checkpoint_path = config.out_checkpoint_path.replace(".",
f"_seed{str(args.seed).strip()}_{datetime.now().strftime('%m-%d-%Y_%H-%M-%S')}.")
# PREPARE TRAINING
# TODO: Optimizer params (lr, momentum) should be moved to classifier_config.
if config.optimizer_type == "sgd":
optimizer = optim.SGD(net.parameters(), lr=config.clf_lr, momentum=0.9) # lr=0.001, momentum=0.9)
elif config.optimizer_type == "adam":
optimizer = optim.Adam(net.parameters(), lr=config.clf_lr, weight_decay=config.clf_weight_decay)
elif config.optimizer_type == "adamw":
optimizer = optim.AdamW(net.parameters(), lr=config.clf_lr, weight_decay=config.clf_weight_decay)
if args.use_dp or config.use_dp: # for ease of use, we want to allow activating DP both via args as well as via config. Both have default=False
net, optimizer, train_dataloader, privacy_engine = make_private_with_epsilon(net=net, optimizer=optimizer,
dataloader=train_dataloader,
dp_target_epsilon=config.dp_target_epsilon,
dp_target_delta=config.dp_target_delta,
dp_max_grad_norm=config.dp_max_grad_norm,
num_epochs=config.num_epochs,
auto_validate_model=False,
grad_sample_mode=None, # "ew"
)
final_epsilon = float("inf")
best_loss = float("inf")
best_f1 = 0
best_epoch = 0
best_prc_auc = 0
# START TRAINING LOOP
for epoch in tqdm(
range(config.num_epochs)
): # loop over the dataset multiple times
running_loss = 0.0
y_true_train = []
y_prob_logit_train = []
train_loss = []
logging.info(f"Training in epoch {epoch}... {args.config_path}")
for i, data in enumerate(tqdm(train_dataloader)):
# get the inputs; data is a list of [inputs, labels]
try:
samples, labels, _, _, _, _ = data
except:
samples, labels, _, _, _ = data
if len(samples) <= 1:
continue # batch normalization won't work if samples too small (https://stackoverflow.com/a/48344268/3692004)
# Explicitely setting model into training mode.
net.train()
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = net(samples.to(device))
logging.debug(f"outputs (shape:{outputs.shape}): {outputs}")
logging.debug(f"labels: {labels}")
# Converting to float as model (e.g. swin) can return doubles leading to dtpye mismatch error.
y_true_train.append(labels)
# logging.info(f"outputs type: {outputs.dtype}, outputs shape: {outputs.shape}, labels type: {labels.dtype}, labels shape: {labels.shape}")
# if outputs.shape != labels.shape:
# labels = torch.unsqueeze(labels, dim=-1).to(device).to(torch.float32)
try:
loss = criterion(outputs, labels.to(device))
except:
labels = labels.type(torch.float)
loss = criterion(outputs, (labels.to(device)))
loss.backward()
optimizer.step()
# print statistics
running_loss += loss.item()
if i % 2000 == 1999: # print every 2000 mini-batches
if args.use_dp or config.use_dp: # for ease of use, we want to allow activating DP both via args as well as via config. Both have default=False
epsilon = privacy_engine.get_epsilon(config.dp_target_delta)
logging.info(
"[%d, %5d] loss: %.3f DP(ε=%.3f,δ=%.3f) " % (
epoch + 1, i + 1, running_loss / 2000, epsilon, config.dp_target_delta)
)
else:
logging.info(
"[%d, %5d] loss: %.3f" % (epoch + 1, i + 1, running_loss / 2000)
)
running_loss = 0.0
y_prob_logit_train.append(outputs.data.cpu())
# train_loss.append(loss.detach().cpu())
# Calculating metrics for training
y_true_train = torch.cat(y_true_train)
y_prob_logit_train = torch.cat(y_prob_logit_train)
y_prob_train = from_logits_to_probs(y_prob_logit_train)
_, _, prec_rec_f1, roc_auc, prc_auc = calc_all_scores(
y_true_train,
y_prob_train,
train_loss,
"Training",
config,
epoch,
config_path=args.config_path,
test_only=args.only_get_metrics,
)
# saving model
if args.save_per_epoch:
torch.save(net.state_dict(), config.out_checkpoint_path.replace("best_classifier", f"{epoch}"))
elif epoch % args.save_each_n_epochs == 0 and epoch != 0:
torch.save(net.state_dict(), config.out_checkpoint_path.replace("best_classifier", f"{epoch}"))
# VALIDATE
val_loss = []
with torch.no_grad():
y_true = []
y_prob_logit = []
net.eval()
if args.use_dp or config.use_dp: # for ease of use, we want to allow activating DP both via args as well as via config. Both have default=False
epsilon = privacy_engine.get_epsilon(config.dp_target_delta)
logging.info(
f"Validating in epoch {epoch}... {args.config_path}. Current DP -> DP(ε={epsilon}, δ={config.dp_target_delta}).")
else:
logging.info(f"Validating in epoch {epoch}... {args.config_path} ")
for i, data in enumerate(tqdm(val_dataloader)):
try:
samples, labels, _, _, _, _ = data
except:
samples, labels, _, _, _ = data
# logging.info(images.size())
outputs = net(samples.to(device))
# if outputs.shape != labels.shape:
# labels = torch.unsqueeze(labels, dim=-1).to(device).to(torch.float32)
val_loss.append(criterion(outputs.cpu(), labels))
y_true.append(labels)
y_prob_logit.append(outputs.data.cpu())
val_loss = np.mean(val_loss)
if config.is_regression:
loss = calc_loss(val_loss, "Valid", epoch)
if not (args.use_dp or config.use_dp) or (
(args.use_dp or config.use_dp) and is_epsilon_within_target(
target_epsilon=config.dp_target_epsilon,
actual_epsilon=privacy_engine.get_epsilon(config.dp_target_delta))):
# if we use DP, then we want the epsilon to be at least a specific value (e.g. 5% within target) to accept a DP model as best model.
if loss < best_loss:
best_loss = loss
best_epoch = epoch
torch.save(net.state_dict(), config.out_checkpoint_path)
if args.use_dp or config.use_dp: # for ease of use, we want to allow activating DP both via args as well as via config. Both have default=False
epsilon = privacy_engine.get_epsilon(config.dp_target_delta)
logging.info(
f"Saving best model so far at epoch {epoch} with DP(ε={epsilon},δ={config.dp_target_delta}) with loss = {loss} (best: lowest val_loss)"
)
else:
logging.info(
f"Saving best model so far at epoch {epoch} with loss = {loss} (best: lowest val_loss)"
)
else: # classification
y_true = torch.cat(y_true)
y_prob_logit = torch.cat(y_prob_logit)
y_prob = from_logits_to_probs(y_prob_logit)
config_path = f"{args.config_path} with DP(ε={privacy_engine.get_epsilon(config.dp_target_delta)}, δ={config.dp_target_delta}) with target ε={config.dp_target_epsilon} and max_grad_norm={config.dp_max_grad_norm}" if (
args.use_dp or config.use_dp) else f"{args.config_path} without DP"
_, _, prec_rec_f1, roc_auc, prc_auc = calc_all_scores(
y_true,
y_prob,
val_loss,
"Valid",
config,
epoch,
config_path=config_path,
write_results_txt=False,
test_only=args.only_get_metrics,
)
if not (args.use_dp or config.use_dp) or (
(args.use_dp or config.use_dp) and is_epsilon_within_target(
target_epsilon=config.dp_target_epsilon,
actual_epsilon=privacy_engine.get_epsilon(config.dp_target_delta))):
# if we use DP, then we want the epsilon to be at least a specific value (e.g. 5% within target) to accept a DP model as best model.
val_f1 = prec_rec_f1[-1:][0]
# if val_loss < best_loss:
# if val_f1 > best_f1:
if prc_auc is None or np.isnan(prc_auc):
prc_auc = best_prc_auc
if prc_auc > best_prc_auc or (prc_auc == best_prc_auc and val_loss < best_loss):
best_loss = val_loss
best_f1 = val_f1
best_prc_auc = prc_auc
best_epoch = epoch
torch.save(net.state_dict(), config.out_checkpoint_path)
if args.use_dp or config.use_dp: # for ease of use, we want to allow activating DP both via args as well as via config. Both have default=False
final_epsilon = privacy_engine.get_epsilon(config.dp_target_delta)
logging.info(
f"Saving best model so far at epoch {epoch} with DP(ε={final_epsilon},δ={config.dp_target_delta}), with f1 = {val_f1}, au prc = {prc_auc}, and val_loss = {val_loss} (best: highest prc_auc on validation)"
)
else:
logging.info(
f"Saving best model so far at epoch {epoch} with f1 = {val_f1}, au prc = {prc_auc}, and val_loss = {val_loss} (best: highest prc_auc on validation)"
)
logging.info("Finished Training")
logging.info(f"Saved best model state dict to {config.out_checkpoint_path}")
if args.use_dp or config.use_dp: # for ease of use, we want to allow activating DP both via args as well as via config. Both have default=False
logging.info(
f"Best model was achieved after {best_epoch} epochs, with val loss = {best_loss} and DP(ε={final_epsilon},δ={config.dp_target_delta})."
)
else:
logging.info(
f"Best model was achieved after {best_epoch} epochs, with val loss = {best_loss}"
)
# TESTING
test(config=config, args=args, net=net, device=device, test_dataloaders=test_dataloaders, logfile_path=logfile_path,
best_epoch=None if args.only_get_metrics else best_epoch, criterion=criterion, val_dataloader=val_dataloader,
val_dataset=val_dataset, train_dataloader=train_dataloader, train_dataset=train_dataset, )
def make_net_private(net, config, dataloader) -> nn.Module:
if config.optimizer_type == "sgd":
optimizer = optim.SGD(net.parameters(), lr=config.clf_lr, momentum=0.9) # lr=0.001, momentum=0.9)
elif config.optimizer_type == "adam":
optimizer = optim.Adam(net.parameters(), lr=config.clf_lr, weight_decay=config.clf_weight_decay)
elif config.optimizer_type == "adamw":
optimizer = optim.AdamW(net.parameters(), lr=config.clf_lr, weight_decay=config.clf_weight_decay)
net, _, _, _ = make_private_with_epsilon(net=net,
optimizer=optimizer,
dataloader=dataloader,
dp_target_epsilon=config.dp_target_epsilon,
dp_target_delta=config.dp_target_delta,
dp_max_grad_norm=config.dp_max_grad_norm,
num_epochs=config.num_epochs,
auto_validate_model=False,
grad_sample_mode=None, # "ew"
)
return net
def get_model_name(model_path) -> str:
if 'swin_t_radimagenet_frozen' in model_path.lower():
return 'swin_t_radimagenet_frozen'
elif 'swin_t_imagenet_frozen' in model_path.lower():
return 'swin_t_imagenet_frozen'
elif 'swin_t_radimagenet' in model_path.lower():
return 'swin_t_radimagenet'
elif 'swin_t_imagenet' in model_path.lower():
return 'swin_t_imagenet'
elif 'swin_transformer' in model_path.lower():
return 'swin_transformer'
elif 'cnn' in model_path.lower():
return 'cnn'
else:
#raise Exception(f"None of the available model names found in model path '{model_path}'")
logging.warning(f"None of the available model names found in model path '{model_path}'. Returning 'swin_t_imagenet_frozen' as default.")
return 'swin_t_imagenet_frozen'
def test(config, args, net, device, test_dataloaders: list, logfile_path, best_epoch, criterion, val_dataloader=None,
val_dataset=None, train_dataloader=None, train_dataset=None):
model_paths = []
if args.only_get_metrics:
model_paths = [str(in_path) for in_path in args.in_checkpoint_path if
len(str(in_path)) > 2] # avoid commas introduced via cmd line
else:
model_paths.append(config.out_checkpoint_path)
if len(model_paths) > 1:
logging.info(f"Ensemble testing of models, as more than one model path detected: {model_paths}")
models = prepare_models(config, args, model_paths, test_dataloaders, device, net)
if val_dataloader is not None and args.validation_set:
for i, model in enumerate(models):
logging.info(f"Getting validation score for model {i + 1} of {len(models)}...")
description = f'VALIDATION_seed{args.seed}_model{i + 1}of{len(models)}'
get_val_scores(config, args, model, val_dataloader, device, description, write_results_txt=True)
else:
for idx, test_dataloader in enumerate(test_dataloaders):
logging.info(f"Beginning test for test_dataloader {idx + 1} of {len(test_dataloaders)}...")
y_probs_list = []
for idx2, model in enumerate(models):
logging.info(f"Beginning test for model {idx2 + 1} of {len(models)}...")
with torch.no_grad():
y_true = []
y_prob_logit = []
test_loss = []
roi_type_arr = []
id_arr = []
logging.info(f"Testing for args: {args}")
for i, data in enumerate(tqdm(test_dataloader)):
try:
samples, labels, _, roi_types, ids, _ = data
except:
samples, labels, _, roi_types, ids = data
# logging.info(images.size())
samples, model = samples.to(device), model.to(device)
outputs = model(samples)
# if outputs.shape != labels.shape:
# labels = torch.unsqueeze(labels, dim=-1).to(device).to(torch.float32)
test_loss.append(criterion(outputs.cpu(), labels))
y_true.append(labels)
y_prob_logit.append(outputs.data.cpu())
roi_type_arr.extend(roi_types)
id_arr.extend(ids)
# Accumulate results over entire dataset
test_loss = np.mean(test_loss)
y_true = torch.cat(y_true)
y_prob_logit = torch.cat(y_prob_logit)
y_prob = from_logits_to_probs(y_prob_logit)
y_probs_list.append(y_prob)
# Calculate the metrics per model
# write_results_txt = True if len(models)==1 else False # Do only write results to txt if we only test one model and not an ensemble?
get_metrics_and_outputs(config, args, y_prob, y_true, test_loss, best_epoch, logfile_path,
roi_type_arr, id_arr, split="test",
description=f'seed{args.seed}_model{idx2 + 1}of{len(models)}_testdl{idx + 1}of{len(test_dataloaders)}',
write_results_txt=True)
test_ensemble(config, args, models, y_probs_list, idx, logfile_path, y_true, roi_type_arr, id_arr,
device=device, val_dataloader=val_dataloader, val_dataset=val_dataset,
test_dataloader=test_dataloader, train_dataloader=train_dataloader,
train_dataset=train_dataset, )
logging.info("Finished testing.")
def get_val_scores(config, args, net, val_dataloader, device, description='get_val_scores', write_results_txt=False,
is_logged: bool = True):
criterion = get_criterion(config)
# VALIDATE
net.to(device)
val_loss = []
with torch.no_grad():
y_true = []
y_prob_logit = []
iterable = enumerate(tqdm(val_dataloader)) if is_logged else enumerate(val_dataloader)
for i, data in iterable:
try:
samples, labels, _, _, _, _ = data
except:
samples, labels, _, _, _ = data
outputs = net(samples.to(device))
# if outputs.shape != labels.shape:
# labels = torch.unsqueeze(labels, dim=-1).to(device).to(torch.float32)
val_loss.append(criterion(outputs.cpu(), labels))
y_true.append(labels)
y_prob_logit.append(outputs.data.cpu())
y_true = torch.cat(y_true)
y_prob_logit = torch.cat(y_prob_logit)
y_prob = from_logits_to_probs(y_prob_logit)
val_loss, acc_score, prec_rec_f1, roc_auc, prc_auc = calc_all_scores(
y_true,
y_prob,
val_loss,
"Valid",
config,
epoch=None,
config_path=args.config_path,
write_results_txt=write_results_txt,
description=description,
test_only=args.only_get_metrics,
is_logged=is_logged,
)
return val_loss, acc_score, prec_rec_f1, roc_auc, prc_auc
def test_ensemble(config, args, models, y_probs_list, idx, logfile_path, y_true, roi_type_arr, id_arr, device,
val_dataloader=None, val_dataset=None, test_dataloader=None, train_dataloader=None,
train_dataset=None, ):
# Model Ensembling
logging.debug(f"models={models}")
logging.info(f"Number of models: {len(models)}, Number of y_probs: {len(y_probs_list)}")
if len(models) > 1:
# 1 = voting by mean probabilities of all models i.e. mean over probabilities of multiple models
if str(1) in args.ensemble_strategies:
mean_y_probs = None
stacked_y_probs = torch.stack(y_probs_list)
logging.info(f"final stacked_y_probs.shape: {stacked_y_probs.shape}")
logging.debug(f"final stacked_y_probs: {stacked_y_probs}")
mean_y_probs = torch.mean(stacked_y_probs, 0)
logging.info(f"final mean_y_probs.shape: {mean_y_probs.shape}")
logging.debug(f"final mean_y_probs: {mean_y_probs}")
# y_true, roi_type_arr, id_arr, and logfile_path don't change between models
get_metrics_and_outputs(config=config, args=args, y_prob=mean_y_probs, y_true=y_true, test_loss=None,
best_epoch=f"ensemble_w_strategy{args.ensemble_strategies}",
logfile_path=logfile_path,
roi_type_arr=roi_type_arr, id_arr=id_arr, split="test",
description=f'ensemble_w_strategy_1of{args.ensemble_strategies}_of_{len(models)}_models_testdl{idx + 1}')
if str(2) in args.ensemble_strategies:
weight_multiplier_list = []
mean_y_probs = None
for i, y_probs in enumerate(y_probs_list):
# get weight multiplier
val_loss, val_acc_score, val_prec_rec_f1_scores, val_roc_auc, val_prc_auc = get_val_scores(config, args,
net=models[
i],
val_dataloader=val_dataloader,
device=device)
weight_multiplier = get_weight_multiplier(args, val_loss, val_acc_score, val_prec_rec_f1_scores,
val_roc_auc, val_prc_auc)
logging.info(
f"weight_multiplier {args.ensemble_weight_multiplier} of model {i + 1} of {len(y_probs_list)}: {weight_multiplier}")
if args.weighting_by_rank:
weight_multiplier_list.append({'model_id': i, 'wm': weight_multiplier})
else:
weight_multiplier_list.append(weight_multiplier)
y_probs = y_probs * weight_multiplier # multiplying tensor with weight
logging.debug(f"{i} y_probs * weight_multiplier shape: {y_probs.shape}")
if mean_y_probs is None:
mean_y_probs = torch.zeros(y_probs.shape)
mean_y_probs = mean_y_probs.add(y_probs) # addition of the two tensors
if args.weighting_by_rank:
# sort by wm value in ascending order (e.g. smallest value, i.e. worst model, first)
sorted_weight_multiplier_list = sorted(weight_multiplier_list, key=lambda wml: wml['wm']) #
# now replace wm values with values based on rank of model
weight_multiplier_list = []
for i, swm in enumerate(sorted_weight_multiplier_list):