-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtrain.py
More file actions
359 lines (228 loc) · 9.59 KB
/
train.py
File metadata and controls
359 lines (228 loc) · 9.59 KB
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
from config import opt
import torch
import dataset
from torch import nn
from torch import optim
from torch.autograd import Variable
from torch.utils.data import DataLoader
import torch.nn.functional as F
from model_cross import weight_init,C_Net
import numpy as np
from torch.utils.data import DataLoader
import os
from loss import CAMLoss,exclusLoss,AlignLoss
from torchvision import transforms as T
import random
from evaluation import *
os.environ["CUDA_VISIBLE_DEVICES"] = "1"
random.seed(309)
np.random.seed(309)
torch.manual_seed(309)
torch.cuda.manual_seed_all(309)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
model=C_Net(img_ch=4,feature_ch=64)
model = model.cuda()
w = np.loadtxt('Label_cross.txt')
w1 = w[0,:].sum()/w.shape[1]
w2 = w[1,:].sum()/w.shape[1]
w1=torch.FloatTensor([w1,1-w1]).cuda()
w2=torch.FloatTensor([w2,1-w2]).cuda()
train_data = dataset.create_cross(opt.data_root1, opt.data_root2, train=True)
val_data = dataset.create_cross(opt.data_root1, opt.data_root2, train=False)
train_dataloader = DataLoader(train_data, opt.batch_size, shuffle=True)
val_dataloader = DataLoader(val_data, 1)
lr = opt.lr
criterion1 = CAMLoss()
criterion3 = nn.L1Loss()
criterion4 = exclusLoss()
criterion5 = nn.CrossEntropyLoss(weight=w1)
criterion6 = nn.CrossEntropyLoss(weight=w2)
criterion9 = AlignLoss()
optimizer=optim.Adam(model.parameters(),lr=opt.lr)
best_score = 0.6
flip = T.RandomVerticalFlip(p=1)
#### setting losses for CAM, classification and mutual erasure ###########
def compute_loss(cl1,cl2,cam1,cam2,label1,label2):
loss1 = criterion1(cam2,label2)+2*criterion1(cam1,label1)
loss2 = criterion6(cl2[0],label2)+criterion6(cl2[1],label2)+criterion5(cl1[0],label1)+criterion5(cl1[1],label1)
loss3 = criterion4(cam1,cam2,label1,label2)
loss = loss1+loss2+0.2*loss3
return loss
###### start training #########
for epoch in range(opt.max_epoch):
model.train()
l=0
l1=0
l2=0
l3=0
total=0
length = 0
cl_correct1=0
cl_correct2=0
cl_correct1_ = 0
cl_correct2_ = 0
for i, (data, label1, label2,label4,Mask1,Mask2,data_name) in enumerate(train_dataloader):
input = Variable(data.cuda())
label1 = Variable(label1.cuda()).long()
label2 = Variable(label2.cuda()).long()
label4 = Variable(label4.cuda()).long()
###### obtain the labels of tumor core (TC=ET+NET) ##########
label1 = ((label1+label4)>0).long()
###### obtain the labels of decomposing features ##########
label1_ = (label1[:,0] + label1[:,1]==2).long()
label2_ = (label2[:,0] + label2[:,1]==2).long()
output,output_ = model(input[:,:4,:],input[:,4:,:])
[cl1,cl2,cam1,cam2] = output
[cl_co1,cl_co2,cam_co1,cam_co2] = output_
loss1 = compute_loss(cl1,cl2,cam1,cam2,label1[:,0],label2[:,0])
loss1_ = compute_loss(cl_co1,cl_co2,cam_co1,cam_co2,label1_,label2_)
loss_align = criterion9(cam1,cam_co1,label1_)+criterion9(cam2,cam_co2,label2_)
l1 += loss1
l2 += loss1_
l3 += loss_align
optimizer.zero_grad()
(loss1+0.1*loss1_+0.1*loss_align).backward()
optimizer.step()
total+=label1.size(0)
######## computing classification performance ##############
_, predicted1 = torch.max(0.5*(cl1[0]+cl1[1]), 1)
_, predicted2 = torch.max(0.5*(cl2[0]+cl2[1]), 1)
_, predicted_co1 = torch.max(0.5*(cl_co1[0]+cl_co1[1]), 1)
_, predicted_co2 = torch.max(0.5*(cl_co2[0]+cl_co2[1]), 1)
label1 = label1>0
cl_correct1+=(predicted1==label1[:,0]).sum().item()
label2 = label2>0
cl_correct2+=(predicted2==label2[:,0]).sum().item()
label1_ = label1_>0
cl_correct1_+=(predicted_co1==label1_).sum().item()
label2_ = label2_>0
cl_correct2_+=(predicted_co2==label2_).sum().item()
Cl_Acc1=cl_correct1/total
Cl_Acc2=cl_correct2/total
Cl_Acc1_=cl_correct1_/total
Cl_Acc2_=cl_correct2_/total
if (epoch + 1) % 20==0 and epoch + 1>=20:
lr = lr*0.9
print('reset learning rate to:', lr)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
print(
'Epoch [%d/%d], Loss: %.4f, %.4f, %.4f, \n[Training] Cl_Acc1: %.4f,Cl_Acc2: %.4f, Cl_Acc1_: %.4f,Cl_Acc2_: %.4f,\n' % (
epoch + 1, opt.max_epoch,l1,l2,l3,
Cl_Acc1,Cl_Acc2,Cl_Acc1_,Cl_Acc2_))
model.eval()
l = 0
l1 =0
l2 =0
total=0
correct=0
cl_correct1=0
cl_correct2=0
cl_correct1_=0
cl_correct2_=0
acc_c = 0. # Accuracy for tumor core
SE_c = 0. # Sensitivity
SP_c = 0. # Specificity
PC_c = 0. # Precision
DC_c = 0. # Dice Coefficient
acc = 0. # Accuracy for whole core
SE = 0. # Sensitivity
SP = 0. # Specificity
PC = 0. # Precision
DC = 0. # Dice Coefficient
id = 0
s = 1
p = 0
with torch.no_grad():
for i, (data, label1, label2,label4,Mask1,Mask2,data_name) in enumerate(val_dataloader):
input = Variable(data.cuda())
GT_1 = Variable(Mask1.cuda())
GT_2 = Variable(Mask2.cuda())
label1 = Variable(label1.cuda()).long()
label2 = Variable(label2.cuda()).long()
label4 = Variable(label4.cuda()).long()
###### obtain the labels of tumor core (TC=ET+NET) ##########
label1 = ((label1+label4)>0).long()
###### obtain the labels of decomposing features ##########
label1_ = (label1[:,0] + label1[:,1]==2).long()
label2_ = (label2[:,0] + label2[:,1]==2).long()
output,output_ = model(input[:,:4,:],input[:,4:,:])
[cl1,cl2,cam1,cam2] = output
[cl_co1,cl_co2,cam_co1,cam_co2] = output_
loss1 = compute_loss(cl1,cl2,cam1,cam2,label1[:,0],label2[:,0])
loss1_ = compute_loss(cl_co1,cl_co2,cam_co1,cam_co2,label1_,label2_)
l1 += loss1
l2 += loss1_
######## computing classification performance ##############
total+=label1.size(0)
_, predicted1 = torch.max(0.5*(cl1[0]+cl1[1]), 1)
_, predicted2 = torch.max(0.5*(cl2[0]+cl2[1]), 1)
_, predicted_co1 = torch.max(0.5*(cl_co1[0]+cl_co1[1]), 1)
_, predicted_co2 = torch.max(0.5*(cl_co2[0]+cl_co2[1]), 1)
label1 = label1>0
cl_correct1+=(predicted1==label1[:,0]).sum().item()
label2 = label2>0
cl_correct2+=(predicted2==label2[:,0]).sum().item()
label1_ = label1_>0
cl_correct1_+=(predicted_co1==label1_).sum().item()
label2_ = label2_>0
cl_correct2_+=(predicted_co2==label2_).sum().item()
SR1_c = cam1[:,1,:,:].unsqueeze(1)
SR2_c = cam2[:,1,:,:].unsqueeze(1)
SR1_c = SR1_c>0.5
SR2_c = SR2_c>0.5
SR2_c = SR1_c+SR2_c
######## computing segmentation performance ##############
if data_name[0].split('_')[-3] != id:
if p > 0:
if torch.sum(GT2) != 0:
acc_c += get_accuracy(SR1, GT1)
SE_c += get_sensitivity(SR1, GT1)
SP_c += get_specificity(SR1, GT1)
DC_c += get_DC(SR1, GT1)
acc += get_accuracy(SR2, GT2)
SE += get_sensitivity(SR2, GT2)
SP += get_specificity(SR2, GT2)
DC += get_DC(SR2, GT2)
id = data_name[0].split('_')[-3]
SR1 = SR1_c
GT1 = GT_1
SR2 = SR2_c
GT2 = GT_2
s = 1
p += 1
else:
SR1 = torch.cat((SR1,SR1_c),1)
GT1 = torch.cat((GT1,GT_1),1)
SR2 = torch.cat((SR2,SR2_c),1)
GT2 = torch.cat((GT2,GT_2),1)
s += 1
###last scan###
if torch.sum(GT2) != 0:
acc_c += get_accuracy(SR1, GT1)
SE_c += get_sensitivity(SR1, GT1)
SP_c += get_specificity(SR1, GT1)
DC_c += get_DC(SR1, GT1)
acc += get_accuracy(SR2, GT2)
SE += get_sensitivity(SR2, GT2)
SP += get_specificity(SR2, GT2)
DC += get_DC(SR2, GT2)
Cl_Acc1=cl_correct1/total
Cl_Acc2=cl_correct2/total
Cl_Acc1_=cl_correct1_/total
Cl_Acc2_=cl_correct2_/total
score = DC/ p
print(
'[val] Loss: %.4f, %.4f, \n Cl_Acc1: %.4f,Cl_Acc2: %.4f, Cl_Acc1_: %.4f,Cl_Acc2_: %.4f,\n' % (
l1,l2,
Cl_Acc1,Cl_Acc2,Cl_Acc1_,Cl_Acc2_))
print(
'[Seg] Acc: %.4f, %.4f, SE: %.4f, %.4f, SP: %.4f, %.4f, DC: %.4f, %.4f\n' % (
acc_c/ p, acc/ p, SE_c/ p, SE/ p, SP_c/ p,SP/ p, DC_c/ p,DC/ p))
# Save Best model
if score > best_score:
best_score = score
best_Net = model.state_dict()
print('Best model score : %.4f \n' % (best_score))
torch.save(best_Net, './models/model_cl_cross.ckpt')