-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrainer.py
151 lines (127 loc) · 5.87 KB
/
trainer.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
import argparse
import logging
import os
import random
import sys
import time
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from tensorboardX import SummaryWriter
from torch.nn.modules.loss import CrossEntropyLoss
from torch.utils.data import DataLoader
from tqdm import tqdm
from utils import DiceLoss, IoULoss, TverskyLoss, GDiceLoss, HDLoss, FocalDiceLoss, eDiceLoss, BoundaryDoULoss, SSLoss
from torchvision import transforms
from utils import test_single_volume
FloatingPointError
def trainer_synapse(args, model, snapshot_path):
from dataset_synapse import Synapse_dataset, RandomGenerator
logging.basicConfig(filename=snapshot_path + "/log.txt", level=logging.INFO,
format='[%(asctime)s.%(msecs)03d] %(message)s', datefmt='%H:%M:%S')
logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))
logging.info(str(args))
base_lr = args.base_lr
num_classes = args.num_classes
batch_size = args.batch_size * args.n_gpu
# max_iterations = args.max_iterations
db_train = Synapse_dataset(base_dir=args.root_path, list_dir=args.list_dir, split="train",
transform=transforms.Compose(
[RandomGenerator(output_size=[args.img_size, args.img_size])]))
print("The length of train set is: {}".format(len(db_train)))
def worker_init_fn(worker_id):
random.seed(args.seed + worker_id)
trainloader = DataLoader(db_train, batch_size=batch_size, shuffle=True, num_workers=8,
pin_memory=True, persistent_workers=True)
if args.n_gpu > 1:
model = nn.DataParallel(model)
model.train()
if args.loss_type == 'ABeDice':
dice_loss = DiceLoss(num_classes)
elif args.loss_type == 'Dice':
dice_loss = DiceLoss(num_classes)
elif args.loss_type == 'gDice':
dice_loss = GDiceLoss(num_classes)
elif args.loss_type == 'tDice':
dice_loss = TverskyLoss(num_classes)
elif args.loss_type == 'fDice':
dice_loss = FocalDiceLoss(num_classes)
elif args.loss_type == 'eDice':
dice_loss = eDiceLoss(num_classes)
elif args.loss_type == 'hDice':
dice_loss = HDLoss(num_classes)
elif args.loss_type == 'IoU':
dice_loss = IoULoss(num_classes)
elif args.loss_type == 'BDoU':
dice_loss = BoundaryDoULoss(num_classes)
elif args.loss_type == 'SS':
dice_loss = SSLoss(num_classes)
elif args.loss_type == 'CE':
ce_loss = CrossEntropyLoss()
elif args.loss_type == 'CE+Dice':
ce_loss = CrossEntropyLoss()
dice_loss = DiceLoss(num_classes)
optimizer = optim.SGD(model.parameters(), lr=base_lr, momentum=0.9, weight_decay=0.0001)
writer = SummaryWriter(snapshot_path + '/log')
iter_num = 0
max_epoch = args.max_epochs
max_iterations = args.max_epochs * len(trainloader) # max_epoch = max_iterations // len(trainloader) + 1
logging.info("{} iterations per epoch. {} max iterations ".format(len(trainloader), max_iterations))
best_performance = 0.0
iterator = tqdm(range(max_epoch), ncols=70)
for epoch_num in iterator:
for i_batch, sampled_batch in enumerate(trainloader):
image_batch, label_batch = sampled_batch['image'], sampled_batch['label']
image_batch, label_batch = image_batch.cuda(), label_batch.cuda()
outputs = model(image_batch)
if args.loss_type == 'ABeDice':
loss_ce = 0
outputs = torch.softmax(outputs, dim=1)
t = 1
for i in range(args.d_b):
t = 1 - outputs ** t
outputs = outputs ** (args.d_a * t)
loss_dice = dice_loss(outputs, label_batch[:].long())
loss = loss_dice
elif args.loss_type == 'CE':
loss_ce = ce_loss(outputs, label_batch[:].long())
loss_dice = 0
loss = loss_ce
elif args.loss_type == 'CE+Dice':
loss_ce = ce_loss(outputs, label_batch[:].long())
loss_dice = dice_loss(outputs, label_batch, softmax=True)
loss = 0.4 * loss_ce + 0.6 * loss_dice
else:
loss_ce = 0
loss_dice = dice_loss(outputs, label_batch, softmax=True)
loss = loss_dice
optimizer.zero_grad()
loss.backward()
optimizer.step()
lr_ = base_lr * (1.0 - iter_num / max_iterations) ** 0.9
for param_group in optimizer.param_groups:
param_group['lr'] = lr_
iter_num = iter_num + 1
writer.add_scalar('info/lr', lr_, iter_num)
writer.add_scalar('info/total_loss', loss, iter_num)
writer.add_scalar('info/loss_ce', loss_ce, iter_num)
writer.add_scalar('info/loss_dice', loss_dice, iter_num)
logging.info('iteration %d : loss : %f, loss_ce: %f, loss_dice: %f' % (
iter_num, loss.item(), loss_ce, loss_dice.item()))
if iter_num % 20 == 0:
image = image_batch[1, 0:1, :, :]
image = (image - image.min()) / (image.max() - image.min())
writer.add_image('train/Image', image, iter_num)
outputs = torch.argmax(torch.softmax(outputs, dim=1), dim=1, keepdim=True)
writer.add_image('train/Prediction', outputs[1, ...] * 50, iter_num)
labs = label_batch[1, ...].unsqueeze(0) * 50
writer.add_image('train/GroundTruth', labs, iter_num)
if epoch_num >= max_epoch - 1:
save_mode_path = os.path.join(snapshot_path, 'epoch_' + str(epoch_num) + '.pth')
torch.save(model.state_dict(), save_mode_path)
logging.info("save model to {}".format(save_mode_path))
iterator.close()
break
writer.close()
return "Training Finished!"