-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpredict.py
283 lines (209 loc) · 7.51 KB
/
predict.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
import argparse
import os
import shutil
import time
import logging
import random
import torch
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
from torch.utils.data import DataLoader
import torch.optim
cudnn.benchmark = True
import numpy as np
from medpy import metric
import models
from models import criterions
from data import datasets
from data.data_utils_isles import add_mask
from utils import Parser
path = os.path.dirname(__file__)
def calculate_metrics(pred, target):
sens = metric.sensitivity(pred, target)
spec = metric.specificity(pred, target)
dice = metric.dc(pred, target)
eps = 1e-5
def f1_score(o, t):
num = 2*(o*t).sum() + eps
den = o.sum() + t.sum() + eps
return num/den
#https://github.com/ellisdg/3DUnetCNN
#https://github.com/ellisdg/3DUnetCNN/blob/master/brats/evaluate.py
#https://github.com/MIC-DKFZ/BraTS2017
#https://github.com/MIC-DKFZ/BraTS2017/blob/master/utils_validation.py
def dice(output, target):
ret = []
# whole
o = output > 0; t = target > 0
ret += f1_score(o, t),
return ret
keys = 'whole'
def main():
ckpts = args.getdir()
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu
# setup networks
Network = getattr(models, args.net)
model = Network(**args.net_params)
model = model.cuda()
model_file = os.path.join(ckpts, args.ckpt)
checkpoint = torch.load(model_file)
model.load_state_dict(checkpoint['state_dict'])
Dataset = getattr(datasets, args.dataset)
valid_list = os.path.join(args.data_dir, args.valid_list)
valid_set = Dataset(valid_list, root=args.data_dir,
for_train=False, return_target=args.scoring,
transforms=args.test_transforms)
valid_loader = DataLoader(
valid_set,
batch_size=1, shuffle=False,
collate_fn=valid_set.collate,
num_workers=4, pin_memory=True)
start = time.time()
with torch.no_grad():
scores = validate(valid_loader, model,
args.out_dir, valid_set.names, scoring=args.scoring)
msg = 'total time {:.4f} minutes'.format((time.time() - start)/60)
logging.info(msg)
def validate(valid_loader, model,ckpt,ckpts_dir,
out_dir='', names=None, scoring=True, verbose=True):
model_file = os.path.join(ckpts_dir, ckpt)
checkpoint = torch.load(model_file)
model.load_state_dict(checkpoint['state_dict'])
H, W, T = 181, 217, 181
dtype = torch.float32
dset = valid_loader.dataset
model.eval()
criterion = F.cross_entropy
vals = AverageMeter()
for i, data in enumerate(valid_loader):
target_cpu = data[1][0, :H, :W, :T].numpy() if scoring else None
data = [t.cuda(non_blocking=True) for t in data]
x, target = data[:2]
print('x_origin_size',x.shape)
print('target',target.shape)
if len(data) > 2:
x = add_mask(x, data.pop(), 1)
print('x_size',x.shape)
# compute output
print('x_size',x.shape)
_, logit = model(x) # nx5x9x9x9, target nx9x9x9
print('logit',logit.shape)
output = F.softmax(logit, dim=1) # nx5x9x9x9
## measure accuracy and record loss
#loss = None
#if scoring and criterion is not None:
# loss = criterion(logit, target).item()
output = output[0, :, :H, :W, :T].cpu().numpy()
msg = 'Subject {}/{}, '.format(i+1, len(valid_loader))
name = str(i)
if names:
name = names[i]
msg += '{:>20}, '.format(name)
if out_dir:
np.save(os.path.join(out_dir, name + '_preds'), output)
if scoring:
output = output.argmax(0)
scores = dice(output, target_cpu)
#if loss is not None:
# scores += loss,
vals.update(np.array(scores))
msg += ', '.join(['{}: {:.4f}'.format(k, v) for k, v in zip(keys, scores)])
if verbose:
logging.info(msg)
if scoring:
msg = 'Average scores: '
msg += ', '.join(['{}: {:.4f}'.format(k, v) for k, v in zip(keys, vals.avg)])
logging.info(msg)
model.train()
return vals.avg
def validate_ema(valid_loader, model,ckpt,ckpts_dir,
out_dir='', names=None, scoring=True, verbose=True):
model_file = os.path.join(ckpts_dir, ckpt)
checkpoint = torch.load(model_file)
model.load_state_dict(checkpoint['ema_state_dict'])
H, W, T = 181, 217, 181
dtype = torch.float32
dset = valid_loader.dataset
model.eval()
criterion = F.cross_entropy
vals = AverageMeter()
for i, data in enumerate(valid_loader):
target_cpu = data[1][0, :H, :W, :T].numpy() if scoring else None
data = [t.cuda(non_blocking=True) for t in data]
x, target = data[:2]
print('x_origin_size',x.shape)
print('target',target.shape)
if len(data) > 2:
x = add_mask(x, data.pop(), 1)
print('x_size',x.shape)
print('x_size',x.shape)
_, logit = model(x) # nx5x9x9x9, target nx9x9x9
print('logit',logit.shape)
output = F.softmax(logit, dim=1) # nx5x9x9x9
## measure accuracy and record loss
#loss = None
#if scoring and criterion is not None:
# loss = criterion(logit, target).item()
output = output[0, :, :H, :W, :T].cpu().numpy()
msg = 'Subject {}/{}, '.format(i+1, len(valid_loader))
name = str(i)
if names:
name = names[i]
msg += '{:>20}, '.format(name)
if out_dir:
np.save(os.path.join(out_dir, name + '_preds'), output)
if scoring:
output = output.argmax(0)
scores = dice(output, target_cpu)
#if loss is not None:
# scores += loss,
vals.update(np.array(scores))
msg += ', '.join(['{}: {:.4f}'.format(k, v) for k, v in zip(keys, scores)])
if verbose:
logging.info(msg)
if scoring:
msg = 'Average scores: '
msg += ', '.join(['{}: {:.4f}'.format(k, v) for k, v in zip(keys, vals.avg)])
logging.info(msg)
model.train()
return vals.avg
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
if __name__ == '__main__':
global args
parser = argparse.ArgumentParser()
parser.add_argument('-cfg', '--cfg', default='unet', type=str)
parser.add_argument('-gpu', '--gpu', default='0', type=str)
args = parser.parse_args()
args = Parser(args.cfg, log='testing_550').add_args(args)
#args.valid_list = 'valid_0.txt'
#args.valid_list = 'all.txt'
#args.saving = False
#args.scoring = True
args.data_dir = '/emc_lun/cgx/Script/U-Net_CNN/SemiSeg/code/BraTS2018/brats2018/testing'
args.valid_list = 'test.txt'
args.saving = True
args.scoring = False # for real test data, set this to False
# args.ckpt = 'model_epoch_550.tar'
#args.ckpt = 'model_iter_227.tar'
if args.saving:
folder = os.path.splitext(args.valid_list)[0]
out_dir = os.path.join('output', args.name, folder)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
args.out_dir = out_dir
else:
args.out_dir = ''
main()