-
Notifications
You must be signed in to change notification settings - Fork 29
/
train_model.py
143 lines (110 loc) · 4.49 KB
/
train_model.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
import torch
import torch.nn.functional as F
from torch import nn
from torch.utils.data import DataLoader
from torchvision import transforms
from torch.autograd import Variable
from build_model import FCN_GCN
import os
import csv
class SoftDiceLoss(nn.Module):
def __init__(self, weight=None, size_average=True):
super(SoftDiceLoss, self).__init__()
def forward(self, logits, targets):
smooth = 1.
logits = F.sigmoid(logits)
iflat = logits.view(-1)
tflat = targets.view(-1)
intersection = (iflat * tflat).sum()
return 1 - ((2. * intersection + smooth) /(iflat.sum() + tflat.sum() + smooth))
class SoftInvDiceLoss(nn.Module):
def __init__(self, weight=None, size_average=True):
super(SoftInvDiceLoss, self).__init__()
def forward(self, logits, targets):
smooth = 1.
logits = F.sigmoid(logits)
iflat = 1 - logits.view(-1)
tflat = 1 - targets.view(-1)
intersection = (iflat * tflat).sum()
return 1 - ((2. * intersection + smooth) /(iflat.sum() + tflat.sum() + smooth))
img_size = (1024,1024)
transformations_train = transforms.Compose([transforms.Resize(img_size),
transforms.RandomRotation(10),
transforms.RandomHorizontalFlip(),
transforms.ToTensor()])
transformations_test = transforms.Compose([transforms.Resize(img_size),
transforms.ToTensor()])
from data_loader import LungSeg
from data_loader import LungSegTest
train_set = LungSeg(transforms = transformations_train)
test_set = LungSegTest(transforms = transformations_test)
batch_size = 1
num_epochs = 30
class Average(object):
def __init__(self):
self.reset()
def reset(self):
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.sum += val
self.count += n
@property
def avg(self):
return self.sum / self.count
def train():
cuda = torch.cuda.is_available()
net = FCN_GCN(1)
net.load_state_dict(torch.load('cp.pth'))
criterion1 = nn.BCEWithLogitsLoss()
criterion2 = SoftDiceLoss()
criterion3 = SoftInvDiceLoss()
if cuda:
net = net.cuda()
criterion1 = criterion1.cuda()
criterion2 = criterion2.cuda()
criterion3 = criterion3.cuda()
optimizer = torch.optim.Adam(net.parameters(), lr=4e-5)
#scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[10,20], gamma=0.5)
print("preparing training data ...")
train_loader = DataLoader(train_set, batch_size=batch_size, shuffle=True)
print("done ...")
test_set = LungSegTest(transforms = transformations_test)
test_loader = DataLoader(test_set, batch_size=batch_size)
for epoch in range(num_epochs):
train_loss = Average()
net.train()
#scheduler.step()
for i, (images, masks) in enumerate(train_loader):
images = Variable(images)
masks = Variable(masks)
if cuda:
images = images.cuda()
masks = masks.cuda()
optimizer.zero_grad()
outputs = net(images)
loss = 0.4*criterion1(outputs, masks) + 0.4*criterion2(outputs, masks) + 0.2*criterion3(outputs, masks)
loss.backward()
optimizer.step()
train_loss.update(loss.item(), images.size(0))
val_loss = Average()
val_loss_dice = Average()
net.eval()
for images, masks in test_loader:
images = Variable(images)
masks = Variable(masks)
if cuda:
images = images.cuda()
masks = masks.cuda()
outputs = net(images)
vloss = 0.4*criterion1(outputs, masks) + 0.4*criterion2(outputs, masks) + 0.2*criterion3(outputs, masks)
vloss_dice = criterion2(outputs, masks)
val_loss.update(vloss.item(), images.size(0))
val_loss_dice.update(vloss_dice.item(), images.size(0))
print("Epoch {}/{}, Loss: {}, Validation Loss: {}, Validation Dice Loss: {}".format(epoch+1,num_epochs, train_loss.avg, val_loss.avg, val_loss_dice.avg))
torch.save(net.state_dict(), 'Weights_221/cp_{}_{}.pth'.format(epoch+1, val_loss_dice.avg))
return net
def test(model):
model.eval()
if __name__ == "__main__":
train()