-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_fldo.py
executable file
·615 lines (488 loc) · 29.4 KB
/
main_fldo.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
"""
Created on May 4, 2023.
main_fldo.py
@author: Soroosh Tayebi Arasteh <[email protected]>
https://github.com/tayebiarasteh/
"""
import pdb
import torch
import os
from torch.utils.data import Dataset
from torch.nn import BCEWithLogitsLoss
from torchvision import transforms, models
import timm
import numpy as np
from sklearn import metrics
# from mne.stats import fdr_correction
from config.serde import open_experiment, create_experiment, delete_experiment, write_config
from Train_Valid_fldo import Training
from Prediction_fldo import Prediction
from data.data_provider import vindr_data_loader_2D, chexpert_data_loader_2D, mimic_data_loader_2D, cxr14_data_loader_2D, padchest_data_loader_2D
import warnings
warnings.filterwarnings('ignore')
def main_train_central_2D(global_config_path="", valid=False, resume=False, augment=False, experiment_name='name', dataset_name='vindr',
pretrained=False, vit=False, dinov2=True, image_size=224, batch_size=30, lr=1e-5):
"""Main function for training + validation centrally
Parameters
----------
global_config_path: str
always global_config_path="/FLdomain/config/config.yaml"
valid: bool
if we want to do validation
resume: bool
if we are resuming training on a model
augment: bool
if we want to have data augmentation during training
experiment_name: str
name of the experiment, in case of resuming training.
name of new experiment, in case of new training.
"""
if resume == True:
params = open_experiment(experiment_name, global_config_path)
else:
params = create_experiment(experiment_name, global_config_path)
cfg_path = params["cfg_path"]
if dataset_name == 'vindr':
train_dataset = vindr_data_loader_2D(cfg_path=cfg_path, mode='train', augment=augment, image_size=image_size)
valid_dataset = vindr_data_loader_2D(cfg_path=cfg_path, mode='test', augment=False, image_size=image_size)
elif dataset_name == 'chexpert':
train_dataset = chexpert_data_loader_2D(cfg_path=cfg_path, mode='train', augment=augment, image_size=image_size)
valid_dataset = chexpert_data_loader_2D(cfg_path=cfg_path, mode='test', augment=False, image_size=image_size)
elif dataset_name == 'mimic':
train_dataset = mimic_data_loader_2D(cfg_path=cfg_path, mode='train', augment=augment, image_size=image_size)
valid_dataset = mimic_data_loader_2D(cfg_path=cfg_path, mode='test', augment=False, image_size=image_size)
elif dataset_name == 'cxr14':
train_dataset = cxr14_data_loader_2D(cfg_path=cfg_path, mode='train', augment=augment, image_size=image_size)
valid_dataset = cxr14_data_loader_2D(cfg_path=cfg_path, mode='test', augment=False, image_size=image_size)
elif dataset_name == 'padchest':
train_dataset = padchest_data_loader_2D(cfg_path=cfg_path, mode='train', augment=augment, image_size=image_size)
valid_dataset = padchest_data_loader_2D(cfg_path=cfg_path, mode='test', augment=False, image_size=image_size)
train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size,
pin_memory=True, drop_last=True, shuffle=True, num_workers=10)
weight = train_dataset.pos_weight()
label_names = train_dataset.chosen_labels
if valid:
valid_loader = torch.utils.data.DataLoader(dataset=valid_dataset, batch_size=batch_size,
pin_memory=True, drop_last=False, shuffle=False, num_workers=5)
else:
valid_loader = None
# Changeable network parameters
if vit:
if dinov2:
model = load_pretrained_dinov2(num_classes=len(weight))
else:
model = load_pretrained_timm_model(num_classes=len(weight), pretrained=pretrained, imgsize=image_size)
else:
model = load_pretrained_timm_model(num_classes=len(weight), model_name='resnet50d', pretrained=pretrained)
loss_function = BCEWithLogitsLoss
model_info = params['Network']
model_info['lr'] = lr
model_info['batch_size'] = batch_size
params['Network'] = model_info
write_config(params, cfg_path, sort_keys=True)
if vit:
optimizer = torch.optim.AdamW(model.parameters(), lr=float(lr),
weight_decay=float(params['Network']['weight_decay']))
else:
optimizer = torch.optim.Adam(model.parameters(), lr=float(lr),
weight_decay=float(params['Network']['weight_decay']),
amsgrad=params['Network']['amsgrad'])
trainer = Training(cfg_path, resume=resume, label_names=label_names)
if resume == True:
trainer.load_checkpoint(model=model, optimiser=optimizer, loss_function=loss_function, weight=weight, label_names=label_names)
else:
trainer.setup_model(model=model, optimiser=optimizer, loss_function=loss_function, weight=weight)
trainer.train_epoch(train_loader=train_loader, valid_loader=valid_loader, num_epochs=params['Network']['num_epochs'])
def main_train_federated(global_config_path="", valid=False, resume=False, augment=False, experiment_name='name', train_sites=['vindr', 'cxr14'], pretrained=True, vit=False, dinov2=True, image_size=224, batch_size=30, lr=1e-5):
"""
Parameters
----------
global_config_path: str
always global_config_path="FLdomain/config/config.yaml"
resume: bool
if we are resuming training on a model
experiment_name: str
name of the experiment, in case of resuming training.
name of new experiment, in case of new training.
"""
if resume == True:
params = open_experiment(experiment_name, global_config_path)
else:
params = create_experiment(experiment_name, global_config_path)
cfg_path = params["cfg_path"]
train_loader = []
valid_loader = []
weight_loader = []
loss_function_loader = []
label_names_loader = []
for dataset_name in train_sites:
if dataset_name == 'vindr':
train_dataset_model = vindr_data_loader_2D(cfg_path=cfg_path, mode='train', augment=augment, image_size=image_size)
valid_dataset_model = vindr_data_loader_2D(cfg_path=cfg_path, mode='test', augment=False, image_size=image_size)
elif dataset_name == 'chexpert':
train_dataset_model = chexpert_data_loader_2D(cfg_path=cfg_path, mode='train', augment=augment, image_size=image_size)
valid_dataset_model = chexpert_data_loader_2D(cfg_path=cfg_path, mode='test', augment=False, image_size=image_size)
elif dataset_name == 'mimic':
train_dataset_model = mimic_data_loader_2D(cfg_path=cfg_path, mode='train', augment=augment, image_size=image_size)
valid_dataset_model = mimic_data_loader_2D(cfg_path=cfg_path, mode='test', augment=False, image_size=image_size)
elif dataset_name == 'cxr14':
train_dataset_model = cxr14_data_loader_2D(cfg_path=cfg_path, mode='train', augment=augment, image_size=image_size)
valid_dataset_model = cxr14_data_loader_2D(cfg_path=cfg_path, mode='test', augment=False, image_size=image_size)
elif dataset_name == 'padchest':
train_dataset_model = padchest_data_loader_2D(cfg_path=cfg_path, mode='train', augment=augment, image_size=image_size)
valid_dataset_model = padchest_data_loader_2D(cfg_path=cfg_path, mode='test', augment=False, image_size=image_size)
model_info = params['Network']
model_info['lr'] = lr
model_info['batch_size'] = batch_size
params['Network'] = model_info
write_config(params, cfg_path, sort_keys=True)
weight_model = train_dataset_model.pos_weight()
label_names_model = train_dataset_model.chosen_labels
loss_function_model = BCEWithLogitsLoss
train_loader_model = torch.utils.data.DataLoader(dataset=train_dataset_model,
batch_size=batch_size,
pin_memory=True, drop_last=True, shuffle=True, num_workers=10)
train_loader.append(train_loader_model)
weight_loader.append(weight_model)
loss_function_loader.append(loss_function_model)
label_names_loader.append(label_names_model)
valid_loader_model = torch.utils.data.DataLoader(dataset=valid_dataset_model, batch_size=batch_size,
pin_memory=True, drop_last=False, shuffle=False, num_workers=5)
valid_loader.append(valid_loader_model)
# Changeable network parameters for the global network
if vit:
if dinov2:
model = load_pretrained_dinov2(num_classes=len(weight_model))
else:
model = load_pretrained_timm_model(num_classes=len(weight_model), pretrained=pretrained, imgsize=image_size)
else:
model = load_pretrained_timm_model(num_classes=len(weight_model), model_name='resnet50d', pretrained=pretrained)
trainer = Training(cfg_path, resume=resume, label_names_loader=label_names_loader)
if resume == True:
trainer.load_checkpoints(model=model, loss_function_loader=loss_function_loader, weight_loader=weight_loader)
else:
trainer.setup_models(model=model, loss_function_loader=loss_function_loader, weight_loader=weight_loader)
trainer.training_setup_conventional_federated(train_loader=train_loader, valid_loader=valid_loader, vit=vit)
def main_train_federated_validall(global_config_path="",
resume=False, augment=False, experiment_name='name', train_sites=['vindr', 'cxr14'], pretrained=True, vit=False, dinov2=True, image_size=224, batch_size=30, lr=1e-5):
"""
Parameters
----------
global_config_path: str
always global_config_path="FLdomain/config/config.yaml"
resume: bool
if we are resuming training on a model
experiment_name: str
name of the experiment, in case of resuming training.
name of new experiment, in case of new training.
"""
if resume == True:
params = open_experiment(experiment_name, global_config_path)
else:
params = create_experiment(experiment_name, global_config_path)
cfg_path = params["cfg_path"]
train_loader = []
valid_loader = []
weight_loader = []
loss_function_loader = []
label_names_loader = []
for dataset_name in train_sites:
if dataset_name == 'vindr':
train_dataset_model = vindr_data_loader_2D(cfg_path=cfg_path, mode='train', augment=augment, image_size=image_size)
elif dataset_name == 'chexpert':
train_dataset_model = chexpert_data_loader_2D(cfg_path=cfg_path, mode='train', augment=augment, image_size=image_size)
elif dataset_name == 'mimic':
train_dataset_model = mimic_data_loader_2D(cfg_path=cfg_path, mode='train', augment=augment, image_size=image_size)
elif dataset_name == 'cxr14':
train_dataset_model = cxr14_data_loader_2D(cfg_path=cfg_path, mode='train', augment=augment, image_size=image_size)
elif dataset_name == 'padchest':
train_dataset_model = padchest_data_loader_2D(cfg_path=cfg_path, mode='train', augment=augment, image_size=image_size)
model_info = params['Network']
model_info['lr'] = lr
model_info['batch_size'] = batch_size
params['Network'] = model_info
write_config(params, cfg_path, sort_keys=True)
weight_model = train_dataset_model.pos_weight()
loss_function_model = BCEWithLogitsLoss
train_loader_model = torch.utils.data.DataLoader(dataset=train_dataset_model,
batch_size=batch_size,
pin_memory=True, drop_last=True, shuffle=True, num_workers=10)
train_loader.append(train_loader_model)
weight_loader.append(weight_model)
loss_function_loader.append(loss_function_model)
valid_dataset_vindr = vindr_data_loader_2D(cfg_path=cfg_path, mode='test', augment=False, image_size=image_size)
label_names_vindr = valid_dataset_vindr.chosen_labels
label_names_loader.append(label_names_vindr)
valid_loader_vindr = torch.utils.data.DataLoader(dataset=valid_dataset_vindr, batch_size=batch_size, pin_memory=True, drop_last=False, shuffle=False, num_workers=5)
valid_loader.append(valid_loader_vindr)
valid_dataset_cxr14 = cxr14_data_loader_2D(cfg_path=cfg_path, mode='test', augment=False, image_size=image_size)
label_names_cxr14 = valid_dataset_cxr14.chosen_labels
label_names_loader.append(label_names_cxr14)
valid_loader_cxr14 = torch.utils.data.DataLoader(dataset=valid_dataset_cxr14, batch_size=batch_size, pin_memory=True, drop_last=False, shuffle=False, num_workers=5)
valid_loader.append(valid_loader_cxr14)
valid_dataset_chexpert = chexpert_data_loader_2D(cfg_path=cfg_path, mode='test', augment=False, image_size=image_size)
label_names_chexpert = valid_dataset_chexpert.chosen_labels
label_names_loader.append(label_names_chexpert)
valid_loader_chexpert = torch.utils.data.DataLoader(dataset=valid_dataset_chexpert, batch_size=batch_size, pin_memory=True, drop_last=False, shuffle=False, num_workers=5)
valid_loader.append(valid_loader_chexpert)
valid_dataset_mimic = mimic_data_loader_2D(cfg_path=cfg_path, mode='test', augment=False, image_size=image_size)
label_names_mimic = valid_dataset_mimic.chosen_labels
label_names_loader.append(label_names_mimic)
valid_loader_mimic = torch.utils.data.DataLoader(dataset=valid_dataset_mimic, batch_size=batch_size, pin_memory=True, drop_last=False, shuffle=False, num_workers=5)
valid_loader.append(valid_loader_mimic)
valid_dataset_padchest = padchest_data_loader_2D(cfg_path=cfg_path, mode='test', augment=False, image_size=image_size)
label_names_padchest = valid_dataset_padchest.chosen_labels
label_names_loader.append(label_names_padchest)
valid_loader_padchest = torch.utils.data.DataLoader(dataset=valid_dataset_padchest, batch_size=batch_size, pin_memory=True, drop_last=False, shuffle=False, num_workers=5)
valid_loader.append(valid_loader_padchest)
# Changeable network parameters for the global network
if vit:
if dinov2:
model = load_pretrained_dinov2(num_classes=len(weight_model))
else:
model = load_pretrained_timm_model(num_classes=len(weight_model), pretrained=pretrained, imgsize=image_size)
else:
model = load_pretrained_timm_model(num_classes=len(weight_model), model_name='resnet50d', pretrained=pretrained)
trainer = Training(cfg_path, resume=resume, label_names_loader=label_names_loader)
if resume == True:
trainer.load_checkpoints(model=model, loss_function_loader=loss_function_loader, weight_loader=weight_loader)
else:
trainer.setup_models(model=model, loss_function_loader=loss_function_loader, weight_loader=weight_loader)
trainer.training_setup_conventional_federated(train_loader=train_loader, valid_loader=valid_loader, vit=vit)
def main_train_federated_validone(global_config_path="",
resume=False, augment=False, experiment_name='name', train_site='cxr14', pretrained=True, vit=False, dinov2=True, image_size=224, batch_size=30, lr=1e-5):
"""
Parameters
----------
global_config_path: str
always global_config_path="FLdomain/config/config.yaml"
resume: bool
if we are resuming training on a model
experiment_name: str
name of the experiment, in case of resuming training.
name of new experiment, in case of new training.
"""
if resume == True:
params = open_experiment(experiment_name, global_config_path)
else:
params = create_experiment(experiment_name, global_config_path)
cfg_path = params["cfg_path"]
train_loader = []
valid_loader = []
weight_loader = []
loss_function_loader = []
label_names_loader = []
for idx in range(4):
if train_site == 'chexpert':
train_dataset_model = chexpert_data_loader_2D(cfg_path=cfg_path, mode='train', augment=augment, image_size=image_size, site_num=idx+1)
elif train_site == 'mimic':
train_dataset_model = mimic_data_loader_2D(cfg_path=cfg_path, mode='train', augment=augment, image_size=image_size, site_num=idx+1)
elif train_site == 'cxr14':
train_dataset_model = cxr14_data_loader_2D(cfg_path=cfg_path, mode='train', augment=augment, image_size=image_size, site_num=idx+1)
elif train_site == 'padchest':
train_dataset_model = padchest_data_loader_2D(cfg_path=cfg_path, mode='train', augment=augment, image_size=image_size, site_num=idx+1)
model_info = params['Network']
model_info['lr'] = lr
model_info['batch_size'] = batch_size
params['Network'] = model_info
write_config(params, cfg_path, sort_keys=True)
weight_model = train_dataset_model.pos_weight()
loss_function_model = BCEWithLogitsLoss
train_loader_model = torch.utils.data.DataLoader(dataset=train_dataset_model,
batch_size=batch_size,
pin_memory=True, drop_last=True, shuffle=True, num_workers=10)
train_loader.append(train_loader_model)
weight_loader.append(weight_model)
loss_function_loader.append(loss_function_model)
valid_dataset_vindr = vindr_data_loader_2D(cfg_path=cfg_path, mode='test', augment=False, image_size=image_size)
label_names_vindr = valid_dataset_vindr.chosen_labels
label_names_loader.append(label_names_vindr)
valid_loader_vindr = torch.utils.data.DataLoader(dataset=valid_dataset_vindr, batch_size=batch_size, pin_memory=True, drop_last=False, shuffle=False, num_workers=5)
valid_loader.append(valid_loader_vindr)
valid_dataset_cxr14 = cxr14_data_loader_2D(cfg_path=cfg_path, mode='test', augment=False, image_size=image_size)
label_names_cxr14 = valid_dataset_cxr14.chosen_labels
label_names_loader.append(label_names_cxr14)
valid_loader_cxr14 = torch.utils.data.DataLoader(dataset=valid_dataset_cxr14, batch_size=batch_size, pin_memory=True, drop_last=False, shuffle=False, num_workers=5)
valid_loader.append(valid_loader_cxr14)
valid_dataset_chexpert = chexpert_data_loader_2D(cfg_path=cfg_path, mode='test', augment=False, image_size=image_size)
label_names_chexpert = valid_dataset_chexpert.chosen_labels
label_names_loader.append(label_names_chexpert)
valid_loader_chexpert = torch.utils.data.DataLoader(dataset=valid_dataset_chexpert, batch_size=batch_size, pin_memory=True, drop_last=False, shuffle=False, num_workers=5)
valid_loader.append(valid_loader_chexpert)
valid_dataset_mimic = mimic_data_loader_2D(cfg_path=cfg_path, mode='test', augment=False, image_size=image_size)
label_names_mimic = valid_dataset_mimic.chosen_labels
label_names_loader.append(label_names_mimic)
valid_loader_mimic = torch.utils.data.DataLoader(dataset=valid_dataset_mimic, batch_size=batch_size, pin_memory=True, drop_last=False, shuffle=False, num_workers=5)
valid_loader.append(valid_loader_mimic)
valid_dataset_padchest = padchest_data_loader_2D(cfg_path=cfg_path, mode='test', augment=False, image_size=image_size)
label_names_padchest = valid_dataset_padchest.chosen_labels
label_names_loader.append(label_names_padchest)
valid_loader_padchest = torch.utils.data.DataLoader(dataset=valid_dataset_padchest, batch_size=batch_size, pin_memory=True, drop_last=False, shuffle=False, num_workers=5)
valid_loader.append(valid_loader_padchest)
# Changeable network parameters for the global network
if vit:
if dinov2:
model = load_pretrained_dinov2(num_classes=len(weight_model))
else:
model = load_pretrained_timm_model(num_classes=len(weight_model), pretrained=pretrained, imgsize=image_size)
else:
model = load_pretrained_timm_model(num_classes=len(weight_model), model_name='resnet50d', pretrained=pretrained)
trainer = Training(cfg_path, resume=resume, label_names_loader=label_names_loader)
if resume == True:
trainer.load_checkpoints(model=model, loss_function_loader=loss_function_loader, weight_loader=weight_loader)
else:
trainer.setup_models(model=model, loss_function_loader=loss_function_loader, weight_loader=weight_loader)
trainer.training_setup_conventional_federated(train_loader=train_loader, valid_loader=valid_loader, vit=vit)
def main_test_central_2D_pvalue_out_of_bootstrap(global_config_path="",
experiment_name1='central_exp_for_test', experiment_name2='central_exp_for_test',
experiment1_epoch_num=100, experiment2_epoch_num=100, dataset_name='vindr', vit=False, dinov2=False, image_size=224):
"""Main function for multi label prediction
Parameters
----------
experiment_name: str
name of the experiment to be loaded.
"""
params1 = open_experiment(experiment_name1, global_config_path)
cfg_path1 = params1['cfg_path']
if dataset_name == 'vindr':
test_dataset = vindr_data_loader_2D(cfg_path=cfg_path1, mode='test', augment=False, image_size=image_size)
elif dataset_name == 'chexpert':
test_dataset = chexpert_data_loader_2D(cfg_path=cfg_path1, mode='test', augment=False, image_size=image_size)
elif dataset_name == 'mimic':
test_dataset = mimic_data_loader_2D(cfg_path=cfg_path1, mode='test', augment=False, image_size=image_size)
elif dataset_name == 'cxr14':
test_dataset = cxr14_data_loader_2D(cfg_path=cfg_path1, mode='test', augment=False, image_size=image_size)
elif dataset_name == 'padchest':
test_dataset = padchest_data_loader_2D(cfg_path=cfg_path1, mode='test', augment=False, image_size=image_size)
weight = test_dataset.pos_weight()
label_names = test_dataset.chosen_labels
# Changeable network parameters for the global network
if vit:
if dinov2:
model1 = load_pretrained_dinov2(num_classes=len(weight))
else:
model1 = load_pretrained_timm_model(num_classes=len(weight), imgsize=image_size)
else:
model1 = load_pretrained_timm_model(num_classes=len(weight), model_name='resnet50d')
test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=params1['Network']['batch_size'],
pin_memory=True, drop_last=False, shuffle=False, num_workers=16)
index_list = []
for counter in range(1000):
index_list.append(np.random.choice(len(test_dataset), len(test_dataset)))
# Initialize prediction 1
predictor1 = Prediction(cfg_path1, label_names)
predictor1.setup_model(model=model1, epoch_num=experiment1_epoch_num)
pred_array1, target_array1 = predictor1.predict_only(test_loader)
AUC_list1 = predictor1.bootstrapper(pred_array1.cpu().numpy(), target_array1.int().cpu().numpy(), index_list, dataset_name)
# Changeable network parameters
if vit:
if dinov2:
model2 = load_pretrained_dinov2(num_classes=len(weight))
else:
model2 = load_pretrained_timm_model(num_classes=len(weight), imgsize=image_size)
else:
model2 = load_pretrained_timm_model(num_classes=len(weight), model_name='resnet50d')
# Initialize prediction 2
params2 = open_experiment(experiment_name2, global_config_path)
cfg_path2 = params2['cfg_path']
predictor2 = Prediction(cfg_path2, label_names)
predictor2.setup_model(model=model2, epoch_num=experiment2_epoch_num)
pred_array2, target_array2 = predictor2.predict_only(test_loader)
AUC_list2 = predictor2.bootstrapper(pred_array2.cpu().numpy(), target_array2.int().cpu().numpy(), index_list, dataset_name)
print('individual labels p-values:\n')
for idx, pathology in enumerate(label_names):
counter = AUC_list1[:, idx] > AUC_list2[:, idx]
ratio1 = (len(counter) - counter.sum()) / len(counter)
reject_fdr, ratio1 = fdr_correction(ratio1, alpha=0.05, method='indep')
if ratio1 <= 0.05:
print(f'\t{pathology} p-value: {ratio1}; model 1 significantly higher AUC than model 2')
else:
counter = AUC_list2[:, idx] > AUC_list1[:, idx]
ratio2 = (len(counter) - counter.sum()) / len(counter)
reject_fdr, ratio2 = fdr_correction(ratio2, alpha=0.05, method='indep')
if ratio2 <= 0.05:
print(f'\t{pathology} p-value: {ratio2}; model 2 significantly higher AUC than model 1')
else:
print(f'\t{pathology} p-value: {ratio1}; models NOT significantly different for this label')
print('\nAvg AUC of labels p-values:\n')
avgAUC_list1 = AUC_list1.mean(1)
avgAUC_list2 = AUC_list2.mean(1)
counter = avgAUC_list1 > avgAUC_list2
ratio1 = (len(counter) - counter.sum()) / len(counter)
reject_fdr, ratio1 = fdr_correction(ratio1, alpha=0.05, method='indep')
if ratio1 <= 0.05:
print(f'\tp-value: {ratio1}; model 1 significantly higher AUC than model 2 on average')
else:
counter = avgAUC_list2 > avgAUC_list1
ratio2 = (len(counter) - counter.sum()) / len(counter)
reject_fdr, ratio2 = fdr_correction(ratio2, alpha=0.05, method='indep')
if ratio2 <= 0.05:
print(f'\tp-value: {ratio2}; model 2 significantly higher AUC than model 1 on average')
else:
print(f'\tp-value: {ratio1}; models NOT significantly different on average for all labels')
msg = f'\n\nindividual labels p-values:\n'
with open(os.path.join(params1['target_dir'], params1['stat_log_path']) + '/Test_on_' + str(dataset_name), 'a') as f:
f.write(msg)
with open(os.path.join(params2['target_dir'], params2['stat_log_path']) + '/Test_on_' + str(dataset_name), 'a') as f:
f.write(msg)
for idx, pathology in enumerate(label_names):
counter = AUC_list1[:, idx] > AUC_list2[:, idx]
ratio1 = (len(counter) - counter.sum()) / len(counter)
reject_fdr, ratio1 = fdr_correction(ratio1, alpha=0.05, method='indep')
if ratio1 <= 0.05:
msg = f'\t{pathology} p-value: {ratio1}; model 1 significantly higher AUC than model 2'
else:
counter = AUC_list2[:, idx] > AUC_list1[:, idx]
ratio2 = (len(counter) - counter.sum()) / len(counter)
reject_fdr, ratio2 = fdr_correction(ratio2, alpha=0.05, method='indep')
if ratio2 <= 0.05:
msg = f'\t{pathology} p-value: {ratio2}; model 2 significantly higher AUC than model 1'
else:
msg = f'\t{pathology} p-value: {ratio1}; models NOT significantly different for this label'
with open(os.path.join(params1['target_dir'], params1['stat_log_path']) + '/Test_on_' + str(dataset_name), 'a') as f:
f.write(msg)
with open(os.path.join(params2['target_dir'], params2['stat_log_path']) + '/Test_on_' + str(dataset_name), 'a') as f:
f.write(msg)
msg = f'\n\nAvg AUC of labels p-values:\n'
with open(os.path.join(params1['target_dir'], params1['stat_log_path']) + '/Test_on_' + str(dataset_name), 'a') as f:
f.write(msg)
with open(os.path.join(params2['target_dir'], params2['stat_log_path']) + '/Test_on_' + str(dataset_name), 'a') as f:
f.write(msg)
avgAUC_list1 = AUC_list1.mean(1)
avgAUC_list2 = AUC_list2.mean(1)
counter = avgAUC_list1 > avgAUC_list2
ratio1 = (len(counter) - counter.sum()) / len(counter)
reject_fdr, ratio1 = fdr_correction(ratio1, alpha=0.05, method='indep')
if ratio1 <= 0.05:
msg = f'\tp-value: {ratio1}; model 1 significantly higher AUC than model 2 on average'
else:
counter = avgAUC_list2 > avgAUC_list1
ratio2 = (len(counter) - counter.sum()) / len(counter)
reject_fdr, ratio2 = fdr_correction(ratio2, alpha=0.05, method='indep')
if ratio2 <= 0.05:
msg = f'\tp-value: {ratio2}; model 2 significantly higher AUC than model 1 on average'
else:
msg = f'\tp-value: {ratio1}; models NOT significantly different on average for all labels'
with open(os.path.join(params1['target_dir'], params1['stat_log_path']) + '/Test_on_' + str(dataset_name), 'a') as f:
f.write(msg)
with open(os.path.join(params2['target_dir'], params2['stat_log_path']) + '/Test_on_' + str(dataset_name), 'a') as f:
f.write(msg)
def load_pretrained_timm_model(num_classes=2, model_name='vit_base_patch16_224', pretrained=False, imgsize=512):
# Load a pre-trained model from config file
if model_name == 'resnet50d':
model = timm.create_model(model_name, num_classes=num_classes, pretrained=pretrained)
else:
model = timm.create_model(model_name, num_classes=num_classes, img_size=imgsize, pretrained=pretrained)
for param in model.parameters():
param.requires_grad = True
return model
def load_pretrained_dinov2(num_classes=2):
# Load a pre-trained model from config file
# model = torch.hub.load('facebookresearch/dinov2', 'dinov2_vits14')
model = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitb14')
model.head = torch.nn.Linear(in_features=768, out_features=num_classes)
# model = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitl14')
for param in model.parameters():
param.requires_grad = True
return model
if __name__ == '__main__':