-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_tta.py
189 lines (162 loc) · 9.19 KB
/
test_tta.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
# MIT License
#
# Copyright (c) 2024 Mohammad Zunaed, mHealth Lab, BUET
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from argparse import ArgumentParser
import torch
from torch.utils.data import DataLoader
from torch import nn
import time
import numpy as np
from tqdm import tqdm
from sklearn.metrics import roc_auc_score
from datasets import collate_fn_img_level_ds, NIH_IMG_LEVEL_DS_TTA
from models import ThoraXPriorNet
from configs import all_configs, DEVICE, NIH_DATASET_ROOT_DIR, NIH_SPLIT_INFO_DICT_DIR, NIH_MASK_ROOT_DIR, NIH_ABNORMALITY_MASK_DIR
from trainer_callbacks import set_random_state
def get_args():
parser = ArgumentParser(description='test')
parser.add_argument('--run_configs', type=str, default=['exp_512_r48'])
parser.add_argument('--gpu_ids', type=str, default='0,1,2,3')
parser.add_argument('--n_workers', type=int, default=8)
parser.add_argument('--batch_size', type=int, default=8)
parser.add_argument('--seed', type=int, default=0)
parser.add_argument('--image_resize_dim', type=int, default=586)
parser.add_argument('--image_crop_dim', type=int, default=512)
args = parser.parse_args()
return args
def main():
args = get_args()
# set gpu ids
str_ids = args.gpu_ids.split(',')
args.gpu_ids = []
for str_id in str_ids:
gpu_id = int(str_id)
if gpu_id >= 0:
args.gpu_ids.append(gpu_id)
# get configs
for run_config in args.run_configs:
# run_config = args.run_config
configs = all_configs[run_config]
weight_saving_path = configs['weight_saving_path']
# get dataloader
print('Loading dataloaders!')
test_dataset = NIH_IMG_LEVEL_DS_TTA(
NIH_DATASET_ROOT_DIR,
NIH_MASK_ROOT_DIR,
NIH_SPLIT_INFO_DICT_DIR,
'test',
args.image_resize_dim,
args.image_crop_dim,
configs['use_eight_class'],
NIH_ABNORMALITY_MASK_DIR,
)
test_loader = DataLoader(
test_dataset,
batch_size=args.batch_size,
shuffle=False,
num_workers=args.n_workers,
drop_last=False,
collate_fn=collate_fn_img_level_ds,
)
set_random_state(args.seed)
all_targets = []
all_probabilities = []
num_classes = 8 if configs['use_eight_class'] else 15
print('Loading model!')
model = ThoraXPriorNet(num_classes, configs['model_type'], configs['mask_resize_dim'])
checkpoint = torch.load(weight_saving_path+'/checkpoint_best_auc.pth')
print('loss score: {:.4f}'.format(checkpoint['val_loss']))
print('auc score: {:.4f}'.format(checkpoint['val_auc']))
model.load_state_dict(checkpoint['Model_state_dict'])
model = model.to(DEVICE)
if len(args.gpu_ids) > 1:
model = nn.DataParallel(model, device_ids=args.gpu_ids)
model.eval()
del checkpoint
torch.set_grad_enabled(False)
with torch.no_grad():
for itera_no, data in tqdm(enumerate(test_loader), total=len(test_loader)):
images = data['image'].to(DEVICE)
targets = data['target'].to(DEVICE)
# images
images_c1 = images[:, 0, ...].to(DEVICE)
images_c2 = images[:, 1, ...].to(DEVICE)
images_c3 = images[:, 2, ...].to(DEVICE)
images_c4 = images[:, 3, ...].to(DEVICE)
images_c5 = images[:, 4, ...].to(DEVICE)
images_c1_hf = images_c1.flip(3)
images_c2_hf = images_c2.flip(3)
images_c3_hf = images_c3.flip(3)
images_c4_hf = images_c4.flip(3)
images_c5_hf = images_c5.flip(3)
lung_masks = data['lung_mask'].to(DEVICE)
abnormality_masks = data['abnormality_masks'].to(DEVICE)
# print(lung_masks.shape)
# lung masks
lung_masks_c1 = lung_masks[:, 0, ...].to(DEVICE)
lung_masks_c2 = lung_masks[:, 1, ...].to(DEVICE)
lung_masks_c3 = lung_masks[:, 2, ...].to(DEVICE)
lung_masks_c4 = lung_masks[:, 3, ...].to(DEVICE)
lung_masks_c5 = lung_masks[:, 4, ...].to(DEVICE)
lung_masks_c1_hf = lung_masks_c1.flip(3)
lung_masks_c2_hf = lung_masks_c2.flip(3)
lung_masks_c3_hf = lung_masks_c3.flip(3)
lung_masks_c4_hf = lung_masks_c4.flip(3)
lung_masks_c5_hf = lung_masks_c5.flip(3)
# abnormality masks
abnormality_masks_c1 = abnormality_masks[:, 0, ...].to(DEVICE)
abnormality_masks_c2 = abnormality_masks[:, 1, ...].to(DEVICE)
abnormality_masks_c3 = abnormality_masks[:, 2, ...].to(DEVICE)
abnormality_masks_c4 = abnormality_masks[:, 3, ...].to(DEVICE)
abnormality_masks_c5 = abnormality_masks[:, 4, ...].to(DEVICE)
abnormality_masks_c1_hf = abnormality_masks_c1.flip(3)
abnormality_masks_c2_hf = abnormality_masks_c2.flip(3)
abnormality_masks_c3_hf = abnormality_masks_c3.flip(3)
abnormality_masks_c4_hf = abnormality_masks_c4.flip(3)
abnormality_masks_c5_hf = abnormality_masks_c5.flip(3)
# print(images_c5_hf.shape, lung_masks_c5_hf.shape, abnormality_masks_c5_hf.shape)
with torch.cuda.amp.autocast():
out_1 = model(images_c1, abnormality_masks_c1, lung_masks_c1)['logits'].cpu().detach().clone().float().sigmoid()
out_2 = model(images_c2, abnormality_masks_c2, lung_masks_c2)['logits'].cpu().detach().clone().float().sigmoid()
out_3 = model(images_c3, abnormality_masks_c3, lung_masks_c3)['logits'].cpu().detach().clone().float().sigmoid()
out_4 = model(images_c4, abnormality_masks_c4, lung_masks_c4)['logits'].cpu().detach().clone().float().sigmoid()
out_5 = model(images_c5, abnormality_masks_c5, lung_masks_c5)['logits'].cpu().detach().clone().float().sigmoid()
out_6 = model(images_c1_hf, abnormality_masks_c1_hf, lung_masks_c1_hf)['logits'].cpu().detach().clone().float().sigmoid()
out_7 = model(images_c2_hf, abnormality_masks_c2_hf, lung_masks_c2_hf)['logits'].cpu().detach().clone().float().sigmoid()
out_8 = model(images_c3_hf, abnormality_masks_c3_hf, lung_masks_c3_hf)['logits'].cpu().detach().clone().float().sigmoid()
out_9 = model(images_c4_hf, abnormality_masks_c4_hf, lung_masks_c4_hf)['logits'].cpu().detach().clone().float().sigmoid()
out_10 = model(images_c5_hf, abnormality_masks_c5_hf, lung_masks_c5_hf)['logits'].cpu().detach().clone().float().sigmoid()
all_targets.append(targets.cpu().data.numpy())
# y_prob = out['logits'].cpu().detach().clone().float().sigmoid()
y_prob = (out_1+out_2+out_3+out_4+out_5+out_6+out_7+out_8+out_9+out_10)/10
all_probabilities.append(y_prob.numpy())
num_classes = 8 if configs['use_eight_class'] else 14
all_targets = np.concatenate(all_targets)[:,:num_classes]
all_probabilities = np.concatenate(all_probabilities)[:,:num_classes]
auc = roc_auc_score(all_targets, all_probabilities)
print(f'auc score: {auc*100}')
time.sleep(1)
all_clswise_auc = roc_auc_score(all_targets, all_probabilities, average=None)
all_clswise_auc = 100 * all_clswise_auc
print(all_clswise_auc)
return all_probabilities, all_targets
if __name__ == '__main__':
all_probabilities, all_targets = main()