无人机视角的行人小目标检测
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

157 lines
6.7KB

  1. # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
  2. """
  3. Logging utils
  4. """
  5. import os
  6. import warnings
  7. from threading import Thread
  8. import pkg_resources as pkg
  9. import torch
  10. from torch.utils.tensorboard import SummaryWriter
  11. from utils.general import colorstr, emojis
  12. from utils.loggers.wandb.wandb_utils import WandbLogger
  13. from utils.plots import plot_images, plot_results
  14. from utils.torch_utils import de_parallel
  15. LOGGERS = ('csv', 'tb', 'wandb') # text-file, TensorBoard, Weights & Biases
  16. RANK = int(os.getenv('RANK', -1))
  17. try:
  18. import wandb
  19. assert hasattr(wandb, '__version__') # verify package import not local dir
  20. if pkg.parse_version(wandb.__version__) >= pkg.parse_version('0.12.2') and RANK in [0, -1]:
  21. wandb_login_success = wandb.login(timeout=30)
  22. if not wandb_login_success:
  23. wandb = None
  24. except (ImportError, AssertionError):
  25. wandb = None
  26. class Loggers():
  27. # YOLOv5 Loggers class
  28. def __init__(self, save_dir=None, weights=None, opt=None, hyp=None, logger=None, include=LOGGERS):
  29. self.save_dir = save_dir
  30. self.weights = weights
  31. self.opt = opt
  32. self.hyp = hyp
  33. self.logger = logger # for printing results to console
  34. self.include = include
  35. self.keys = ['train/box_loss', 'train/obj_loss', 'train/cls_loss', # train loss
  36. 'metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/mAP_0.5:0.95', # metrics
  37. 'val/box_loss', 'val/obj_loss', 'val/cls_loss', # val loss
  38. 'x/lr0', 'x/lr1', 'x/lr2'] # params
  39. for k in LOGGERS:
  40. setattr(self, k, None) # init empty logger dictionary
  41. self.csv = True # always log to csv
  42. # Message
  43. if not wandb:
  44. prefix = colorstr('Weights & Biases: ')
  45. s = f"{prefix}run 'pip install wandb' to automatically track and visualize YOLOv5 🚀 runs (RECOMMENDED)"
  46. print(emojis(s))
  47. # TensorBoard
  48. s = self.save_dir
  49. if 'tb' in self.include and not self.opt.evolve:
  50. prefix = colorstr('TensorBoard: ')
  51. self.logger.info(f"{prefix}Start with 'tensorboard --logdir {s.parent}', view at http://localhost:6006/")
  52. self.tb = SummaryWriter(str(s))
  53. # W&B
  54. if wandb and 'wandb' in self.include:
  55. wandb_artifact_resume = isinstance(self.opt.resume, str) and self.opt.resume.startswith('wandb-artifact://')
  56. run_id = torch.load(self.weights).get('wandb_id') if self.opt.resume and not wandb_artifact_resume else None
  57. self.opt.hyp = self.hyp # add hyperparameters
  58. self.wandb = WandbLogger(self.opt, run_id)
  59. else:
  60. self.wandb = None
  61. def on_pretrain_routine_end(self):
  62. # Callback runs on pre-train routine end
  63. paths = self.save_dir.glob('*labels*.jpg') # training labels
  64. if self.wandb:
  65. self.wandb.log({"Labels": [wandb.Image(str(x), caption=x.name) for x in paths]})
  66. def on_train_batch_end(self, ni, model, imgs, targets, paths, plots, sync_bn):
  67. # Callback runs on train batch end
  68. if plots:
  69. if ni == 0:
  70. if not sync_bn: # tb.add_graph() --sync known issue https://github.com/ultralytics/yolov5/issues/3754
  71. with warnings.catch_warnings():
  72. warnings.simplefilter('ignore') # suppress jit trace warning
  73. self.tb.add_graph(torch.jit.trace(de_parallel(model), imgs[0:1], strict=False), [])
  74. if ni < 3:
  75. f = self.save_dir / f'train_batch{ni}.jpg' # filename
  76. Thread(target=plot_images, args=(imgs, targets, paths, f), daemon=True).start()
  77. if self.wandb and ni == 10:
  78. files = sorted(self.save_dir.glob('train*.jpg'))
  79. self.wandb.log({'Mosaics': [wandb.Image(str(f), caption=f.name) for f in files if f.exists()]})
  80. def on_train_epoch_end(self, epoch):
  81. # Callback runs on train epoch end
  82. if self.wandb:
  83. self.wandb.current_epoch = epoch + 1
  84. def on_val_image_end(self, pred, predn, path, names, im):
  85. # Callback runs on val image end
  86. if self.wandb:
  87. self.wandb.val_one_image(pred, predn, path, names, im)
  88. def on_val_end(self):
  89. # Callback runs on val end
  90. if self.wandb:
  91. files = sorted(self.save_dir.glob('val*.jpg'))
  92. self.wandb.log({"Validation": [wandb.Image(str(f), caption=f.name) for f in files]})
  93. def on_fit_epoch_end(self, vals, epoch, best_fitness, fi):
  94. # Callback runs at the end of each fit (train+val) epoch
  95. x = {k: v for k, v in zip(self.keys, vals)} # dict
  96. if self.csv:
  97. file = self.save_dir / 'results.csv'
  98. n = len(x) + 1 # number of cols
  99. s = '' if file.exists() else (('%20s,' * n % tuple(['epoch'] + self.keys)).rstrip(',') + '\n') # add header
  100. with open(file, 'a') as f:
  101. f.write(s + ('%20.5g,' * n % tuple([epoch] + vals)).rstrip(',') + '\n')
  102. if self.tb:
  103. for k, v in x.items():
  104. self.tb.add_scalar(k, v, epoch)
  105. if self.wandb:
  106. self.wandb.log(x)
  107. self.wandb.end_epoch(best_result=best_fitness == fi)
  108. def on_model_save(self, last, epoch, final_epoch, best_fitness, fi):
  109. # Callback runs on model save event
  110. if self.wandb:
  111. if ((epoch + 1) % self.opt.save_period == 0 and not final_epoch) and self.opt.save_period != -1:
  112. self.wandb.log_model(last.parent, self.opt, epoch, fi, best_model=best_fitness == fi)
  113. def on_train_end(self, last, best, plots, epoch, results):
  114. # Callback runs on training end
  115. if plots:
  116. plot_results(file=self.save_dir / 'results.csv') # save results.png
  117. files = ['results.png', 'confusion_matrix.png', *(f'{x}_curve.png' for x in ('F1', 'PR', 'P', 'R'))]
  118. files = [(self.save_dir / f) for f in files if (self.save_dir / f).exists()] # filter
  119. if self.tb:
  120. import cv2
  121. for f in files:
  122. self.tb.add_image(f.stem, cv2.imread(str(f))[..., ::-1], epoch, dataformats='HWC')
  123. if self.wandb:
  124. self.wandb.log({"Results": [wandb.Image(str(f), caption=f.name) for f in files]})
  125. # Calling wandb.log. TODO: Refactor this into WandbLogger.log_model
  126. if not self.opt.evolve:
  127. wandb.log_artifact(str(best if best.exists() else last), type='model',
  128. name='run_' + self.wandb.wandb_run.id + '_model',
  129. aliases=['latest', 'best', 'stripped'])
  130. self.wandb.finish_run()
  131. else:
  132. self.wandb.finish_run()
  133. self.wandb = WandbLogger(self.opt)