forked from ljwztc/CLIP-Driven-Universal-Model
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpred_pseudo.py
197 lines (165 loc) · 9.16 KB
/
pred_pseudo.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
import torch
from torch import nn
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
import os
import argparse
import time
from monai.losses import DiceCELoss
from monai.data import load_decathlon_datalist, decollate_batch
from monai.transforms import AsDiscrete
from monai.metrics import DiceMetric
from monai.inferers import sliding_window_inference
from model.Universal_model import Universal_model
from dataset.dataloader import get_loader_without_gt
from utils import loss
from utils.utils import dice_score, threshold_organ, visualize_label, merge_label, get_key
from utils.utils import TEMPLATE, ORGAN_NAME, NUM_CLASS
from utils.utils import organ_post_process, threshold_organ
torch.multiprocessing.set_sharing_strategy('file_system')
def validation(model, ValLoader, val_transforms, args):
save_dir = 'out/' + args.log_name #+ f'/pesudolbl_{args.epoch}'
if not os.path.isdir(save_dir):
os.mkdir(save_dir)
os.mkdir(save_dir+'/predict')
model.eval()
dice_list = {}
for key in TEMPLATE.keys():
dice_list[key] = np.zeros((2, NUM_CLASS)) # 1st row for dice, 2nd row for count
for index, batch in enumerate(tqdm(ValLoader)):
# print('%d processd' % (index))
image, name = batch["image"].cuda(), batch["name"]
print(image.shape)
# print(label.shape)
with torch.no_grad():
# with torch.autocast(device_type="cuda", dtype=torch.float16):
pred = sliding_window_inference(image, (args.roi_x, args.roi_y, args.roi_z), 1, model, overlap=0.5, mode='gaussian')
pred_sigmoid = F.sigmoid(pred)
#pred_hard = threshold_organ(pred_sigmoid, organ=args.threshold_organ, threshold=args.threshold)
pred_hard = threshold_organ(pred_sigmoid)
pred_hard = pred_hard.cpu()
torch.cuda.empty_cache()
B = pred_hard.shape[0]
for b in range(B):
content = 'case%s| '%(name[b])
template_key = get_key(name[b])
organ_list = TEMPLATE[template_key]
pred_hard_post = organ_post_process(pred_hard.numpy(), organ_list, args.log_name+'/'+name[0].split('/')[0]+'/'+name[0].split('/')[-1],args)
pred_hard_post = torch.tensor(pred_hard_post)
# for organ in organ_list:
# if torch.sum(label[b,organ-1,:,:,:].cuda()) != 0:
# dice_organ, recall, precision = dice_score(pred_hard_post[b,organ-1,:,:,:].cuda(), label[b,organ-1,:,:,:].cuda())
# dice_list[template_key][0][organ-1] += dice_organ.item()
# dice_list[template_key][1][organ-1] += 1
# content += '%s: %.4f, '%(ORGAN_NAME[organ-1], dice_organ.item())
# print('%s: dice %.4f, recall %.4f, precision %.4f.'%(ORGAN_NAME[organ-1], dice_organ.item(), recall.item(), precision.item()))
# print(content)
### testing phase for this function
one_channel_label_v1, one_channel_label_v2 = merge_label(pred_hard_post, name)
batch['one_channel_label_v1'] = one_channel_label_v1.cpu()
batch['one_channel_label_v2'] = one_channel_label_v2.cpu()
visualize_label(batch, save_dir + '/output/' + name[0].split('/')[0] , val_transforms)
torch.cuda.empty_cache()
ave_organ_dice = np.zeros((2, NUM_CLASS))
# with open('out/'+args.log_name+f'/test_{args.epoch}.txt', 'w') as f:
# for key in TEMPLATE.keys():
# organ_list = TEMPLATE[key]
# content = 'Task%s| '%(key)
# for organ in organ_list:
# dice = dice_list[key][0][organ-1] / dice_list[key][1][organ-1]
# content += '%s: %.4f, '%(ORGAN_NAME[organ-1], dice)
# ave_organ_dice[0][organ-1] += dice_list[key][0][organ-1]
# ave_organ_dice[1][organ-1] += dice_list[key][1][organ-1]
# print(content)
# f.write(content)
# f.write('\n')
# content = 'Average | '
# for i in range(NUM_CLASS):
# content += '%s: %.4f, '%(ORGAN_NAME[i], ave_organ_dice[0][i] / ave_organ_dice[1][i])
# print(content)
# f.write(content)
# f.write('\n')
# print(np.mean(ave_organ_dice[0] / ave_organ_dice[1]))
# f.write('%s: %.4f, '%('average', np.mean(ave_organ_dice[0] / ave_organ_dice[1])))
# f.write('\n')
# np.save(save_dir + '/result.npy', dice_list)
# load
# dice_list = np.load(/out/epoch_xxx/result.npy, allow_pickle=True)
def main():
parser = argparse.ArgumentParser()
## for distributed training
parser.add_argument('--dist', dest='dist', type=bool, default=False,
help='distributed training or not')
parser.add_argument("--local_rank", type=int)
parser.add_argument("--device")
parser.add_argument("--epoch", default=0)
## logging
parser.add_argument('--log_name', default='Nvidia', help='The path resume from checkpoint')
## model load
parser.add_argument('--resume', default='./pretrained_weights/swinunetr.pth', help='The path resume from checkpoint')
parser.add_argument('--pretrain', default='./pretrained_weights/swin_unetr.base_5000ep_f48_lr2e-4_pretrained.pt',
help='The path of pretrain model')
parser.add_argument('--backbone', default='swinunetr', help='backbone [swinunetr or unet]')
## hyperparameter
parser.add_argument('--max_epoch', default=1000, type=int, help='Number of training epoches')
parser.add_argument('--store_num', default=10, type=int, help='Store model how often')
parser.add_argument('--lr', default=1e-4, type=float, help='Learning rate')
parser.add_argument('--weight_decay', default=1e-5, type=float, help='Weight Decay')
## dataset
parser.add_argument('--dataset_list', nargs='+', default=['PAOT_123457891213', 'PAOT_10_inner']) # 'PAOT', 'felix'
### please check this argment carefully
### PAOT: include PAOT_123457891213 and PAOT_10
### PAOT_123457891213: include 1 2 3 4 5 7 8 9 12 13
### PAOT_10_inner: same with NVIDIA for comparison
### PAOT_10: original division
parser.add_argument('--data_root_path', default='/computenodes/node31/team1/jliu/data/ct_data/', help='data root path')
parser.add_argument('--data_txt_path', default='./dataset/dataset_list/', help='data txt path')
parser.add_argument('--batch_size', default=1, type=int, help='batch size')
parser.add_argument('--num_workers', default=8, type=int, help='workers numebr for DataLoader')
parser.add_argument('--a_min', default=-175, type=float, help='a_min in ScaleIntensityRanged')
parser.add_argument('--a_max', default=250, type=float, help='a_max in ScaleIntensityRanged')
parser.add_argument('--b_min', default=0.0, type=float, help='b_min in ScaleIntensityRanged')
parser.add_argument('--b_max', default=1.0, type=float, help='b_max in ScaleIntensityRanged')
parser.add_argument('--space_x', default=1.5, type=float, help='spacing in x direction')
parser.add_argument('--space_y', default=1.5, type=float, help='spacing in y direction')
parser.add_argument('--space_z', default=1.5, type=float, help='spacing in z direction')
parser.add_argument('--roi_x', default=96, type=int, help='roi size in x direction')
parser.add_argument('--roi_y', default=96, type=int, help='roi size in y direction')
parser.add_argument('--roi_z', default=96, type=int, help='roi size in z direction')
parser.add_argument('--num_samples', default=1, type=int, help='sample number in each ct')
parser.add_argument('--phase', default='test', help='train or validation or test')
parser.add_argument('--cache_dataset', action="store_true", default=False, help='whether use cache dataset')
parser.add_argument('--store_result', action="store_true", default=False, help='whether save prediction result')
parser.add_argument('--cache_rate', default=0.6, type=float, help='The percentage of cached data in total')
parser.add_argument('--threshold_organ', default='Pancreas Tumor')
parser.add_argument('--threshold', default=0.6, type=float)
args = parser.parse_args()
# prepare the 3D model
model = Universal_model(img_size=(args.roi_x, args.roi_y, args.roi_z),
in_channels=1,
out_channels=NUM_CLASS,
backbone=args.backbone,
encoding='word_embedding'
)
#Load pre-trained weights
store_dict = model.state_dict()
checkpoint = torch.load(args.resume)
load_dict = checkpoint['net']
# args.epoch = checkpoint['epoch']
for key, value in load_dict.items():
if 'swinViT' in key or 'encoder' in key or 'decoder' in key:
name = '.'.join(key.split('.')[1:])
name = 'backbone.' + name
else:
name = '.'.join(key.split('.')[1:])
store_dict[name] = value
model.load_state_dict(store_dict)
print('Use pretrained weights')
model.cuda()
torch.backends.cudnn.benchmark = True
test_loader, val_transforms = get_loader_without_gt(args)
validation(model, test_loader, val_transforms, args)
if __name__ == "__main__":
main()