validator.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. """
  3. Check a model's accuracy on a test or val split of a dataset.
  4. Usage:
  5. $ yolo mode=val model=yolov8n.pt data=coco8.yaml imgsz=640
  6. Usage - formats:
  7. $ yolo mode=val model=yolov8n.pt # PyTorch
  8. yolov8n.torchscript # TorchScript
  9. yolov8n.onnx # ONNX Runtime or OpenCV DNN with dnn=True
  10. yolov8n_openvino_model # OpenVINO
  11. yolov8n.engine # TensorRT
  12. yolov8n.mlpackage # CoreML (macOS-only)
  13. yolov8n_saved_model # TensorFlow SavedModel
  14. yolov8n.pb # TensorFlow GraphDef
  15. yolov8n.tflite # TensorFlow Lite
  16. yolov8n_edgetpu.tflite # TensorFlow Edge TPU
  17. yolov8n_paddle_model # PaddlePaddle
  18. yolov8n_ncnn_model # NCNN
  19. """
  20. import json
  21. import time
  22. from pathlib import Path
  23. import numpy as np
  24. import torch
  25. from ultralytics.cfg import get_cfg, get_save_dir
  26. from ultralytics.data.utils import check_cls_dataset, check_det_dataset
  27. from ultralytics.nn.autobackend import AutoBackend
  28. from ultralytics.utils import LOGGER, TQDM, callbacks, colorstr, emojis
  29. from ultralytics.utils.checks import check_imgsz
  30. from ultralytics.utils.ops import Profile
  31. from ultralytics.utils.torch_utils import de_parallel, select_device, smart_inference_mode
  32. class BaseValidator:
  33. """
  34. BaseValidator.
  35. A base class for creating validators.
  36. Attributes:
  37. args (SimpleNamespace): Configuration for the validator.
  38. dataloader (DataLoader): Dataloader to use for validation.
  39. pbar (tqdm): Progress bar to update during validation.
  40. model (nn.Module): Model to validate.
  41. data (dict): Data dictionary.
  42. device (torch.device): Device to use for validation.
  43. batch_i (int): Current batch index.
  44. training (bool): Whether the model is in training mode.
  45. names (dict): Class names.
  46. seen: Records the number of images seen so far during validation.
  47. stats: Placeholder for statistics during validation.
  48. confusion_matrix: Placeholder for a confusion matrix.
  49. nc: Number of classes.
  50. iouv: (torch.Tensor): IoU thresholds from 0.50 to 0.95 in spaces of 0.05.
  51. jdict (dict): Dictionary to store JSON validation results.
  52. speed (dict): Dictionary with keys 'preprocess', 'inference', 'loss', 'postprocess' and their respective
  53. batch processing times in milliseconds.
  54. save_dir (Path): Directory to save results.
  55. plots (dict): Dictionary to store plots for visualization.
  56. callbacks (dict): Dictionary to store various callback functions.
  57. """
  58. def __init__(self, dataloader=None, save_dir=None, pbar=None, args=None, _callbacks=None):
  59. """
  60. Initializes a BaseValidator instance.
  61. Args:
  62. dataloader (torch.utils.data.DataLoader): Dataloader to be used for validation.
  63. save_dir (Path, optional): Directory to save results.
  64. pbar (tqdm.tqdm): Progress bar for displaying progress.
  65. args (SimpleNamespace): Configuration for the validator.
  66. _callbacks (dict): Dictionary to store various callback functions.
  67. """
  68. self.args = get_cfg(overrides=args)
  69. self.dataloader = dataloader
  70. self.pbar = pbar
  71. self.stride = None
  72. self.data = None
  73. self.device = None
  74. self.batch_i = None
  75. self.training = True
  76. self.names = None
  77. self.seen = None
  78. self.stats = None
  79. self.confusion_matrix = None
  80. self.nc = None
  81. self.iouv = None
  82. self.jdict = None
  83. self.speed = {"preprocess": 0.0, "inference": 0.0, "loss": 0.0, "postprocess": 0.0}
  84. self.save_dir = save_dir or get_save_dir(self.args)
  85. (self.save_dir / "labels" if self.args.save_txt else self.save_dir).mkdir(parents=True, exist_ok=True)
  86. if self.args.conf is None:
  87. self.args.conf = 0.001 # default conf=0.001
  88. self.args.imgsz = check_imgsz(self.args.imgsz, max_dim=1)
  89. self.plots = {}
  90. self.callbacks = _callbacks or callbacks.get_default_callbacks()
  91. @smart_inference_mode()
  92. def __call__(self, trainer=None, model=None):
  93. """Supports validation of a pre-trained model if passed or a model being trained if trainer is passed (trainer
  94. gets priority).
  95. """
  96. self.training = trainer is not None
  97. augment = self.args.augment and (not self.training)
  98. if self.training:
  99. self.device = trainer.device
  100. self.data = trainer.data
  101. self.args.half = self.device.type != "cpu" # force FP16 val during training
  102. # self.args.half = False # force FP16 val during training
  103. model = trainer.ema.ema or trainer.model
  104. model = model.half() if self.args.half else model.float()
  105. # self.model = model
  106. self.loss = torch.zeros_like(trainer.loss_items, device=trainer.device)
  107. self.args.plots &= trainer.stopper.possible_stop or (trainer.epoch == trainer.epochs - 1)
  108. model.eval()
  109. else:
  110. callbacks.add_integration_callbacks(self)
  111. model = AutoBackend(
  112. weights=model or self.args.model,
  113. device=select_device(self.args.device, self.args.batch),
  114. dnn=self.args.dnn,
  115. data=self.args.data,
  116. fp16=self.args.half,
  117. )
  118. # self.model = model
  119. self.device = model.device # update device
  120. self.args.half = model.fp16 # update half
  121. stride, pt, jit, engine = model.stride, model.pt, model.jit, model.engine
  122. imgsz = check_imgsz(self.args.imgsz, stride=stride)
  123. if engine:
  124. self.args.batch = model.batch_size
  125. elif not pt and not jit:
  126. self.args.batch = 1 # export.py models default to batch-size 1
  127. LOGGER.info(f"Forcing batch=1 square inference (1,3,{imgsz},{imgsz}) for non-PyTorch models")
  128. if str(self.args.data).split(".")[-1] in {"yaml", "yml"}:
  129. self.data = check_det_dataset(self.args.data, self.args.is_train_on_platform)
  130. elif self.args.task == "classify":
  131. self.data = check_cls_dataset(self.args.data, split=self.args.split)
  132. else:
  133. raise FileNotFoundError(emojis(f"Dataset '{self.args.data}' for task={self.args.task} not found ❌"))
  134. if self.device.type in {"cpu", "mps"}:
  135. self.args.workers = 0 # faster CPU val as time dominated by inference, not dataloading
  136. if not pt:
  137. self.args.rect = False
  138. self.stride = model.stride # used in get_dataloader() for padding
  139. self.dataloader = self.dataloader or self.get_dataloader(self.data.get(self.args.split), self.args.batch)
  140. model.eval()
  141. model.warmup(imgsz=(1 if pt else self.args.batch, 3, imgsz, imgsz)) # warmup
  142. self.run_callbacks("on_val_start")
  143. dt = (
  144. Profile(device=self.device),
  145. Profile(device=self.device),
  146. Profile(device=self.device),
  147. Profile(device=self.device),
  148. )
  149. bar = TQDM(self.dataloader, desc=self.get_desc(), total=len(self.dataloader))
  150. self.init_metrics(de_parallel(model))
  151. self.jdict = [] # empty before each val
  152. for batch_i, batch in enumerate(bar):
  153. self.run_callbacks("on_val_batch_start")
  154. self.batch_i = batch_i
  155. # Preprocess
  156. with dt[0]:
  157. batch = self.preprocess(batch)
  158. # Inference
  159. with dt[1]:
  160. preds = model(batch["img"], augment=augment)
  161. # Loss
  162. with dt[2]:
  163. if self.training:
  164. self.loss += model.loss(batch, preds)[1]
  165. # Postprocess
  166. with dt[3]:
  167. preds = self.postprocess(preds)
  168. self.update_metrics(preds, batch)
  169. if self.args.plots and batch_i < 3:
  170. self.plot_val_samples(batch, batch_i)
  171. self.plot_predictions(batch, preds, batch_i)
  172. self.run_callbacks("on_val_batch_end")
  173. stats = self.get_stats()
  174. self.check_stats(stats)
  175. self.speed = dict(zip(self.speed.keys(), (x.t / len(self.dataloader.dataset) * 1e3 for x in dt)))
  176. self.finalize_metrics()
  177. self.print_results()
  178. self.run_callbacks("on_val_end")
  179. if self.training:
  180. model.float()
  181. results = {**stats, **trainer.label_loss_items(self.loss.cpu() / len(self.dataloader), prefix="val")}
  182. return {k: round(float(v), 5) for k, v in results.items()} # return results as 5 decimal place floats
  183. else:
  184. LOGGER.info(
  185. "Speed: %.1fms preprocess, %.1fms inference, %.1fms loss, %.1fms postprocess per image"
  186. % tuple(self.speed.values())
  187. )
  188. if self.args.save_json and self.jdict:
  189. with open(str(self.save_dir / "predictions.json"), "w") as f:
  190. LOGGER.info(f"Saving {f.name}...")
  191. json.dump(self.jdict, f) # flatten and save
  192. stats = self.eval_json(stats) # update stats
  193. if self.args.plots or self.args.save_json:
  194. LOGGER.info(f"Results saved to {colorstr('bold', self.save_dir)}")
  195. return stats
  196. def match_predictions(self, pred_classes, true_classes, iou, use_scipy=False):
  197. """
  198. Matches predictions to ground truth objects (pred_classes, true_classes) using IoU.
  199. Args:
  200. pred_classes (torch.Tensor): Predicted class indices of shape(N,).
  201. true_classes (torch.Tensor): Target class indices of shape(M,).
  202. iou (torch.Tensor): An NxM tensor containing the pairwise IoU values for predictions and ground of truth
  203. use_scipy (bool): Whether to use scipy for matching (more precise).
  204. Returns:
  205. (torch.Tensor): Correct tensor of shape(N,10) for 10 IoU thresholds.
  206. """
  207. # Dx10 matrix, where D - detections, 10 - IoU thresholds
  208. correct = np.zeros((pred_classes.shape[0], self.iouv.shape[0])).astype(bool)
  209. # LxD matrix where L - labels (rows), D - detections (columns)
  210. correct_class = true_classes[:, None] == pred_classes
  211. iou = iou * correct_class # zero out the wrong classes
  212. iou = iou.cpu().numpy()
  213. for i, threshold in enumerate(self.iouv.cpu().tolist()):
  214. if use_scipy:
  215. # WARNING: known issue that reduces mAP in https://github.com/ultralytics/ultralytics/pull/4708
  216. import scipy # scope import to avoid importing for all commands
  217. cost_matrix = iou * (iou >= threshold)
  218. if cost_matrix.any():
  219. labels_idx, detections_idx = scipy.optimize.linear_sum_assignment(cost_matrix, maximize=True)
  220. valid = cost_matrix[labels_idx, detections_idx] > 0
  221. if valid.any():
  222. correct[detections_idx[valid], i] = True
  223. else:
  224. matches = np.nonzero(iou >= threshold) # IoU > threshold and classes match
  225. matches = np.array(matches).T
  226. if matches.shape[0]:
  227. if matches.shape[0] > 1:
  228. matches = matches[iou[matches[:, 0], matches[:, 1]].argsort()[::-1]]
  229. matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
  230. # matches = matches[matches[:, 2].argsort()[::-1]]
  231. matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
  232. correct[matches[:, 1].astype(int), i] = True
  233. return torch.tensor(correct, dtype=torch.bool, device=pred_classes.device)
  234. def add_callback(self, event: str, callback):
  235. """Appends the given callback."""
  236. self.callbacks[event].append(callback)
  237. def run_callbacks(self, event: str):
  238. """Runs all callbacks associated with a specified event."""
  239. for callback in self.callbacks.get(event, []):
  240. callback(self)
  241. def get_dataloader(self, dataset_path, batch_size):
  242. """Get data loader from dataset path and batch size."""
  243. raise NotImplementedError("get_dataloader function not implemented for this validator")
  244. def build_dataset(self, img_path):
  245. """Build dataset."""
  246. raise NotImplementedError("build_dataset function not implemented in validator")
  247. def preprocess(self, batch):
  248. """Preprocesses an input batch."""
  249. return batch
  250. def postprocess(self, preds):
  251. """Describes and summarizes the purpose of 'postprocess()' but no details mentioned."""
  252. return preds
  253. def init_metrics(self, model):
  254. """Initialize performance metrics for the YOLO model."""
  255. pass
  256. def update_metrics(self, preds, batch):
  257. """Updates metrics based on predictions and batch."""
  258. pass
  259. def finalize_metrics(self, *args, **kwargs):
  260. """Finalizes and returns all metrics."""
  261. pass
  262. def get_stats(self):
  263. """Returns statistics about the model's performance."""
  264. return {}
  265. def check_stats(self, stats):
  266. """Checks statistics."""
  267. pass
  268. def print_results(self):
  269. """Prints the results of the model's predictions."""
  270. pass
  271. def get_desc(self):
  272. """Get description of the YOLO model."""
  273. pass
  274. @property
  275. def metric_keys(self):
  276. """Returns the metric keys used in YOLO training/validation."""
  277. return []
  278. def on_plot(self, name, data=None):
  279. """Registers plots (e.g. to be consumed in callbacks)"""
  280. self.plots[Path(name)] = {"data": data, "timestamp": time.time()}
  281. # TODO: may need to put these following functions into callback
  282. def plot_val_samples(self, batch, ni):
  283. """Plots validation samples during training."""
  284. pass
  285. def plot_predictions(self, batch, preds, ni):
  286. """Plots YOLO model predictions on batch images."""
  287. pass
  288. def pred_to_json(self, preds, batch):
  289. """Convert predictions to JSON format."""
  290. pass
  291. def eval_json(self, stats):
  292. """Evaluate and return JSON format of prediction statistics."""
  293. pass