forked from DengPingFan/Inf-Net
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtraining_&_testing_infnet_&_semiinfnet.py
326 lines (261 loc) · 13.6 KB
/
training_&_testing_infnet_&_semiinfnet.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
# -*- coding: utf-8 -*-
"""Training_&_Testing_InfNet_&_SemiInfNet.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1ja8JaidGb1zgkL_aTEnpwEAN7VRBo0CI
**Pooyan Rezaeipour Lasaki**
e-mails:
**Mohsen Safaei**
e-mails: [email protected] & [email protected]
**Saeed Chamani**
e-mails: [email protected]
*Biomedical Engineering Department, School of Electrical Engineering, "Iran University of Science and Technology", Tehran*
*To find the files which you have uploaded in your "Google Drive"*
"""
from google.colab import drive
drive.mount('/content/gdrive')
"""*Unzipping the mentioned file which is named "Inf-Net-master"*"""
!unzip "/content/gdrive/MyDrive/Inf-Net-master.zip"
"""*Install the package named "thop"*"""
pip install thop
"""*For recognizing the module named "Code"*"""
cd '/content/Inf-Net-master'
import sys
sys.path.append('/content/Inf-Net-master')
"""*For solving the error of "ipykernel_launcher.py: error: unrecognized arguments"*"""
!pip install ipykernel
import sys
sys.argv=['-f']
del sys
"""*Training "MyTrain_LungInf.py" for Inf-Net & Semi-Inf-Net*
*The following code is adjusted for Inf-Net. If you want to change it to Semi-Inf-Net, follow the [README.md](https://github.com/DengPingFan/Inf-Net/blob/master/README.md)*
"""
# -*- coding: utf-8 -*-
"""Preview
Code for 'Inf-Net: Automatic COVID-19 Lung Infection Segmentation from CT Scans'
submit to Transactions on Medical Imaging, 2020.
1st Version: Created on 2020-05-13 (@author: Ge-Peng Ji)
2nd Version: Fix some bugs caused by THOP on 2020-06-10 (@author: Ge-Peng Ji)
"""
import torch
from torch.autograd import Variable
import os
import argparse
from datetime import datetime
from Code.utils.dataloader_LungInf import get_loader
from Code.utils.utils import clip_gradient, adjust_lr, AvgMeter
import torch.nn.functional as F
def joint_loss(pred, mask):
weit = 1 + 5*torch.abs(F.avg_pool2d(mask, kernel_size=31, stride=1, padding=15) - mask)
wbce = F.binary_cross_entropy_with_logits(pred, mask, reduce='none')
wbce = (weit*wbce).sum(dim=(2, 3)) / weit.sum(dim=(2, 3))
pred = torch.sigmoid(pred)
inter = ((pred * mask)*weit).sum(dim=(2, 3))
union = ((pred + mask)*weit).sum(dim=(2, 3))
wiou = 1 - (inter + 1)/(union - inter+1)
return (wbce + wiou).mean()
def train(train_loader, model, optimizer, epoch, train_save):
model.train()
# ---- multi-scale training ----
size_rates = [0.75, 1, 1.25] # replace your desired scale, try larger scale for better accuracy in small object
loss_record1, loss_record2, loss_record3, loss_record4, loss_record5 = AvgMeter(), AvgMeter(), AvgMeter(), AvgMeter(), AvgMeter()
for i, pack in enumerate(train_loader, start=1):
for rate in size_rates:
optimizer.zero_grad()
# ---- data prepare ----
images, gts, edges = pack
images = Variable(images).cuda()
gts = Variable(gts).cuda()
edges = Variable(edges).cuda()
# ---- rescaling the inputs (img/gt/edge) ----
trainsize = int(round(opt.trainsize*rate/32)*32)
if rate != 1:
images = F.upsample(images, size=(trainsize, trainsize), mode='bilinear', align_corners=True)
gts = F.upsample(gts, size=(trainsize, trainsize), mode='bilinear', align_corners=True)
edges = F.upsample(edges, size=(trainsize, trainsize), mode='bilinear', align_corners=True)
# ---- forward ----
lateral_map_5, lateral_map_4, lateral_map_3, lateral_map_2, lateral_edge = model(images)
# ---- loss function ----
loss5 = joint_loss(lateral_map_5, gts)
loss4 = joint_loss(lateral_map_4, gts)
loss3 = joint_loss(lateral_map_3, gts)
loss2 = joint_loss(lateral_map_2, gts)
loss1 = BCE(lateral_edge, edges)
loss = loss1 + loss2 + loss3 + loss4 + loss5
# ---- backward ----
loss.backward()
clip_gradient(optimizer, opt.clip)
optimizer.step()
# ---- recording loss ----
if rate == 1:
loss_record1.update(loss1.data, opt.batchsize)
loss_record2.update(loss2.data, opt.batchsize)
loss_record3.update(loss3.data, opt.batchsize)
loss_record4.update(loss4.data, opt.batchsize)
loss_record5.update(loss5.data, opt.batchsize)
# ---- train logging ----
if i % 20 == 0 or i == total_step:
print('{} Epoch [{:03d}/{:03d}], Step [{:04d}/{:04d}], [lateral-edge: {:.4f}, '
'lateral-2: {:.4f}, lateral-3: {:0.4f}, lateral-4: {:0.4f}, lateral-5: {:0.4f}]'.
format(datetime.now(), epoch, opt.epoch, i, total_step, loss_record1.show(),
loss_record2.show(), loss_record3.show(), loss_record4.show(), loss_record5.show()))
# ---- save model_lung_infection ----
save_path = './Snapshots/save_weights/{}/'.format(train_save)
os.makedirs(save_path, exist_ok=True)
if (epoch+1) % 10 == 0:
torch.save(model.state_dict(), save_path + 'Inf-Net-%d.pth' % (epoch+1))
print('[Saving Snapshot:]', save_path + 'Inf-Net-%d.pth' % (epoch+1))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
# hyper-parameters
parser.add_argument('--epoch', type=int, default=100,
help='epoch number')
parser.add_argument('--lr', type=float, default=1e-4,
help='learning rate')
parser.add_argument('--batchsize', type=int, default=24,
help='training batch size')
parser.add_argument('--trainsize', type=int, default=352,
help='set the size of training sample')
parser.add_argument('--clip', type=float, default=0.5,
help='gradient clipping margin')
parser.add_argument('--decay_rate', type=float, default=0.1,
help='decay rate of learning rate')
parser.add_argument('--decay_epoch', type=int, default=50,
help='every n epochs decay learning rate')
parser.add_argument('--is_thop', type=bool, default=False,
help='whether calculate FLOPs/Params (Thop)')
parser.add_argument('--gpu_device', type=int, default=0,
help='choose which GPU device you want to use')
parser.add_argument('--num_workers', type=int, default=8,
help='number of workers in dataloader. In windows, set num_workers=0')
# model_lung_infection parameters
parser.add_argument('--net_channel', type=int, default=32,
help='internal channel numbers in the Inf-Net, default=32, try larger for better accuracy')
parser.add_argument('--n_classes', type=int, default=1,
help='binary segmentation when n_classes=1')
parser.add_argument('--backbone', type=str, default='Res2Net50',
help='change different backbone, choice: VGGNet16, ResNet50, Res2Net50')
# training dataset
parser.add_argument('--train_path', type=str,
default='./Dataset/COVID-SemiSeg/Dataset/TrainingSet/LungInfection-Train/Doctor-label')
parser.add_argument('--is_semi', type=bool, default=False,
help='if True, you will turn on the mode of `Semi-Inf-Net`')
parser.add_argument('--is_pseudo', type=bool, default=False,
help='if True, you will train the model on pseudo-label')
parser.add_argument('--train_save', type=str, default=None,
help='If you use custom save path, please edit `--is_semi=True` and `--is_pseudo=True`')
opt = parser.parse_args()
# ---- build models ----
torch.cuda.set_device(opt.gpu_device)
# - please asign your prefer backbone in opt.
if opt.backbone == 'Res2Net50':
print('Backbone loading: Res2Net50')
from Code.model_lung_infection.InfNet_Res2Net import Inf_Net
elif opt.backbone == 'ResNet50':
print('Backbone loading: ResNet50')
from Code.model_lung_infection.InfNet_ResNet import Inf_Net
elif opt.backbone == 'VGGNet16':
print('Backbone loading: VGGNet16')
from Code.model_lung_infection.InfNet_VGGNet import Inf_Net
else:
raise ValueError('Invalid backbone parameters: {}'.format(opt.backbone))
model = Inf_Net(channel=opt.net_channel, n_class=opt.n_classes).cuda()
# ---- load pre-trained weights (mode=Semi-Inf-Net) ----
# - See Sec.2.3 of `README.md` to learn how to generate your own img/pseudo-label from scratch.
if opt.is_semi and opt.backbone == 'Res2Net50':
print('Loading weights from weights file trained on pseudo label')
model.load_state_dict(torch.load('./Snapshots/save_weights/Inf-Net_Pseduo/Inf-Net_pseudo_100.pth'))
else:
print('Not loading weights from weights file')
# weights file save path
if opt.is_pseudo and (not opt.is_semi):
train_save = 'Inf-Net_Pseudo'
elif (not opt.is_pseudo) and opt.is_semi:
train_save = 'Semi-Inf-Net'
elif (not opt.is_pseudo) and (not opt.is_semi):
train_save = 'Inf-Net'
else:
print('Use custom save path')
train_save = opt.train_save
# ---- calculate FLOPs and Params ----
if opt.is_thop:
from Code.utils.utils import CalParams
x = torch.randn(1, 3, opt.trainsize, opt.trainsize).cuda()
CalParams(model, x)
# ---- load training sub-modules ----
BCE = torch.nn.BCEWithLogitsLoss()
params = model.parameters()
optimizer = torch.optim.Adam(params, opt.lr)
image_root = '{}/Imgs/'.format(opt.train_path)
gt_root = '{}/GT/'.format(opt.train_path)
edge_root = '{}/Edge/'.format(opt.train_path)
train_loader = get_loader(image_root, gt_root, edge_root,
batchsize=opt.batchsize, trainsize=opt.trainsize, num_workers=opt.num_workers)
total_step = len(train_loader)
# ---- start !! -----
print("#"*20, "\nStart Training (Inf-Net-{})\n{}\nThis code is written for 'Inf-Net: Automatic COVID-19 Lung "
"Infection Segmentation from CT Scans', 2020, TMI.\n"
"----\nPlease cite the paper if you use this code and dataset. "
"And any questions feel free to contact me "
"via E-mail ([email protected])\n----\n".format(opt.backbone, opt), "#"*20)
for epoch in range(1, opt.epoch):
adjust_lr(optimizer, opt.lr, epoch, opt.decay_rate, opt.decay_epoch)
train(train_loader, model, optimizer, epoch, train_save)
"""*Testing "MyTest_LungInf.py" for Inf-Net & Semi-Inf-Net*
*The following code is adjusted for Inf-Net. If you want to change it to Semi-Inf-Net, follow the [README.md](https://github.com/DengPingFan/Inf-Net/blob/master/README.md)*
"""
# -*- coding: utf-8 -*-
"""Preview
Code for 'Inf-Net: Automatic COVID-19 Lung Infection Segmentation from CT Scans'
submit to Transactions on Medical Imaging, 2020.
First Version: Created on 2020-05-13 (@author: Ge-Peng Ji)
"""
import torch
import torch.nn.functional as F
import numpy as np
import os
import argparse
from scipy import misc
from Code.model_lung_infection.InfNet_Res2Net import Inf_Net as Network
from Code.utils.dataloader_LungInf import test_dataset
def inference():
parser = argparse.ArgumentParser()
parser.add_argument('--testsize', type=int, default=352, help='testing size')
parser.add_argument('--data_path', type=str, default='./Dataset/COVID-SemiSeg/Dataset/TestingSet/LungInfection-Test/',
help='Path to test data')
parser.add_argument('--pth_path', type=str, default='./Snapshots/save_weights/Inf-Net/Inf-Net-100.pth',
help='Path to weights file. If `semi-sup`, edit it to `Semi-Inf-Net/Semi-Inf-Net-100.pth`')
parser.add_argument('--save_path', type=str, default='./Results/Lung infection segmentation/Inf-Net/',
help='Path to save the predictions. if `semi-sup`, edit it to `Semi-Inf-Net`')
opt = parser.parse_args()
print("#" * 20, "\nStart Testing (Inf-Net)\n{}\nThis code is written for 'Inf-Net: Automatic COVID-19 Lung "
"Infection Segmentation from CT Scans', 2020, TMI.\n"
"----\nPlease cite the paper if you use this code and dataset. "
"And any questions feel free to contact me "
"via E-mail ([email protected])\n----\n".format(opt), "#" * 20)
model = Network()
# model = torch.nn.DataParallel(model, device_ids=[0, 1]) # uncomment it if you have multiply GPUs.
model.load_state_dict(torch.load(opt.pth_path, map_location={'cuda:1':'cuda:0'}))
model.cuda()
model.eval()
image_root = '{}/Imgs/'.format(opt.data_path)
# gt_root = '{}/GT/'.format(opt.data_path)
test_loader = test_dataset(image_root, opt.testsize)
os.makedirs(opt.save_path, exist_ok=True)
for i in range(test_loader.size):
image, name = test_loader.load_data()
image = image.cuda()
lateral_map_5, lateral_map_4, lateral_map_3, lateral_map_2, lateral_edge = model(image)
res = lateral_map_2
# res = F.upsample(res, size=(ori_size[1],ori_size[0]), mode='bilinear', align_corners=False)
res = res.sigmoid().data.cpu().numpy().squeeze()
res = (res - res.min()) / (res.max() - res.min() + 1e-8)
#misc.imsave(opt.save_path + name, res)
import imageio
imageio.imwrite(opt.save_path + name, res)
print('Test Done!')
if __name__ == "__main__":
inference()