-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsets.py
362 lines (295 loc) · 13 KB
/
sets.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
import warnings
import numpy as np
import torch.nn.functional as F
import torch.nn as nn
import torch
from torch.autograd import Variable
from torch.nn import MSELoss, SmoothL1Loss, L1Loss
class FocalLoss(nn.Module):
def __init__(self, focusing_param=2.5, balance_param=1):
super(FocalLoss, self).__init__()
self.focusing_param = focusing_param
self.balance_param = balance_param
def forward(self, output, target):
cross_entropy = F.cross_entropy(output, target)
cross_entropy_log = torch.log(cross_entropy)
logpt = - F.cross_entropy(output, target)
pt = torch.exp(logpt)
focal_loss = -((1 - pt) ** self.focusing_param) * logpt
balanced_focal_loss = self.balance_param * focal_loss
return balanced_focal_loss
class DiceLoss2D(nn.Module):
def __init__(self, smooth = 1, size_average=True):
super(DiceLoss2D, self).__init__()
self.smooth = smooth
self.size_average = size_average
def forward(self, logit, target, type='softmax'):
target = target.view(-1, 1).long()
#print('target.shape',target.shape): 460800, 1
if type=='sigmoid':
if class_weight is None:
class_weight = [1]*2 #[0.5, 0.5]
prob = F.sigmoid(logit)
prob = prob.view(-1, 1)
prob = torch.cat((1-prob, prob), 1)
select = torch.FloatTensor(len(prob), 2).zero_().cuda()
select.scatter_(1, target, 1.)
elif type=='softmax':
B,C,H,W = logit.size()
#print('logit.size()',logit.size()): 8, 5, 240, 240
logit = logit.permute(0, 2, 3, 1).contiguous().view(-1, C)
#print('logit.shape',logit.shape): 460800, 5
prob = F.softmax(logit,1)
#print('prob.shape',prob.shape): 460800, 5
#print('len(prob)',len(prob)): 460800
select = torch.FloatTensor(len(prob), C).zero_().cuda()
#print('select.shape',select.shape): 460800, 5;
#print('target.SUM',target.sum()): 51224
select.scatter_(1, target, 1.)
#print('select.shape',select.shape): 460800, 5
#intersection = prob * select
#print('intersection.shape',intersection.shape)
#loss = 2 * (intersection.sum(1) + self.smooth) / (prob.sum(1) + select.sum(1) + self.smooth)
# print('loss.shape',loss.shape)
#loss = 1 - loss.sum() / len(prob)
num = torch.sum(torch.mul(prob, select), dim=1) + self.smooth
den = torch.sum(prob.pow(2) + select.pow(2), dim=1) + self.smooth
loss = 1 - num / den
if self.size_average:
loss = loss.mean()
else:
loss = loss
#print('loss',loss)
return loss
class DiceLoss3D(nn.Module):
def __init__(self, smooth = 1, size_average=True):
super(DiceLoss3D, self).__init__()
self.smooth = smooth
self.size_average = size_average
def forward(self, logit, target, type='softmax'):
target = target.view(-1, 1).long()
#print('target.shape',target.shape): 460800, 1
if type=='sigmoid':
if class_weight is None:
class_weight = [1]*2 #[0.5, 0.5]
prob = F.sigmoid(logit)
prob = prob.view(-1, 1)
prob = torch.cat((1-prob, prob), 1)
select = torch.FloatTensor(len(prob), 2).zero_().cuda()
select.scatter_(1, target, 1.)
elif type=='softmax':
B,C,H,W,D = logit.size()
#print('logit.size()',logit.size()): 8, 5, 128, 128, 128
logit = logit.permute(0, 2, 3, 4, 1).contiguous().view(-1, C)
#print('logit.shape',logit.shape): 460800, 5
prob = F.softmax(logit,1)
#print('prob.shape',prob.shape): 460800, 5
#print('len(prob)',len(prob)): 460800
select = torch.FloatTensor(len(prob), C).zero_().cuda()
#print('select.shape',select.shape): 460800, 5;
#print('target.SUM',target.sum()): 51224
select.scatter_(1, target, 1.)
#print('select.shape',select.shape): 460800, 5
#intersection = prob * select
#print('intersection.shape',intersection.shape)
#loss = 2 * (intersection.sum(1) + self.smooth) / (prob.sum(1) + select.sum(1) + self.smooth)
# print('loss.shape',loss.shape)
#loss = 1 - loss.sum() / len(prob)
#print(prob.shape,select.shape)
num = torch.sum(torch.mul(prob, select), dim=1) + self.smooth
den = torch.sum(prob.pow(2) + select.pow(2), dim=1) + self.smooth
loss = 1 - num / den
if self.size_average:
loss = loss.mean()
else:
loss = loss
#print('loss',loss)
return loss
class Maskloss(nn.Module):
def __init__(self, smooth = 1, size_average=True):
super(Maskloss, self).__init__()
self.smooth = smooth
self.size_average = size_average
def forward(self, logit, target, mask, type='softmax'):
target = target.view(-1, 1).long()
#print('target.shape',target.shape): 460800, 1
if type=='sigmoid':
if class_weight is None:
class_weight = [1]*2 #[0.5, 0.5]
prob = F.sigmoid(logit)
prob = prob.view(-1, 1)
prob = torch.cat((1-prob, prob), 1)
select = torch.FloatTensor(len(prob), 2).zero_().cuda()
select.scatter_(1, target, 1.)
elif type=='softmax':
B,C,H,W,D = logit.size()
#print('logit.size()',logit.size()): 8, 5, 128, 128, 128
logit = logit.permute(0, 2, 3, 4, 1).contiguous().view(-1, C)
#print('logit.shape',logit.shape): 460800, 5
prob = F.softmax(logit,1)
#print('prob.shape',prob.shape): 460800, 5
#print('len(prob)',len(prob)): 460800
select = torch.FloatTensor(len(prob), C).zero_().cuda()
#print('select.shape',select.shape): 460800, 5;
#print('target.SUM',target.sum()): 51224
select.scatter_(1, target, 1.)
#print('select.shape',select.shape): 460800, 5
#intersection = prob * select
#print('intersection.shape',intersection.shape)
#loss = 2 * (intersection.sum(1) + self.smooth) / (prob.sum(1) + select.sum(1) + self.smooth)
# print('loss.shape',loss.shape)
#loss = 1 - loss.sum() / len(prob)
mask = mask.view(-1, 1).long()
maskk = torch.cat((mask,mask,mask,mask,mask,mask),1)
#print(maskk.shape)
#for i in range(maskk.shape[0]):
# if torch.sum(maskk[i,:]) > 0:
# print(maskk[i,:])
# break
select = select[maskk<1].view(-1, C)
prob = prob[maskk<1].view(-1, C)
#print(select[0,:])
#print(select[10,:])
#print(select[110,:])
#print(select[1110,:])
#print(select[11110,:])
#print(select[111110,:])
num = torch.sum(torch.mul(prob, select), dim=1) + self.smooth
den = torch.sum(prob.pow(2) + select.pow(2), dim=1) + self.smooth
loss = 1 - num / den
if self.size_average:
loss = loss.mean()
else:
loss = loss
#print('loss',loss)
return loss
class FocalLoss2d(nn.Module):
def __init__(self, gamma=2, size_average=True):
super(FocalLoss2d, self).__init__()
self.gamma = gamma
self.size_average = size_average
def forward(self, logit, target, class_weight=None, type='softmax'):
target = target.view(-1, 1).long()
if type=='sigmoid':
if class_weight is None:
class_weight = [1]*2 #[0.5, 0.5]
prob = F.sigmoid(logit)
prob = prob.view(-1, 1)
prob = torch.cat((1-prob, prob), 1)
select = torch.FloatTensor(len(prob), 2).zero_().cuda()
select.scatter_(1, target, 1.)
elif type=='softmax':
B,C,H,W = logit.size()
if class_weight is None:
class_weight =[1]*C #[1/C]*C
logit = logit.permute(0, 2, 3, 1).contiguous().view(-1, C)
prob = F.softmax(logit,1)
select = torch.FloatTensor(len(prob), C).zero_().cuda()
select.scatter_(1, target, 1.)
class_weight = torch.FloatTensor(class_weight).cuda().view(-1,1)
class_weight = torch.gather(class_weight, 0, target)
prob = (prob*select).sum(1).view(-1,1)
prob = torch.clamp(prob,1e-8,1-1e-8)
batch_loss = - class_weight *(torch.pow((1-prob), self.gamma))*prob.log()
if self.size_average:
loss = batch_loss.mean()
else:
loss = batch_loss
return loss
class DefaultConfig(object):
env = '552552' # visdom 鐜
vis_port =8097
model = 'unet_3d' # 浣跨敤鐨勬ā鍨嬶紝鍚嶅瓧蹇呴』涓巑odels/__init__.py涓殑鍚嶅瓧涓€鑷?
train_data_root = r"/media/hitlab/GuoXuTao/FCN01/MICCAI_BraTS17_Data_Training" # 璁粌闆嗗瓨鏀捐矾寰? test_data_root = r'/media/hitlab/GuoXuTao/FCN01/MICCAI_BraTS17_Data_Training' # 娴嬭瘯闆嗗瓨鏀捐矾寰? load_model_path = False # 鍔犺浇棰勮缁冪殑妯″瀷鐨勮矾寰勶紝涓篘one浠h〃涓嶅姞杞?
batch_size = 4 # batch size
use_gpu = True # user GPU or not
num_workers = 8 # how many workers for loading data
print_freq = 20 # print info every N batch
debug_file = '/tmp/debug' # if os.path.exists(debug_file): enter ipdb
result_file = 'result.csv'
max_epoch = 100000
lr = 0.0001 # initial learning rate
lr_decay = 1 # when val_loss increase, lr = lr*lr_decay
weight_decay = 1e-8 # 鎹熷け鍑芥暟
class AverageMeter(object):
# Computes and stores the average and current value
def __init__(self):
self.reset() # __init__():reset parameters
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
def _fast_hist(label_true, label_pred, n_class):
mask = (label_true >= 0) & (label_true < n_class)
hist = np.bincount(
n_class * label_true[mask].astype(int) +
label_pred[mask], minlength=n_class**2).reshape(n_class, n_class)
return hist
def calc_dice(label_true,label_pred):
B_index=label_true.shape[0]*label_true.shape[1]*label_true.shape[2]
A_index=label_pred.shape[0]*label_pred.shape[1]*label_pred.shape[2]
count=0.0
for i in range(label_true.shape[0]):
for j in range(label_true.shape[1]):
for k in range(label_true.shape[2]):
if label_true[i][j][k]==label_pred[i][j][k]:
count=count+1
#print count,B_index,A_index
return float(2*count/(B_index+A_index)),sum(sum(label_true!=label_pred))
def scores(label_trues, label_preds, n_class):
"""Returns accuracy score evaluation result.
- overall accuracy
- mean accuracy
- mean IU
- fwavacc
"""
hist = np.zeros((n_class, n_class))
for lt, lp in zip(label_trues, label_preds):
hist += _fast_hist(lt.flatten(), lp.flatten(), n_class)
acc = np.diag(hist).sum() / hist.sum()
acc_cls = np.diag(hist) / hist.sum(axis=1)
acc_cls = np.nanmean(acc_cls)
iu = np.diag(hist) / (hist.sum(axis=1) + hist.sum(axis=0) - np.diag(hist))
mean_iu = np.nanmean(iu)
freq = hist.sum(axis=1) / hist.sum()
fwavacc = (freq[freq > 0] * iu[freq > 0]).sum()
cls_iu = dict(zip(range(n_class), iu))
return {'Overall Acc: \t': acc,
'Mean Acc : \t': acc_cls,
'FreqW Acc : \t': fwavacc,
'Mean IoU : \t': mean_iu,}, cls_iu,acc
def cross_entropy2d(input, target, weight=None, size_average=False):
n, c, h, w = input.size()
log_p = F.log_softmax(input)
log_p = log_p.transpose(1, 2).transpose(2, 3).contiguous().view(-1,c)
print(log_p)
log_p = log_p[target.view(n, h, w, 1).repeat(1, 1, 1, c) >= 0]
log_p = log_p.view(-1,c)
print(log_p)
mask = target >= 0
target = target[mask]
loss = F.nll_loss(log_p, target, weight=weight, size_average=False)
if size_average:
loss /= mask.data.sum()
return loss
def parse(self,kwargs):
'''
鏍规嵁瀛楀吀kwargs 鏇存柊 config鍙傛暟
'''
for k,v in kwargs.iteritems():
if not hasattr(self,k):
warnings.warn("Warning: opt has not attribut %s" %k)
setattr(self,k,v)
print('user config:')
for k,v in self.__class__.__dict__.iteritems():
if not k.startswith('__'):
print(k,getattr(self,k))
DefaultConfig.parse = parse
opt =DefaultConfig()
# opt.parse = parse