train_cls.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. import argparse
  2. import datetime
  3. import os
  4. import sys
  5. import numpy as np
  6. from torch.utils.tensorboard import SummaryWriter
  7. import torch
  8. import torch.nn as nn
  9. from torch.optim import SGD
  10. from torch.utils.data import DataLoader
  11. from util.util import enumerateWithEstimate
  12. from .dsets import LunaDataset
  13. from .model_cls import LunaModel
  14. from util.logconf import logging
  15. log = logging.getLogger(__name__)
  16. # log.setLevel(logging.WARN)
  17. log.setLevel(logging.INFO)
  18. # log.setLevel(logging.DEBUG)
  19. # Used for computeBatchLoss and logMetrics to index into metrics_t/metrics_a
  20. METRICS_LABEL_NDX=0
  21. METRICS_PRED_NDX=1
  22. METRICS_LOSS_NDX=2
  23. METRICS_SIZE = 3
  24. class LunaTrainingApp(object):
  25. def __init__(self, sys_argv=None):
  26. if sys_argv is None:
  27. sys_argv = sys.argv[1:]
  28. parser = argparse.ArgumentParser()
  29. parser.add_argument('--batch-size',
  30. help='Batch size to use for training',
  31. default=32,
  32. type=int,
  33. )
  34. parser.add_argument('--num-workers',
  35. help='Number of worker processes for background data loading',
  36. default=8,
  37. type=int,
  38. )
  39. parser.add_argument('--epochs',
  40. help='Number of epochs to train for',
  41. default=1,
  42. type=int,
  43. )
  44. parser.add_argument('--balanced',
  45. help="Balance the training data to half benign, half malignant.",
  46. action='store_true',
  47. default=False,
  48. )
  49. parser.add_argument('--augmented',
  50. help="Augment the training data.",
  51. action='store_true',
  52. default=False,
  53. )
  54. parser.add_argument('--augment-flip',
  55. help="Augment the training data by randomly flipping the data left-right, up-down, and front-back.",
  56. action='store_true',
  57. default=False,
  58. )
  59. parser.add_argument('--augment-offset',
  60. help="Augment the training data by randomly offsetting the data slightly along the X and Y axes.",
  61. action='store_true',
  62. default=False,
  63. )
  64. parser.add_argument('--augment-scale',
  65. help="Augment the training data by randomly increasing or decreasing the size of the nodule.",
  66. action='store_true',
  67. default=False,
  68. )
  69. parser.add_argument('--augment-rotate',
  70. help="Augment the training data by randomly rotating the data around the head-foot axis.",
  71. action='store_true',
  72. default=False,
  73. )
  74. parser.add_argument('--augment-noise',
  75. help="Augment the training data by randomly adding noise to the data.",
  76. action='store_true',
  77. default=False,
  78. )
  79. parser.add_argument('--tb-prefix',
  80. default='p2ch13',
  81. help="Data prefix to use for Tensorboard run. Defaults to chapter.",
  82. )
  83. parser.add_argument('comment',
  84. help="Comment suffix for Tensorboard run.",
  85. nargs='?',
  86. default='dlwpt',
  87. )
  88. self.cli_args = parser.parse_args(sys_argv)
  89. self.time_str = datetime.datetime.now().strftime('%Y-%m-%d_%H.%M.%S')
  90. self.trn_writer = None
  91. self.val_writer = None
  92. self.totalTrainingSamples_count = 0
  93. self.augmentation_dict = {}
  94. if self.cli_args.augmented or self.cli_args.augment_flip:
  95. self.augmentation_dict['flip'] = True
  96. if self.cli_args.augmented or self.cli_args.augment_offset:
  97. self.augmentation_dict['offset'] = 0.1
  98. if self.cli_args.augmented or self.cli_args.augment_scale:
  99. self.augmentation_dict['scale'] = 0.2
  100. if self.cli_args.augmented or self.cli_args.augment_rotate:
  101. self.augmentation_dict['rotate'] = True
  102. if self.cli_args.augmented or self.cli_args.augment_noise:
  103. self.augmentation_dict['noise'] = 25.0
  104. self.use_cuda = torch.cuda.is_available()
  105. self.device = torch.device("cuda" if self.use_cuda else "cpu")
  106. self.model = self.initModel()
  107. self.optimizer = self.initOptimizer()
  108. def initModel(self):
  109. model = LunaModel()
  110. if self.use_cuda:
  111. log.info("Using CUDA with {} devices.".format(torch.cuda.device_count()))
  112. if torch.cuda.device_count() > 1:
  113. model = nn.DataParallel(model)
  114. model = model.to(self.device)
  115. return model
  116. def initOptimizer(self):
  117. return SGD(self.model.parameters(), lr=0.001, momentum=0.99)
  118. # return Adam(self.model.parameters())
  119. def initTrainDl(self):
  120. train_ds = LunaDataset(
  121. val_stride=10,
  122. isValSet_bool=False,
  123. ratio_int=int(self.cli_args.balanced),
  124. augmentation_dict=self.augmentation_dict,
  125. )
  126. train_dl = DataLoader(
  127. train_ds,
  128. batch_size=self.cli_args.batch_size * (torch.cuda.device_count() if self.use_cuda else 1),
  129. num_workers=self.cli_args.num_workers,
  130. pin_memory=self.use_cuda,
  131. )
  132. return train_dl
  133. def initValDl(self):
  134. val_ds = LunaDataset(
  135. val_stride=10,
  136. isValSet_bool=True,
  137. )
  138. val_dl = DataLoader(
  139. val_ds,
  140. batch_size=self.cli_args.batch_size * (torch.cuda.device_count() if self.use_cuda else 1),
  141. num_workers=self.cli_args.num_workers,
  142. pin_memory=self.use_cuda,
  143. )
  144. return val_dl
  145. def initTensorboardWriters(self):
  146. if self.trn_writer is None:
  147. log_dir = os.path.join('runs', self.cli_args.tb_prefix, self.time_str)
  148. self.trn_writer = SummaryWriter(log_dir=log_dir + '-trn_cls-' + self.cli_args.comment)
  149. self.val_writer = SummaryWriter(log_dir=log_dir + '-val_cls-' + self.cli_args.comment)
  150. def main(self):
  151. log.info("Starting {}, {}".format(type(self).__name__, self.cli_args))
  152. train_dl = self.initTrainDl()
  153. val_dl = self.initValDl()
  154. best_score = 0.0
  155. for epoch_ndx in range(1, self.cli_args.epochs + 1):
  156. log.info("Epoch {} of {}, {}/{} batches of size {}*{}".format(
  157. epoch_ndx,
  158. self.cli_args.epochs,
  159. len(train_dl),
  160. len(val_dl),
  161. self.cli_args.batch_size,
  162. (torch.cuda.device_count() if self.use_cuda else 1),
  163. ))
  164. trnMetrics_t = self.doTraining(epoch_ndx, train_dl)
  165. self.logMetrics(epoch_ndx, 'trn', trnMetrics_t)
  166. valMetrics_t = self.doValidation(epoch_ndx, val_dl)
  167. score = self.logMetrics(epoch_ndx, 'val', valMetrics_t)
  168. best_score = max(score, best_score)
  169. self.saveModel('cls', epoch_ndx, score == best_score)
  170. if hasattr(self, 'trn_writer'):
  171. self.trn_writer.close()
  172. self.val_writer.close()
  173. def doTraining(self, epoch_ndx, train_dl):
  174. self.model.train()
  175. train_dl.dataset.shuffleSamples()
  176. trnMetrics_g = torch.zeros(
  177. METRICS_SIZE,
  178. len(train_dl.dataset),
  179. ).to(self.device)
  180. batch_iter = enumerateWithEstimate(
  181. train_dl,
  182. "E{} Training".format(epoch_ndx),
  183. start_ndx=train_dl.num_workers,
  184. )
  185. for batch_ndx, batch_tup in batch_iter:
  186. self.optimizer.zero_grad()
  187. loss_var = self.computeBatchLoss(
  188. batch_ndx,
  189. batch_tup,
  190. train_dl.batch_size,
  191. trnMetrics_g
  192. )
  193. loss_var.backward()
  194. self.optimizer.step()
  195. del loss_var
  196. self.totalTrainingSamples_count += len(train_dl.dataset)
  197. return trnMetrics_g.to('cpu')
  198. def doValidation(self, epoch_ndx, val_dl):
  199. with torch.no_grad():
  200. self.model.eval()
  201. valMetrics_g = torch.zeros(
  202. METRICS_SIZE,
  203. len(val_dl.dataset),
  204. ).to(self.device)
  205. batch_iter = enumerateWithEstimate(
  206. val_dl,
  207. "E{} Validation ".format(epoch_ndx),
  208. start_ndx=val_dl.num_workers,
  209. )
  210. for batch_ndx, batch_tup in batch_iter:
  211. self.computeBatchLoss(
  212. batch_ndx,
  213. batch_tup,
  214. val_dl.batch_size,
  215. valMetrics_g,
  216. )
  217. return valMetrics_g.to('cpu')
  218. def computeBatchLoss(self, batch_ndx, batch_tup, batch_size, metrics_g):
  219. input_t, label_t, _series_list, _center_list = batch_tup
  220. input_g = input_t.to(self.device, non_blocking=True)
  221. label_g = label_t.to(self.device, non_blocking=True)
  222. logits_g, probability_g = self.model(input_g)
  223. loss_func = nn.CrossEntropyLoss(reduction='none')
  224. loss_g = loss_func(
  225. logits_g,
  226. label_g[:,1],
  227. )
  228. start_ndx = batch_ndx * batch_size
  229. end_ndx = start_ndx + label_t.size(0)
  230. metrics_g[METRICS_LABEL_NDX, start_ndx:end_ndx] = label_g[:,1]
  231. metrics_g[METRICS_PRED_NDX, start_ndx:end_ndx] = probability_g[:,1]
  232. metrics_g[METRICS_LOSS_NDX, start_ndx:end_ndx] = loss_g
  233. return loss_g.mean()
  234. def logMetrics(
  235. self,
  236. epoch_ndx,
  237. mode_str,
  238. metrics_t,
  239. ):
  240. self.initTensorboardWriters()
  241. log.info("E{} {}".format(
  242. epoch_ndx,
  243. type(self).__name__,
  244. ))
  245. metrics_t = metrics_t.detach().numpy()
  246. benLabel_mask = metrics_t[METRICS_LABEL_NDX] <= 0.5
  247. benPred_mask = metrics_t[METRICS_PRED_NDX] <= 0.5
  248. malLabel_mask = ~benLabel_mask
  249. malPred_mask = ~benPred_mask
  250. ben_count = benLabel_mask.sum()
  251. mal_count = malLabel_mask.sum()
  252. trueNeg_count = ben_correct = (benLabel_mask & benPred_mask).sum()
  253. truePos_count = mal_correct = (malLabel_mask & malPred_mask).sum()
  254. falsePos_count = ben_count - ben_correct
  255. falseNeg_count = mal_count - mal_correct
  256. metrics_dict = {}
  257. metrics_dict['loss/all'] = metrics_t[METRICS_LOSS_NDX].mean()
  258. metrics_dict['loss/ben'] = metrics_t[METRICS_LOSS_NDX, benLabel_mask].mean()
  259. metrics_dict['loss/mal'] = metrics_t[METRICS_LOSS_NDX, malLabel_mask].mean()
  260. metrics_dict['correct/all'] = (mal_correct + ben_correct) / metrics_t.shape[1] * 100
  261. metrics_dict['correct/ben'] = (ben_correct) / ben_count * 100
  262. metrics_dict['correct/mal'] = (mal_correct) / mal_count * 100
  263. precision = metrics_dict['pr/precision'] = \
  264. truePos_count / (truePos_count + falsePos_count)
  265. recall = metrics_dict['pr/recall'] = \
  266. truePos_count / (truePos_count + falseNeg_count)
  267. metrics_dict['pr/f1_score'] = \
  268. 2 * (precision * recall) / (precision + recall)
  269. log.info(
  270. ("E{} {:8} {loss/all:.4f} loss, "
  271. + "{correct/all:-5.1f}% correct, "
  272. + "{pr/precision:.4f} precision, "
  273. + "{pr/recall:.4f} recall, "
  274. + "{pr/f1_score:.4f} f1 score"
  275. ).format(
  276. epoch_ndx,
  277. mode_str,
  278. **metrics_dict,
  279. )
  280. )
  281. log.info(
  282. ("E{} {:8} {loss/ben:.4f} loss, "
  283. + "{correct/ben:-5.1f}% correct ({ben_correct:} of {ben_count:})"
  284. ).format(
  285. epoch_ndx,
  286. mode_str + '_ben',
  287. ben_correct=ben_correct,
  288. ben_count=ben_count,
  289. **metrics_dict,
  290. )
  291. )
  292. log.info(
  293. ("E{} {:8} {loss/mal:.4f} loss, "
  294. + "{correct/mal:-5.1f}% correct ({mal_correct:} of {mal_count:})"
  295. ).format(
  296. epoch_ndx,
  297. mode_str + '_mal',
  298. mal_correct=mal_correct,
  299. mal_count=mal_count,
  300. **metrics_dict,
  301. )
  302. )
  303. writer = getattr(self, mode_str + '_writer')
  304. for key, value in metrics_dict.items():
  305. writer.add_scalar(key, value, self.totalTrainingSamples_count)
  306. writer.add_pr_curve(
  307. 'pr',
  308. metrics_t[METRICS_LABEL_NDX],
  309. metrics_t[METRICS_PRED_NDX],
  310. self.totalTrainingSamples_count,
  311. )
  312. bins = [x/50.0 for x in range(51)]
  313. benHist_mask = benLabel_mask & (metrics_t[METRICS_PRED_NDX] > 0.01)
  314. malHist_mask = malLabel_mask & (metrics_t[METRICS_PRED_NDX] < 0.99)
  315. if benHist_mask.any():
  316. writer.add_histogram(
  317. 'is_ben',
  318. metrics_t[METRICS_PRED_NDX, benHist_mask],
  319. self.totalTrainingSamples_count,
  320. bins=bins,
  321. )
  322. if malHist_mask.any():
  323. writer.add_histogram(
  324. 'is_mal',
  325. metrics_t[METRICS_PRED_NDX, malHist_mask],
  326. self.totalTrainingSamples_count,
  327. bins=bins,
  328. )
  329. score = 1 \
  330. + metrics_dict['pr/f1_score'] \
  331. - metrics_dict['loss/mal'] * 0.01 \
  332. - metrics_dict['loss/all'] * 0.0001
  333. return score
  334. def saveModel(self, type_str, epoch_ndx, isBest=False):
  335. file_path = os.path.join(
  336. 'data-unversioned',
  337. 'part2',
  338. 'models',
  339. self.cli_args.tb_prefix,
  340. '{}_{}_{}.{}.state'.format(
  341. type_str,
  342. self.time_str,
  343. self.cli_args.comment,
  344. self.totalTrainingSamples_count,
  345. )
  346. )
  347. os.makedirs(os.path.dirname(file_path), mode=0o755, exist_ok=True)
  348. model = self.model
  349. if hasattr(model, 'module'):
  350. model = model.module
  351. state = {
  352. 'model_state': model.state_dict(),
  353. 'model_name': type(model).__name__,
  354. 'optimizer_state' : self.optimizer.state_dict(),
  355. 'optimizer_name': type(self.optimizer).__name__,
  356. 'epoch': epoch_ndx,
  357. 'totalTrainingSamples_count': self.totalTrainingSamples_count,
  358. # 'resumed_from': self.cli_args.resume,
  359. }
  360. torch.save(state, file_path)
  361. log.debug("Saved model params to {}".format(file_path))
  362. if isBest:
  363. file_path = os.path.join(
  364. 'data-unversioned',
  365. 'part2',
  366. 'models',
  367. self.cli_args.tb_prefix,
  368. '{}_{}_{}.{}.state'.format(
  369. type_str,
  370. self.time_str,
  371. self.cli_args.comment,
  372. 'best',
  373. )
  374. )
  375. torch.save(state, file_path)
  376. log.debug("Saved model params to {}".format(file_path))
  377. if __name__ == '__main__':
  378. LunaTrainingApp().main()