val.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. import os
  3. from pathlib import Path
  4. import numpy as np
  5. import torch
  6. from ultralytics.data import build_dataloader, build_yolo_dataset, converter
  7. from ultralytics.engine.validator import BaseValidator
  8. from ultralytics.utils import LOGGER, ops
  9. from ultralytics.utils.checks import check_requirements
  10. from ultralytics.utils.metrics import ConfusionMatrix, DetMetrics, box_iou
  11. from ultralytics.utils.plotting import output_to_target, plot_images
  12. from ultralytics.utils.torch_utils import de_parallel
  13. class DetectionValidator(BaseValidator):
  14. """
  15. A class extending the BaseValidator class for validation based on a detection model.
  16. Example:
  17. ```python
  18. from ultralytics.models.yolo.detect import DetectionValidator
  19. args = dict(model='yolov8n.pt', data='coco8.yaml')
  20. validator = DetectionValidator(args=args)
  21. validator()
  22. ```
  23. """
  24. def __init__(self, dataloader=None, save_dir=None, pbar=None, args=None, _callbacks=None):
  25. """Initialize detection model with necessary variables and settings."""
  26. super().__init__(dataloader, save_dir, pbar, args, _callbacks)
  27. self.nt_per_class = None
  28. self.is_coco = False
  29. self.class_map = None
  30. self.args.task = 'detect'
  31. self.metrics = DetMetrics(save_dir=self.save_dir, on_plot=self.on_plot)
  32. self.iouv = torch.linspace(0.5, 0.95, 10) # iou vector for mAP@0.5:0.95
  33. self.niou = self.iouv.numel()
  34. self.lb = [] # for autolabelling
  35. def preprocess(self, batch):
  36. """Preprocesses batch of images for YOLO training."""
  37. batch['img'] = batch['img'].to(self.device, non_blocking=True)
  38. batch['img'] = (batch['img'].half() if self.args.half else batch['img'].float()) / 255
  39. for k in ['batch_idx', 'cls', 'bboxes']:
  40. batch[k] = batch[k].to(self.device)
  41. if self.args.save_hybrid:
  42. height, width = batch['img'].shape[2:]
  43. nb = len(batch['img'])
  44. bboxes = batch['bboxes'] * torch.tensor((width, height, width, height), device=self.device)
  45. self.lb = [
  46. torch.cat([batch['cls'][batch['batch_idx'] == i], bboxes[batch['batch_idx'] == i]], dim=-1)
  47. for i in range(nb)] if self.args.save_hybrid else [] # for autolabelling
  48. return batch
  49. def init_metrics(self, model):
  50. """Initialize evaluation metrics for YOLO."""
  51. val = self.data.get(self.args.split, '') # validation path
  52. self.is_coco = isinstance(val, str) and 'coco' in val and val.endswith(f'{os.sep}val2017.txt') # is COCO
  53. self.class_map = converter.coco80_to_coco91_class() if self.is_coco else list(range(1000))
  54. self.args.save_json |= self.is_coco and not self.training # run on final val if training COCO
  55. self.names = model.names
  56. self.nc = len(model.names)
  57. self.metrics.names = self.names
  58. self.metrics.plot = self.args.plots
  59. self.confusion_matrix = ConfusionMatrix(nc=self.nc)
  60. self.seen = 0
  61. self.jdict = []
  62. self.stats = []
  63. def get_desc(self):
  64. """Return a formatted string summarizing class metrics of YOLO model."""
  65. return ('%22s' + '%11s' * 6) % ('Class', 'Images', 'Instances', 'Box(P', 'R', 'mAP50', 'mAP50-95)')
  66. def postprocess(self, preds):
  67. """Apply Non-maximum suppression to prediction outputs."""
  68. return ops.non_max_suppression(preds,
  69. self.args.conf,
  70. self.args.iou,
  71. labels=self.lb,
  72. multi_label=True,
  73. agnostic=self.args.single_cls,
  74. max_det=self.args.max_det)
  75. def update_metrics(self, preds, batch):
  76. """Metrics."""
  77. for si, pred in enumerate(preds):
  78. idx = batch['batch_idx'] == si
  79. cls = batch['cls'][idx]
  80. bbox = batch['bboxes'][idx]
  81. nl, npr = cls.shape[0], pred.shape[0] # number of labels, predictions
  82. shape = batch['ori_shape'][si]
  83. correct_bboxes = torch.zeros(npr, self.niou, dtype=torch.bool, device=self.device) # init
  84. self.seen += 1
  85. if npr == 0:
  86. if nl:
  87. self.stats.append((correct_bboxes, *torch.zeros((2, 0), device=self.device), cls.squeeze(-1)))
  88. if self.args.plots:
  89. self.confusion_matrix.process_batch(detections=None, labels=cls.squeeze(-1))
  90. continue
  91. # Predictions
  92. if self.args.single_cls:
  93. pred[:, 5] = 0
  94. predn = pred.clone()
  95. ops.scale_boxes(batch['img'][si].shape[1:], predn[:, :4], shape,
  96. ratio_pad=batch['ratio_pad'][si]) # native-space pred
  97. # Evaluate
  98. if nl:
  99. height, width = batch['img'].shape[2:]
  100. tbox = ops.xywh2xyxy(bbox) * torch.tensor(
  101. (width, height, width, height), device=self.device) # target boxes
  102. ops.scale_boxes(batch['img'][si].shape[1:], tbox, shape,
  103. ratio_pad=batch['ratio_pad'][si]) # native-space labels
  104. labelsn = torch.cat((cls, tbox), 1) # native-space labels
  105. correct_bboxes = self._process_batch(predn, labelsn)
  106. # TODO: maybe remove these `self.` arguments as they already are member variable
  107. if self.args.plots:
  108. self.confusion_matrix.process_batch(predn, labelsn)
  109. self.stats.append((correct_bboxes, pred[:, 4], pred[:, 5], cls.squeeze(-1))) # (conf, pcls, tcls)
  110. # Save
  111. if self.args.save_json:
  112. self.pred_to_json(predn, batch['im_file'][si])
  113. if self.args.save_txt:
  114. file = self.save_dir / 'labels' / f'{Path(batch["im_file"][si]).stem}.txt'
  115. self.save_one_txt(predn, self.args.save_conf, shape, file)
  116. def finalize_metrics(self, *args, **kwargs):
  117. """Set final values for metrics speed and confusion matrix."""
  118. self.metrics.speed = self.speed
  119. self.metrics.confusion_matrix = self.confusion_matrix
  120. def get_stats(self):
  121. """Returns metrics statistics and results dictionary."""
  122. stats = [torch.cat(x, 0).cpu().numpy() for x in zip(*self.stats)] # to numpy
  123. if len(stats) and stats[0].any():
  124. self.metrics.process(*stats)
  125. self.nt_per_class = np.bincount(stats[-1].astype(int), minlength=self.nc) # number of targets per class
  126. return self.metrics.results_dict
  127. def print_results(self):
  128. """Prints training/validation set metrics per class."""
  129. pf = '%22s' + '%11i' * 2 + '%11.3g' * len(self.metrics.keys) # print format
  130. LOGGER.info(pf % ('all', self.seen, self.nt_per_class.sum(), *self.metrics.mean_results()))
  131. if self.nt_per_class.sum() == 0:
  132. LOGGER.warning(
  133. f'WARNING ⚠️ no labels found in {self.args.task} set, can not compute metrics without labels')
  134. # Print results per class
  135. if self.args.verbose and not self.training and self.nc > 1 and len(self.stats):
  136. for i, c in enumerate(self.metrics.ap_class_index):
  137. LOGGER.info(pf % (self.names[c], self.seen, self.nt_per_class[c], *self.metrics.class_result(i)))
  138. if self.args.plots:
  139. for normalize in True, False:
  140. self.confusion_matrix.plot(save_dir=self.save_dir,
  141. names=self.names.values(),
  142. normalize=normalize,
  143. on_plot=self.on_plot)
  144. def _process_batch(self, detections, labels):
  145. """
  146. Return correct prediction matrix.
  147. Args:
  148. detections (torch.Tensor): Tensor of shape [N, 6] representing detections.
  149. Each detection is of the format: x1, y1, x2, y2, conf, class.
  150. labels (torch.Tensor): Tensor of shape [M, 5] representing labels.
  151. Each label is of the format: class, x1, y1, x2, y2.
  152. Returns:
  153. (torch.Tensor): Correct prediction matrix of shape [N, 10] for 10 IoU levels.
  154. """
  155. iou = box_iou(labels[:, 1:], detections[:, :4])
  156. return self.match_predictions(detections[:, 5], labels[:, 0], iou)
  157. def build_dataset(self, img_path, mode='val', batch=None):
  158. """
  159. Build YOLO Dataset.
  160. Args:
  161. img_path (str): Path to the folder containing images.
  162. mode (str): `train` mode or `val` mode, users are able to customize different augmentations for each mode.
  163. batch (int, optional): Size of batches, this is for `rect`. Defaults to None.
  164. """
  165. gs = max(int(de_parallel(self.model).stride if self.model else 0), 32)
  166. return build_yolo_dataset(self.args, img_path, batch, self.data, mode=mode, stride=gs)
  167. def get_dataloader(self, dataset_path, batch_size):
  168. """Construct and return dataloader."""
  169. dataset = self.build_dataset(dataset_path, batch=batch_size, mode='val')
  170. return build_dataloader(dataset, batch_size, self.args.workers, shuffle=False, rank=-1) # return dataloader
  171. def plot_val_samples(self, batch, ni):
  172. """Plot validation image samples."""
  173. plot_images(batch['img'],
  174. batch['batch_idx'],
  175. batch['cls'].squeeze(-1),
  176. batch['bboxes'],
  177. paths=batch['im_file'],
  178. fname=self.save_dir / f'val_batch{ni}_labels.jpg',
  179. names=self.names,
  180. on_plot=self.on_plot)
  181. def plot_predictions(self, batch, preds, ni):
  182. """Plots predicted bounding boxes on input images and saves the result."""
  183. plot_images(batch['img'],
  184. *output_to_target(preds, max_det=self.args.max_det),
  185. paths=batch['im_file'],
  186. fname=self.save_dir / f'val_batch{ni}_pred.jpg',
  187. names=self.names,
  188. on_plot=self.on_plot) # pred
  189. def save_one_txt(self, predn, save_conf, shape, file):
  190. """Save YOLO detections to a txt file in normalized coordinates in a specific format."""
  191. gn = torch.tensor(shape)[[1, 0, 1, 0]] # normalization gain whwh
  192. for *xyxy, conf, cls in predn.tolist():
  193. xywh = (ops.xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
  194. line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
  195. with open(file, 'a') as f:
  196. f.write(('%g ' * len(line)).rstrip() % line + '\n')
  197. def pred_to_json(self, predn, filename):
  198. """Serialize YOLO predictions to COCO json format."""
  199. stem = Path(filename).stem
  200. image_id = int(stem) if stem.isnumeric() else stem
  201. box = ops.xyxy2xywh(predn[:, :4]) # xywh
  202. box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner
  203. for p, b in zip(predn.tolist(), box.tolist()):
  204. self.jdict.append({
  205. 'image_id': image_id,
  206. 'category_id': self.class_map[int(p[5])],
  207. 'bbox': [round(x, 3) for x in b],
  208. 'score': round(p[4], 5)})
  209. def eval_json(self, stats):
  210. """Evaluates YOLO output in JSON format and returns performance statistics."""
  211. if self.args.save_json and self.is_coco and len(self.jdict):
  212. anno_json = self.data['path'] / 'annotations/instances_val2017.json' # annotations
  213. pred_json = self.save_dir / 'predictions.json' # predictions
  214. LOGGER.info(f'\nEvaluating pycocotools mAP using {pred_json} and {anno_json}...')
  215. try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb
  216. check_requirements('pycocotools>=2.0.6')
  217. from pycocotools.coco import COCO # noqa
  218. from pycocotools.cocoeval import COCOeval # noqa
  219. for x in anno_json, pred_json:
  220. assert x.is_file(), f'{x} file not found'
  221. anno = COCO(str(anno_json)) # init annotations api
  222. pred = anno.loadRes(str(pred_json)) # init predictions api (must pass string, not Path)
  223. eval = COCOeval(anno, pred, 'bbox')
  224. if self.is_coco:
  225. eval.params.imgIds = [int(Path(x).stem) for x in self.dataloader.dataset.im_files] # images to eval
  226. eval.evaluate()
  227. eval.accumulate()
  228. eval.summarize()
  229. stats[self.metrics.keys[-1]], stats[self.metrics.keys[-2]] = eval.stats[:2] # update mAP50-95 and mAP50
  230. except Exception as e:
  231. LOGGER.warning(f'pycocotools unable to run: {e}')
  232. return stats