forked from deep-learning-with-pytorch/dlwpt-code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtraining.py
528 lines (424 loc) · 18.2 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
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
import argparse
import datetime
import hashlib
import os
import shutil
import socket
import sys
import numpy as np
from torch.utils.tensorboard import SummaryWriter
import torch
import torch.nn as nn
import torch.optim
from torch.optim import SGD, Adam
from torch.utils.data import DataLoader
from util.util import enumerateWithEstimate
from .dsets import Luna2dSegmentationDataset, TrainingLuna2dSegmentationDataset, getCt
from util.logconf import logging
from .model import UNetWrapper, SegmentationAugmentation
log = logging.getLogger(__name__)
# log.setLevel(logging.WARN)
# log.setLevel(logging.INFO)
log.setLevel(logging.DEBUG)
# Used for computeClassificationLoss and logMetrics to index into metrics_t/metrics_a
# METRICS_LABEL_NDX = 0
METRICS_LOSS_NDX = 1
# METRICS_FN_LOSS_NDX = 2
# METRICS_ALL_LOSS_NDX = 3
# METRICS_PTP_NDX = 4
# METRICS_PFN_NDX = 5
# METRICS_MFP_NDX = 6
METRICS_TP_NDX = 7
METRICS_FN_NDX = 8
METRICS_FP_NDX = 9
METRICS_SIZE = 10
class SegmentationTrainingApp:
def __init__(self, sys_argv=None):
if sys_argv is None:
sys_argv = sys.argv[1:]
parser = argparse.ArgumentParser()
parser.add_argument('--batch-size',
help='Batch size to use for training',
default=16,
type=int,
)
parser.add_argument('--num-workers',
help='Number of worker processes for background data loading',
default=8,
type=int,
)
parser.add_argument('--epochs',
help='Number of epochs to train for',
default=1,
type=int,
)
parser.add_argument('--augmented',
help="Augment the training data.",
action='store_true',
default=False,
)
parser.add_argument('--augment-flip',
help="Augment the training data by randomly flipping the data left-right, up-down, and front-back.",
action='store_true',
default=False,
)
parser.add_argument('--augment-offset',
help="Augment the training data by randomly offsetting the data slightly along the X and Y axes.",
action='store_true',
default=False,
)
parser.add_argument('--augment-scale',
help="Augment the training data by randomly increasing or decreasing the size of the candidate.",
action='store_true',
default=False,
)
parser.add_argument('--augment-rotate',
help="Augment the training data by randomly rotating the data around the head-foot axis.",
action='store_true',
default=False,
)
parser.add_argument('--augment-noise',
help="Augment the training data by randomly adding noise to the data.",
action='store_true',
default=False,
)
parser.add_argument('--tb-prefix',
default='p2ch13',
help="Data prefix to use for Tensorboard run. Defaults to chapter.",
)
parser.add_argument('comment',
help="Comment suffix for Tensorboard run.",
nargs='?',
default='none',
)
self.cli_args = parser.parse_args(sys_argv)
self.time_str = datetime.datetime.now().strftime('%Y-%m-%d_%H.%M.%S')
self.totalTrainingSamples_count = 0
self.trn_writer = None
self.val_writer = None
self.augmentation_dict = {}
if self.cli_args.augmented or self.cli_args.augment_flip:
self.augmentation_dict['flip'] = True
if self.cli_args.augmented or self.cli_args.augment_offset:
self.augmentation_dict['offset'] = 0.03
if self.cli_args.augmented or self.cli_args.augment_scale:
self.augmentation_dict['scale'] = 0.2
if self.cli_args.augmented or self.cli_args.augment_rotate:
self.augmentation_dict['rotate'] = True
if self.cli_args.augmented or self.cli_args.augment_noise:
self.augmentation_dict['noise'] = 25.0
self.use_cuda = torch.cuda.is_available()
self.device = torch.device("cuda" if self.use_cuda else "cpu")
self.segmentation_model, self.augmentation_model = self.initModel()
self.optimizer = self.initOptimizer()
def initModel(self):
segmentation_model = UNetWrapper(
in_channels=7,
n_classes=1,
depth=3,
wf=4,
padding=True,
batch_norm=True,
up_mode='upconv',
)
augmentation_model = SegmentationAugmentation(**self.augmentation_dict)
if self.use_cuda:
log.info("Using CUDA; {} devices.".format(torch.cuda.device_count()))
if torch.cuda.device_count() > 1:
segmentation_model = nn.DataParallel(segmentation_model)
augmentation_model = nn.DataParallel(augmentation_model)
segmentation_model = segmentation_model.to(self.device)
augmentation_model = augmentation_model.to(self.device)
return segmentation_model, augmentation_model
def initOptimizer(self):
return Adam(self.segmentation_model.parameters())
# return SGD(self.segmentation_model.parameters(), lr=0.001, momentum=0.99)
def initTrainDl(self):
train_ds = TrainingLuna2dSegmentationDataset(
val_stride=10,
isValSet_bool=False,
contextSlices_count=3,
)
batch_size = self.cli_args.batch_size
if self.use_cuda:
batch_size *= torch.cuda.device_count()
train_dl = DataLoader(
train_ds,
batch_size=batch_size,
num_workers=self.cli_args.num_workers,
pin_memory=self.use_cuda,
)
return train_dl
def initValDl(self):
val_ds = Luna2dSegmentationDataset(
val_stride=10,
isValSet_bool=True,
contextSlices_count=3,
)
batch_size = self.cli_args.batch_size
if self.use_cuda:
batch_size *= torch.cuda.device_count()
val_dl = DataLoader(
val_ds,
batch_size=batch_size,
num_workers=self.cli_args.num_workers,
pin_memory=self.use_cuda,
)
return val_dl
def initTensorboardWriters(self):
if self.trn_writer is None:
log_dir = os.path.join('runs', self.cli_args.tb_prefix, self.time_str)
self.trn_writer = SummaryWriter(
log_dir=log_dir + '_trn_seg_' + self.cli_args.comment)
self.val_writer = SummaryWriter(
log_dir=log_dir + '_val_seg_' + self.cli_args.comment)
def main(self):
log.info("Starting {}, {}".format(type(self).__name__, self.cli_args))
train_dl = self.initTrainDl()
val_dl = self.initValDl()
best_score = 0.0
self.validation_cadence = 5
for epoch_ndx in range(1, self.cli_args.epochs + 1):
log.info("Epoch {} of {}, {}/{} batches of size {}*{}".format(
epoch_ndx,
self.cli_args.epochs,
len(train_dl),
len(val_dl),
self.cli_args.batch_size,
(torch.cuda.device_count() if self.use_cuda else 1),
))
trnMetrics_t = self.doTraining(epoch_ndx, train_dl)
self.logMetrics(epoch_ndx, 'trn', trnMetrics_t)
if epoch_ndx == 1 or epoch_ndx % self.validation_cadence == 0:
# if validation is wanted
valMetrics_t = self.doValidation(epoch_ndx, val_dl)
score = self.logMetrics(epoch_ndx, 'val', valMetrics_t)
best_score = max(score, best_score)
self.saveModel('seg', epoch_ndx, score == best_score)
self.logImages(epoch_ndx, 'trn', train_dl)
self.logImages(epoch_ndx, 'val', val_dl)
self.trn_writer.close()
self.val_writer.close()
def doTraining(self, epoch_ndx, train_dl):
trnMetrics_g = torch.zeros(METRICS_SIZE, len(train_dl.dataset), device=self.device)
self.segmentation_model.train()
train_dl.dataset.shuffleSamples()
batch_iter = enumerateWithEstimate(
train_dl,
"E{} Training".format(epoch_ndx),
start_ndx=train_dl.num_workers,
)
for batch_ndx, batch_tup in batch_iter:
self.optimizer.zero_grad()
loss_var = self.computeBatchLoss(batch_ndx, batch_tup, train_dl.batch_size, trnMetrics_g)
loss_var.backward()
self.optimizer.step()
self.totalTrainingSamples_count += trnMetrics_g.size(1)
return trnMetrics_g.to('cpu')
def doValidation(self, epoch_ndx, val_dl):
with torch.no_grad():
valMetrics_g = torch.zeros(METRICS_SIZE, len(val_dl.dataset), device=self.device)
self.segmentation_model.eval()
batch_iter = enumerateWithEstimate(
val_dl,
"E{} Validation ".format(epoch_ndx),
start_ndx=val_dl.num_workers,
)
for batch_ndx, batch_tup in batch_iter:
self.computeBatchLoss(batch_ndx, batch_tup, val_dl.batch_size, valMetrics_g)
return valMetrics_g.to('cpu')
def computeBatchLoss(self, batch_ndx, batch_tup, batch_size, metrics_g,
classificationThreshold=0.5):
input_t, label_t, series_list, _slice_ndx_list = batch_tup
input_g = input_t.to(self.device, non_blocking=True)
label_g = label_t.to(self.device, non_blocking=True)
if self.segmentation_model.training and self.augmentation_dict:
input_g, label_g = self.augmentation_model(input_g, label_g)
prediction_g = self.segmentation_model(input_g)
diceLoss_g = self.diceLoss(prediction_g, label_g)
fnLoss_g = self.diceLoss(prediction_g * label_g, label_g)
start_ndx = batch_ndx * batch_size
end_ndx = start_ndx + input_t.size(0)
with torch.no_grad():
predictionBool_g = (prediction_g[:, 0:1]
> classificationThreshold).to(torch.float32)
tp = ( predictionBool_g * label_g).sum(dim=[1,2,3])
fn = ((1 - predictionBool_g) * label_g).sum(dim=[1,2,3])
fp = ( predictionBool_g * (~label_g)).sum(dim=[1,2,3])
metrics_g[METRICS_LOSS_NDX, start_ndx:end_ndx] = diceLoss_g
metrics_g[METRICS_TP_NDX, start_ndx:end_ndx] = tp
metrics_g[METRICS_FN_NDX, start_ndx:end_ndx] = fn
metrics_g[METRICS_FP_NDX, start_ndx:end_ndx] = fp
return diceLoss_g.mean() + fnLoss_g.mean() * 8
def diceLoss(self, prediction_g, label_g, epsilon=1):
diceLabel_g = label_g.sum(dim=[1,2,3])
dicePrediction_g = prediction_g.sum(dim=[1,2,3])
diceCorrect_g = (prediction_g * label_g).sum(dim=[1,2,3])
diceRatio_g = (2 * diceCorrect_g + epsilon) \
/ (dicePrediction_g + diceLabel_g + epsilon)
return 1 - diceRatio_g
def logImages(self, epoch_ndx, mode_str, dl):
self.segmentation_model.eval()
images = sorted(dl.dataset.series_list)[:12]
for series_ndx, series_uid in enumerate(images):
ct = getCt(series_uid)
for slice_ndx in range(6):
ct_ndx = slice_ndx * (ct.hu_a.shape[0] - 1) // 5
sample_tup = dl.dataset.getitem_fullSlice(series_uid, ct_ndx)
ct_t, label_t, series_uid, ct_ndx = sample_tup
input_g = ct_t.to(self.device).unsqueeze(0)
label_g = pos_g = label_t.to(self.device).unsqueeze(0)
prediction_g = self.segmentation_model(input_g)[0]
prediction_a = prediction_g.to('cpu').detach().numpy()[0] > 0.5
label_a = label_g.cpu().numpy()[0][0] > 0.5
ct_t[:-1,:,:] /= 2000
ct_t[:-1,:,:] += 0.5
ctSlice_a = ct_t[dl.dataset.contextSlices_count].numpy()
image_a = np.zeros((512, 512, 3), dtype=np.float32)
image_a[:,:,:] = ctSlice_a.reshape((512,512,1))
image_a[:,:,0] += prediction_a & (1 - label_a)
image_a[:,:,0] += (1 - prediction_a) & label_a
image_a[:,:,1] += ((1 - prediction_a) & label_a) * 0.5
image_a[:,:,1] += prediction_a & label_a
image_a *= 0.5
image_a.clip(0, 1, image_a)
writer = getattr(self, mode_str + '_writer')
writer.add_image(
f'{mode_str}/{series_ndx}_prediction_{slice_ndx}',
image_a,
self.totalTrainingSamples_count,
dataformats='HWC',
)
if epoch_ndx == 1:
image_a = np.zeros((512, 512, 3), dtype=np.float32)
image_a[:,:,:] = ctSlice_a.reshape((512,512,1))
# image_a[:,:,0] += (1 - label_a) & lung_a # Red
image_a[:,:,1] += label_a # Green
# image_a[:,:,2] += neg_a # Blue
image_a *= 0.5
image_a[image_a < 0] = 0
image_a[image_a > 1] = 1
writer.add_image(
'{}/{}_label_{}'.format(
mode_str,
series_ndx,
slice_ndx,
),
image_a,
self.totalTrainingSamples_count,
dataformats='HWC',
)
# This flush prevents TB from getting confused about which
# data item belongs where.
writer.flush()
def logMetrics(self, epoch_ndx, mode_str, metrics_t):
log.info("E{} {}".format(
epoch_ndx,
type(self).__name__,
))
metrics_a = metrics_t.detach().numpy()
sum_a = metrics_a.sum(axis=1)
assert np.isfinite(metrics_a).all()
allLabel_count = sum_a[METRICS_TP_NDX] + sum_a[METRICS_FN_NDX]
metrics_dict = {}
metrics_dict['loss/all'] = metrics_a[METRICS_LOSS_NDX].mean()
metrics_dict['percent_all/tp'] = \
sum_a[METRICS_TP_NDX] / (allLabel_count or 1) * 100
metrics_dict['percent_all/fn'] = \
sum_a[METRICS_FN_NDX] / (allLabel_count or 1) * 100
metrics_dict['percent_all/fp'] = \
sum_a[METRICS_FP_NDX] / (allLabel_count or 1) * 100
precision = metrics_dict['pr/precision'] = sum_a[METRICS_TP_NDX] \
/ ((sum_a[METRICS_TP_NDX] + sum_a[METRICS_FP_NDX]) or 1)
recall = metrics_dict['pr/recall'] = sum_a[METRICS_TP_NDX] \
/ ((sum_a[METRICS_TP_NDX] + sum_a[METRICS_FN_NDX]) or 1)
metrics_dict['pr/f1_score'] = 2 * (precision * recall) \
/ ((precision + recall) or 1)
log.info(("E{} {:8} "
+ "{loss/all:.4f} loss, "
+ "{pr/precision:.4f} precision, "
+ "{pr/recall:.4f} recall, "
+ "{pr/f1_score:.4f} f1 score"
).format(
epoch_ndx,
mode_str,
**metrics_dict,
))
log.info(("E{} {:8} "
+ "{loss/all:.4f} loss, "
+ "{percent_all/tp:-5.1f}% tp, {percent_all/fn:-5.1f}% fn, {percent_all/fp:-9.1f}% fp"
).format(
epoch_ndx,
mode_str + '_all',
**metrics_dict,
))
self.initTensorboardWriters()
writer = getattr(self, mode_str + '_writer')
prefix_str = 'seg_'
for key, value in metrics_dict.items():
writer.add_scalar(prefix_str + key, value, self.totalTrainingSamples_count)
writer.flush()
score = metrics_dict['pr/recall']
return score
# def logModelMetrics(self, model):
# writer = getattr(self, 'trn_writer')
#
# model = getattr(model, 'module', model)
#
# for name, param in model.named_parameters():
# if param.requires_grad:
# min_data = float(param.data.min())
# max_data = float(param.data.max())
# max_extent = max(abs(min_data), abs(max_data))
#
# # bins = [x/50*max_extent for x in range(-50, 51)]
#
# writer.add_histogram(
# name.rsplit('.', 1)[-1] + '/' + name,
# param.data.cpu().numpy(),
# # metrics_a[METRICS_PRED_NDX, negHist_mask],
# self.totalTrainingSamples_count,
# # bins=bins,
# )
#
# # print name, param.data
def saveModel(self, type_str, epoch_ndx, isBest=False):
file_path = os.path.join(
'data-unversioned',
'part2',
'models',
self.cli_args.tb_prefix,
'{}_{}_{}.{}.state'.format(
type_str,
self.time_str,
self.cli_args.comment,
self.totalTrainingSamples_count,
)
)
os.makedirs(os.path.dirname(file_path), mode=0o755, exist_ok=True)
model = self.segmentation_model
if isinstance(model, torch.nn.DataParallel):
model = model.module
state = {
'sys_argv': sys.argv,
'time': str(datetime.datetime.now()),
'model_state': model.state_dict(),
'model_name': type(model).__name__,
'optimizer_state' : self.optimizer.state_dict(),
'optimizer_name': type(self.optimizer).__name__,
'epoch': epoch_ndx,
'totalTrainingSamples_count': self.totalTrainingSamples_count,
}
torch.save(state, file_path)
log.info("Saved model params to {}".format(file_path))
if isBest:
best_path = os.path.join(
'data-unversioned', 'part2', 'models',
self.cli_args.tb_prefix,
f'{type_str}_{self.time_str}_{self.cli_args.comment}.best.state')
shutil.copyfile(file_path, best_path)
log.info("Saved model params to {}".format(best_path))
with open(file_path, 'rb') as f:
log.info("SHA1: " + hashlib.sha1(f.read()).hexdigest())
if __name__ == '__main__':
SegmentationTrainingApp().main()