-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtraining.py
327 lines (252 loc) · 15.3 KB
/
training.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
from monai.losses import DiceLoss
import torch
import matplotlib.pylab as plt
import numpy as np
import torch.nn as nn
import numpy as np
def train_unet(train_loader, val_loader, model, optimizer, scheduler, max_epochs, root_dir):
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
model.train()
best_val_loss = 1e+10
loss_object = DiceLoss(to_onehot_y = True)
for epoch in range(1,max_epochs +1):
train_loss = 0.0
val_loss = 0.0
print("Epoch ", epoch, flush=True)
print("Train:", end ="", flush=True)
for step, batch in enumerate(train_loader):
img, brain_mask= (batch["img"].cuda(), batch["brain_mask"].cuda()
)
optimizer.zero_grad()
pred_tissue_mask = model(img)
loss = loss_object(pred_tissue_mask,brain_mask)
loss.backward()
train_loss += loss.item()
optimizer.step()
print("=", end = "", flush=True)
train_loss = train_loss/(step+1)
print()
print("Val:", end ="", flush=True)
with torch.no_grad():
for step, batch in enumerate(val_loader):
img, brain_mask = (batch["img"].cuda(), batch["brain_mask"].cuda())
brain_img = img#*brain_mask
pred_tissue_mask = model(brain_img)
loss = loss_object(pred_tissue_mask,brain_mask)
val_loss += loss.item()
print("=", end = "", flush=True)
print()
val_loss = val_loss/(step+1)
img = img.cpu()
pred_tissue_mask = pred_tissue_mask.cpu()
plt.figure()
plt.subplot(121)
plt.imshow(img.numpy()[0,0,32,:,:], cmap = "gray")
plt.subplot(122)
plt.imshow(img.numpy()[0,0,32,:,:], cmap = "gray")
plt.imshow(np.argmax(pred_tissue_mask.numpy(),axis = 1)[0,32,:,:], alpha = 0.4)
plt.savefig(root_dir +"val_sample_epoch_" + str(epoch) + ".png")
print("Training epoch ", epoch, ", train loss:", train_loss, ", val loss:", val_loss, flush=True)
if val_loss < best_val_loss:
print("Saving model", flush=True)
torch.save(model.state_dict(), root_dir + "unet_neg_neck.pth")
best_val_loss = val_loss
return
def train_unet_da(source_train_loader, source_val_loader,\
target_train_loader, target_val_loader,\
model, optimizer, scheduler, max_epochs, root_dir,\
loss_weight=2, start_epoch=1, resume_training=False):
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
model.to(device)
model.train()
best_val_loss = 1e+10
segmentation_loss = DiceLoss(to_onehot_y=True)
domain_classifier_loss = nn.BCELoss()#nn.CrossEntropyLoss()
m = nn.Sigmoid()
#global_step = 0
print('resume_training: ',resume_training)
if resume_training:
checkpoint = torch.load(root_dir + "checkpoint.pth", map_location='cpu')
model.load_state_dict(checkpoint['model_state_dict'])
optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
start_epoch = checkpoint['epoch'] + 1
best_val_loss = checkpoint['best_val_loss']
print(f"Resuming training from epoch {start_epoch} with best_val_loss = {best_val_loss:.4f}")
for epoch in range(start_epoch, max_epochs + 1):
global_step = 0
len_dataloader = min(len(source_train_loader), len(target_train_loader))
train_loss = 0.0
train_seg_loss = 0.0
train_dc_loss = 0.0
train_dc_loss_source = 0.0
train_dc_loss_target = 0.0
val_loss = 0.0
val_seg_loss = 0.0
val_dc_loss = 0.0
val_dc_loss_source = 0.0
val_dc_loss_target = 0.0
print("Epoch ", epoch, flush=True)
print("Train:", end="", flush=True)
for step, batch in enumerate(zip(target_train_loader, source_train_loader)):
batch_target, batch_source = batch
target_img, target_domain_label = batch_target["img"].to(device),\
batch_target["domain_label"].type(torch.float32).to(device)
source_img, source_mask, source_domain_label = batch_source["img"].to(device), \
batch_source["brain_mask"].to(device),batch_source["domain_label"].type(torch.float32).to(device)
optimizer.zero_grad()
p = float(global_step + epoch * len_dataloader) / max_epochs / len_dataloader
alpha = 2. / (1. + np.exp(-10 * p)) - 1
pred_seg_source, pred_domain_source = model(source_img, alpha)
pred_seg_target, pred_domain_target = model(target_img, alpha)
loss_seg = segmentation_loss(pred_seg_source, source_mask)
#loss_dc = domain_classifier_loss(m(pred_domain_source).reshape(torch.unsqueeze(source_domain_label,0).shape), torch.unsqueeze(source_domain_label,0)) \
#+ domain_classifier_loss(m(pred_domain_target).reshape(torch.unsqueeze(target_domain_label,0).shape), torch.unsqueeze(target_domain_label,0))
dc_loss_source = domain_classifier_loss(m(pred_domain_source).reshape(torch.unsqueeze(source_domain_label,0).shape), torch.unsqueeze(source_domain_label,0))
dc_loss_target = domain_classifier_loss(m(pred_domain_target).reshape(torch.unsqueeze(target_domain_label,0).shape), torch.unsqueeze(target_domain_label,0))
loss_dc = dc_loss_source + dc_loss_target
total_loss = loss_seg + loss_dc
total_loss.backward()
optimizer.step()
train_dc_loss_source += dc_loss_source.item()
train_dc_loss_target += dc_loss_target.item()
train_seg_loss += loss_seg.item()
train_dc_loss += loss_dc.item()
global_step += 1
print("=", end="", flush=True)
train_seg_loss = train_seg_loss / (step + 1)
train_dc_loss = train_dc_loss / (step + 1)
train_loss = train_seg_loss + train_dc_loss
train_dc_loss_source = train_dc_loss_source / (step + 1)
train_dc_loss_target = train_dc_loss_target / (step + 1)
print("Val:", end ="", flush=True)
with torch.no_grad():
for step, batch in enumerate(zip(target_val_loader, source_val_loader)):
batch_target, batch_source = batch
target_img, target_domain_label = batch_target["img"].cuda(),\
batch_target["domain_label"].type(torch.float32).cuda()
source_img, source_mask, source_domain_label = batch_source["img"].cuda(), \
batch_source["brain_mask"].cuda(),batch_source["domain_label"].type(torch.float32).cuda()
#p = float(global_step + epoch * len_dataloader) / max_epochs / len_dataloader
#alpha = 2. / (1. + np.exp(-10 * p)) - 1
pred_seg_source,pred_domain_source = model(source_img,alpha)
pred_seg_target,pred_domain_target = model(target_img,alpha)
loss_seg = segmentation_loss(pred_seg_source,source_mask)
dc_loss_source = domain_classifier_loss(m(pred_domain_source).reshape(torch.unsqueeze(source_domain_label,0).shape), torch.unsqueeze(source_domain_label,0))
dc_loss_target = domain_classifier_loss(m(pred_domain_target).reshape(torch.unsqueeze(target_domain_label,0).shape), torch.unsqueeze(target_domain_label,0))
loss_dc = dc_loss_source + dc_loss_target
val_loss = loss_seg + loss_dc
val_dc_loss_source += dc_loss_source.item()
val_dc_loss_target += dc_loss_target.item()
val_seg_loss += loss_seg.item()
val_dc_loss += loss_dc.item()
print("=", end = "", flush=True)
#global_step+=1
val_seg_loss = val_seg_loss/(step+1)
val_dc_loss = val_dc_loss/(step+1)
val_loss = val_seg_loss + val_dc_loss
val_dc_loss_source = val_dc_loss_source / (step + 1)
val_dc_loss_target = val_dc_loss_target / (step + 1)
print(f"\nTraining epoch {epoch}, train loss: {train_loss:.4f}, train seg loss: {train_seg_loss:.4f}, train domain loss: {train_dc_loss:.4f}, train_dc_loss_source: {train_dc_loss_source:.4f}, train_dc_loss_target: {train_dc_loss_target:.4f}",flush=True)
print(f"\nvalidation loss: {val_loss:.4f}, validation seg loss: {val_seg_loss:.4f}, validation domain loss: {val_dc_loss:.4f}, val_dc_loss_source: {val_dc_loss_source:.4f}, val_dc_loss_target: {val_dc_loss_target:.4f}",flush=True)
#print("torch.cuda.memory_allocated: %fGB" % (torch.cuda.memory_allocated(0) / 1024 / 1024 / 1024))
#print("torch.cuda.memory_reserved: %fGB" % (torch.cuda.memory_reserved(0) / 1024 / 1024 / 1024))
#print("torch.cuda.max_memory_reserved: %fGB" % (torch.cuda.max_memory_reserved(0) / 1024 / 1024 / 1024))
if val_seg_loss < best_val_loss:
print("Saving model", flush=True)
torch.save(model.state_dict(), root_dir + "unet_neg_neck.pth")
best_val_loss = val_seg_loss
# Save model and optimizer state after every epoch
checkpoint = {
'epoch': epoch,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'best_val_loss': best_val_loss
}
torch.save(checkpoint, root_dir + "checkpoint.pth")
return
'''
def train_unet_da(source_train_loader, source_val_loader,\
target_train_loader, target_val_loader,\
model, optimizer, scheduler, max_epochs, root_dir,\
loss_weight = 2):
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
model.train()
best_val_loss = 1e+10
segmentation_loss = DiceLoss(to_onehot_y = True)
domain_classifier_loss = nn.BCELoss()#nn.CrossEntropyLoss()
m = nn.Sigmoid()
global_step = 1
for epoch in range(1,max_epochs +1):
train_loss = 0.0
train_seg_loss = 0.0
train_dc_loss = 0.0
val_loss = 0.0
val_seg_loss = 0.0
val_dc_loss = 0.0
print("Epoch ", epoch, flush=True)
print("Train:", end ="", flush=True)
for step, batch in enumerate(zip(target_train_loader, source_train_loader)):
batch_target, batch_source = batch
target_img, target_domain_label = batch_target["img"].cuda(),\
batch_target["domain_label"].type(torch.float32).cuda()
source_img, source_mask, source_domain_label = batch_source["img"].cuda(), \
batch_source["brain_mask"].cuda(),batch_source["domain_label"].type(torch.float32).cuda()
optimizer.zero_grad()
alpha = 2. / (1. + np.exp(-10 * global_step)) - 1
pred_seg_source,pred_domain_source = model(source_img,alpha)
pred_seg_target,pred_domain_target = model(target_img,alpha)
loss_seg = segmentation_loss(pred_seg_source,source_mask)
loss_dc = domain_classifier_loss(m(pred_domain_source).reshape(torch.unsqueeze(source_domain_label,0).shape),torch.unsqueeze(source_domain_label,0))\
+ domain_classifier_loss(m(pred_domain_target).reshape(torch.unsqueeze(target_domain_label,0).shape),torch.unsqueeze(target_domain_label,0))
total_loss = loss_seg + loss_dc
total_loss.backward()
optimizer.step()
train_seg_loss += loss_seg.item()
train_dc_loss += loss_dc.item()
global_step+=1
print("=", end = "", flush=True)
train_seg_loss = train_seg_loss/(step+1)
train_dc_loss = train_dc_loss/(step+1)
train_loss = train_seg_loss + train_dc_loss
# Temporary
print("Training epoch ", epoch, ", train loss:", train_loss,
", train seg loss:", train_seg_loss,", train domain loss:", train_dc_loss, flush=True)
if train_loss < best_val_loss:
print("Saving model", flush=True)
torch.save(model.state_dict(), root_dir + "unet_neg_neck.pth")
best_val_loss = train_loss
'''
'''
print("Val:", end ="", flush=True)
with torch.no_grad():
for step, batch in enumerate(zip(target_val_loader, source_val_loader)):
batch_target, batch_source = batch
target_img, target_domain_label = batch_target["img"].cuda(),\
batch_target["domain_label"].type(torch.float32).cuda()
source_img, source_mask, source_domain_label = batch_source["img"].cuda(), \
batch_source["brain_mask"].cuda(),batch_source["domain_label"].type(torch.float32).cuda()
alpha = 2. / (1. + np.exp(-10 * global_step)) - 1
pred_seg_source,pred_domain_source = model(source_img,alpha)
pred_seg_target,pred_domain_target = model(target_img,alpha)
loss_seg = segmentation_loss(pred_seg_source,source_mask)
loss_dc = domain_classifier_loss(m(pred_domain_source).reshape(torch.unsqueeze(source_domain_label,0).shape),torch.unsqueeze(source_domain_label,0))\
+ domain_classifier_loss(m(pred_domain_target).reshape(torch.unsqueeze(target_domain_label,0).shape),torch.unsqueeze(target_domain_label,0))
print('Domain_classifier_loss:',domain_classifier_loss(m(pred_domain_source).reshape(torch.unsqueeze(source_domain_label,0).shape),torch.unsqueeze(source_domain_label,0)))
print('Source_classifier_loss',domain_classifier_loss(m(pred_domain_target).reshape(torch.unsqueeze(target_domain_label,0).shape),torch.unsqueeze(target_domain_label,0)))
total_loss = loss_seg + loss_dc
val_seg_loss += loss_seg.item()
val_dc_loss += loss_dc.item()
print("=", end = "", flush=True)
global_step+=1
val_seg_loss = val_seg_loss/(step+1)
val_dc_loss = val_dc_loss/(step+1)
val_loss = val_seg_loss + val_dc_loss
print("Training epoch ", epoch, ", train loss:", train_loss,
", train seg loss:", train_seg_loss,", train domain loss:", train_dc_loss,", validation loss:", val_loss,
", validation seg loss:", val_seg_loss,", validation domain loss:", val_dc_loss, flush=True)
if val_loss < best_val_loss:
print("Saving model", flush=True)
torch.save(model.state_dict(), root_dir + "unet_neg_neck.pth")
best_val_loss = val_loss
'''
#return