-
Notifications
You must be signed in to change notification settings - Fork 22
/
predict_unet.py
210 lines (160 loc) · 5.39 KB
/
predict_unet.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
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 multicrop
import numpy as np
from medpy import metric
import models
from models import criterions
from data import datasets
from data.data_utils 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),
# core
o = (output==1) | (output==4)
t = (target==1) | (target==4)
ret += f1_score(o , t),
# active
o = (output==4); t = (target==4)
ret += f1_score(o , t),
return ret
keys = 'whole', 'core', 'enhancing', 'loss'
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,
out_dir='', names=None, scoring=True, verbose=True):
H, W, T = 240, 240, 155
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]
if len(data) > 2:
x = add_mask(x, data.pop(), 1)
# compute output
logit = model(x) # nx5x9x9x9, target nx9x9x9
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='test').add_args(args)
#args.valid_list = 'valid_0.txt'
#args.valid_list = 'all.txt'
#args.saving = False
#args.scoring = True
#args.data_dir = '/usr/data/pkao/brats2018/testing'
# validation set
args.data_dir = '/media/hdd1/pkao/brats2018/validation'
args.valid_list = 'test.txt'
args.saving = True
args.scoring = False # for real test data, set this to False
args.ckpt = 'model_last.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()