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.

352 lines
16KB

  1. """Validate a trained YOLOv5 model accuracy on a custom dataset
  2. Usage:
  3. $ python path/to/val.py --data coco128.yaml --weights yolov5s.pt --img 640
  4. """
  5. import argparse
  6. import json
  7. import os
  8. import sys
  9. from pathlib import Path
  10. from threading import Thread
  11. import numpy as np
  12. import torch
  13. from tqdm import tqdm
  14. FILE = Path(__file__).absolute()
  15. sys.path.append(FILE.parents[0].as_posix()) # add yolov5/ to path
  16. from models.experimental import attempt_load
  17. from utils.datasets import create_dataloader
  18. from utils.general import coco80_to_coco91_class, check_dataset, check_file, check_img_size, check_requirements, \
  19. box_iou, non_max_suppression, scale_coords, xyxy2xywh, xywh2xyxy, set_logging, increment_path, colorstr
  20. from utils.metrics import ap_per_class, ConfusionMatrix
  21. from utils.plots import plot_images, output_to_target, plot_study_txt
  22. from utils.torch_utils import select_device, time_sync
  23. from utils.loggers import Loggers
  24. def save_one_txt(predn, save_conf, shape, file):
  25. # Save one txt result
  26. gn = torch.tensor(shape)[[1, 0, 1, 0]] # normalization gain whwh
  27. for *xyxy, conf, cls in predn.tolist():
  28. xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
  29. line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
  30. with open(file, 'a') as f:
  31. f.write(('%g ' * len(line)).rstrip() % line + '\n')
  32. def save_one_json(predn, jdict, path, class_map):
  33. # Save one JSON result {"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236}
  34. image_id = int(path.stem) if path.stem.isnumeric() else path.stem
  35. box = xyxy2xywh(predn[:, :4]) # xywh
  36. box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner
  37. for p, b in zip(predn.tolist(), box.tolist()):
  38. jdict.append({'image_id': image_id,
  39. 'category_id': class_map[int(p[5])],
  40. 'bbox': [round(x, 3) for x in b],
  41. 'score': round(p[4], 5)})
  42. def process_batch(predictions, labels, iouv):
  43. # Evaluate 1 batch of predictions
  44. correct = torch.zeros(predictions.shape[0], len(iouv), dtype=torch.bool, device=iouv.device)
  45. detected = [] # label indices
  46. tcls, pcls = labels[:, 0], predictions[:, 5]
  47. nl = labels.shape[0] # number of labels
  48. for cls in torch.unique(tcls):
  49. ti = (cls == tcls).nonzero().view(-1) # label indices
  50. pi = (cls == pcls).nonzero().view(-1) # prediction indices
  51. if pi.shape[0]: # find detections
  52. ious, i = box_iou(predictions[pi, 0:4], labels[ti, 1:5]).max(1) # best ious, indices
  53. detected_set = set()
  54. for j in (ious > iouv[0]).nonzero():
  55. d = ti[i[j]] # detected label
  56. if d.item() not in detected_set:
  57. detected_set.add(d.item())
  58. detected.append(d) # append detections
  59. correct[pi[j]] = ious[j] > iouv # iou_thres is 1xn
  60. if len(detected) == nl: # all labels already located in image
  61. break
  62. return correct
  63. @torch.no_grad()
  64. def run(data,
  65. weights=None, # model.pt path(s)
  66. batch_size=32, # batch size
  67. imgsz=640, # inference size (pixels)
  68. conf_thres=0.001, # confidence threshold
  69. iou_thres=0.6, # NMS IoU threshold
  70. task='val', # train, val, test, speed or study
  71. device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
  72. single_cls=False, # treat as single-class dataset
  73. augment=False, # augmented inference
  74. verbose=False, # verbose output
  75. save_txt=False, # save results to *.txt
  76. save_hybrid=False, # save label+prediction hybrid results to *.txt
  77. save_conf=False, # save confidences in --save-txt labels
  78. save_json=False, # save a COCO-JSON results file
  79. project='runs/val', # save to project/name
  80. name='exp', # save to project/name
  81. exist_ok=False, # existing project/name ok, do not increment
  82. half=True, # use FP16 half-precision inference
  83. model=None,
  84. dataloader=None,
  85. save_dir=Path(''),
  86. plots=True,
  87. loggers=Loggers(),
  88. compute_loss=None,
  89. ):
  90. # Initialize/load model and set device
  91. training = model is not None
  92. if training: # called by train.py
  93. device = next(model.parameters()).device # get model device
  94. else: # called directly
  95. device = select_device(device, batch_size=batch_size)
  96. # Directories
  97. save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
  98. (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
  99. # Load model
  100. model = attempt_load(weights, map_location=device) # load FP32 model
  101. gs = max(int(model.stride.max()), 32) # grid size (max stride)
  102. imgsz = check_img_size(imgsz, s=gs) # check image size
  103. # Multi-GPU disabled, incompatible with .half() https://github.com/ultralytics/yolov5/issues/99
  104. # if device.type != 'cpu' and torch.cuda.device_count() > 1:
  105. # model = nn.DataParallel(model)
  106. # Data
  107. data = check_dataset(data) # check
  108. # Half
  109. half &= device.type != 'cpu' # half precision only supported on CUDA
  110. if half:
  111. model.half()
  112. # Configure
  113. model.eval()
  114. is_coco = type(data['val']) is str and data['val'].endswith('coco/val2017.txt') # COCO dataset
  115. nc = 1 if single_cls else int(data['nc']) # number of classes
  116. iouv = torch.linspace(0.5, 0.95, 10).to(device) # iou vector for mAP@0.5:0.95
  117. niou = iouv.numel()
  118. # Dataloader
  119. if not training:
  120. if device.type != 'cpu':
  121. model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
  122. task = task if task in ('train', 'val', 'test') else 'val' # path to train/val/test images
  123. dataloader = create_dataloader(data[task], imgsz, batch_size, gs, single_cls, pad=0.5, rect=True,
  124. prefix=colorstr(f'{task}: '))[0]
  125. seen = 0
  126. confusion_matrix = ConfusionMatrix(nc=nc)
  127. names = {k: v for k, v in enumerate(model.names if hasattr(model, 'names') else model.module.names)}
  128. class_map = coco80_to_coco91_class() if is_coco else list(range(1000))
  129. s = ('%20s' + '%11s' * 6) % ('Class', 'Images', 'Labels', 'P', 'R', 'mAP@.5', 'mAP@.5:.95')
  130. p, r, f1, mp, mr, map50, map, t0, t1, t2 = 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.
  131. loss = torch.zeros(3, device=device)
  132. jdict, stats, ap, ap_class = [], [], [], []
  133. for batch_i, (img, targets, paths, shapes) in enumerate(tqdm(dataloader, desc=s)):
  134. t_ = time_sync()
  135. img = img.to(device, non_blocking=True)
  136. img = img.half() if half else img.float() # uint8 to fp16/32
  137. img /= 255.0 # 0 - 255 to 0.0 - 1.0
  138. targets = targets.to(device)
  139. nb, _, height, width = img.shape # batch size, channels, height, width
  140. t = time_sync()
  141. t0 += t - t_
  142. # Run model
  143. out, train_out = model(img, augment=augment) # inference and training outputs
  144. t1 += time_sync() - t
  145. # Compute loss
  146. if compute_loss:
  147. loss += compute_loss([x.float() for x in train_out], targets)[1] # box, obj, cls
  148. # Run NMS
  149. targets[:, 2:] *= torch.Tensor([width, height, width, height]).to(device) # to pixels
  150. lb = [targets[targets[:, 0] == i, 1:] for i in range(nb)] if save_hybrid else [] # for autolabelling
  151. t = time_sync()
  152. out = non_max_suppression(out, conf_thres, iou_thres, labels=lb, multi_label=True, agnostic=single_cls)
  153. t2 += time_sync() - t
  154. # Statistics per image
  155. for si, pred in enumerate(out):
  156. labels = targets[targets[:, 0] == si, 1:]
  157. nl = len(labels)
  158. tcls = labels[:, 0].tolist() if nl else [] # target class
  159. path, shape = Path(paths[si]), shapes[si][0]
  160. seen += 1
  161. if len(pred) == 0:
  162. if nl:
  163. stats.append((torch.zeros(0, niou, dtype=torch.bool), torch.Tensor(), torch.Tensor(), tcls))
  164. continue
  165. # Predictions
  166. if single_cls:
  167. pred[:, 5] = 0
  168. predn = pred.clone()
  169. scale_coords(img[si].shape[1:], predn[:, :4], shape, shapes[si][1]) # native-space pred
  170. # Evaluate
  171. if nl:
  172. tbox = xywh2xyxy(labels[:, 1:5]) # target boxes
  173. scale_coords(img[si].shape[1:], tbox, shape, shapes[si][1]) # native-space labels
  174. labelsn = torch.cat((labels[:, 0:1], tbox), 1) # native-space labels
  175. correct = process_batch(predn, labelsn, iouv)
  176. if plots:
  177. confusion_matrix.process_batch(predn, labelsn)
  178. else:
  179. correct = torch.zeros(pred.shape[0], niou, dtype=torch.bool)
  180. stats.append((correct.cpu(), pred[:, 4].cpu(), pred[:, 5].cpu(), tcls)) # (correct, conf, pcls, tcls)
  181. # Save/log
  182. if save_txt:
  183. save_one_txt(predn, save_conf, shape, file=save_dir / 'labels' / (path.stem + '.txt'))
  184. if save_json:
  185. save_one_json(predn, jdict, path, class_map) # append to COCO-JSON dictionary
  186. loggers.on_val_batch_end(pred, predn, path, names, img[si])
  187. # Plot images
  188. if plots and batch_i < 3:
  189. f = save_dir / f'val_batch{batch_i}_labels.jpg' # labels
  190. Thread(target=plot_images, args=(img, targets, paths, f, names), daemon=True).start()
  191. f = save_dir / f'val_batch{batch_i}_pred.jpg' # predictions
  192. Thread(target=plot_images, args=(img, output_to_target(out), paths, f, names), daemon=True).start()
  193. # Compute statistics
  194. stats = [np.concatenate(x, 0) for x in zip(*stats)] # to numpy
  195. if len(stats) and stats[0].any():
  196. p, r, ap, f1, ap_class = ap_per_class(*stats, plot=plots, save_dir=save_dir, names=names)
  197. ap50, ap = ap[:, 0], ap.mean(1) # AP@0.5, AP@0.5:0.95
  198. mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean()
  199. nt = np.bincount(stats[3].astype(np.int64), minlength=nc) # number of targets per class
  200. else:
  201. nt = torch.zeros(1)
  202. # Print results
  203. pf = '%20s' + '%11i' * 2 + '%11.3g' * 4 # print format
  204. print(pf % ('all', seen, nt.sum(), mp, mr, map50, map))
  205. # Print results per class
  206. if (verbose or (nc < 50 and not training)) and nc > 1 and len(stats):
  207. for i, c in enumerate(ap_class):
  208. print(pf % (names[c], seen, nt[c], p[i], r[i], ap50[i], ap[i]))
  209. # Print speeds
  210. t = tuple(x / seen * 1E3 for x in (t0, t1, t2)) # speeds per image
  211. if not training:
  212. shape = (batch_size, 3, imgsz, imgsz)
  213. print(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {shape}' % t)
  214. # Plots
  215. if plots:
  216. confusion_matrix.plot(save_dir=save_dir, names=list(names.values()))
  217. loggers.on_val_end()
  218. # Save JSON
  219. if save_json and len(jdict):
  220. w = Path(weights[0] if isinstance(weights, list) else weights).stem if weights is not None else '' # weights
  221. anno_json = str(Path(data.get('path', '../coco')) / 'annotations/instances_val2017.json') # annotations json
  222. pred_json = str(save_dir / f"{w}_predictions.json") # predictions json
  223. print(f'\nEvaluating pycocotools mAP... saving {pred_json}...')
  224. with open(pred_json, 'w') as f:
  225. json.dump(jdict, f)
  226. try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb
  227. check_requirements(['pycocotools'])
  228. from pycocotools.coco import COCO
  229. from pycocotools.cocoeval import COCOeval
  230. anno = COCO(anno_json) # init annotations api
  231. pred = anno.loadRes(pred_json) # init predictions api
  232. eval = COCOeval(anno, pred, 'bbox')
  233. if is_coco:
  234. eval.params.imgIds = [int(Path(x).stem) for x in dataloader.dataset.img_files] # image IDs to evaluate
  235. eval.evaluate()
  236. eval.accumulate()
  237. eval.summarize()
  238. map, map50 = eval.stats[:2] # update results (mAP@0.5:0.95, mAP@0.5)
  239. except Exception as e:
  240. print(f'pycocotools unable to run: {e}')
  241. # Return results
  242. model.float() # for training
  243. if not training:
  244. s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
  245. print(f"Results saved to {save_dir}{s}")
  246. maps = np.zeros(nc) + map
  247. for i, c in enumerate(ap_class):
  248. maps[c] = ap[i]
  249. return (mp, mr, map50, map, *(loss.cpu() / len(dataloader)).tolist()), maps, t
  250. def parse_opt():
  251. parser = argparse.ArgumentParser(prog='val.py')
  252. parser.add_argument('--data', type=str, default='data/coco128.yaml', help='dataset.yaml path')
  253. parser.add_argument('--weights', nargs='+', type=str, default='yolov5s.pt', help='model.pt path(s)')
  254. parser.add_argument('--batch-size', type=int, default=32, help='batch size')
  255. parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)')
  256. parser.add_argument('--conf-thres', type=float, default=0.001, help='confidence threshold')
  257. parser.add_argument('--iou-thres', type=float, default=0.6, help='NMS IoU threshold')
  258. parser.add_argument('--task', default='val', help='train, val, test, speed or study')
  259. parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  260. parser.add_argument('--single-cls', action='store_true', help='treat as single-class dataset')
  261. parser.add_argument('--augment', action='store_true', help='augmented inference')
  262. parser.add_argument('--verbose', action='store_true', help='report mAP by class')
  263. parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
  264. parser.add_argument('--save-hybrid', action='store_true', help='save label+prediction hybrid results to *.txt')
  265. parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
  266. parser.add_argument('--save-json', action='store_true', help='save a COCO-JSON results file')
  267. parser.add_argument('--project', default='runs/val', help='save to project/name')
  268. parser.add_argument('--name', default='exp', help='save to project/name')
  269. parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
  270. parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
  271. opt = parser.parse_args()
  272. opt.save_json |= opt.data.endswith('coco.yaml')
  273. opt.save_txt |= opt.save_hybrid
  274. opt.data = check_file(opt.data) # check file
  275. return opt
  276. def main(opt):
  277. set_logging()
  278. print(colorstr('val: ') + ', '.join(f'{k}={v}' for k, v in vars(opt).items()))
  279. check_requirements(requirements=FILE.parent / 'requirements.txt', exclude=('tensorboard', 'thop'))
  280. if opt.task in ('train', 'val', 'test'): # run normally
  281. run(**vars(opt))
  282. elif opt.task == 'speed': # speed benchmarks
  283. for w in opt.weights if isinstance(opt.weights, list) else [opt.weights]:
  284. run(opt.data, weights=w, batch_size=opt.batch_size, imgsz=opt.imgsz, conf_thres=.25, iou_thres=.45,
  285. save_json=False, plots=False)
  286. elif opt.task == 'study': # run over a range of settings and save/plot
  287. # python val.py --task study --data coco.yaml --iou 0.7 --weights yolov5s.pt yolov5m.pt yolov5l.pt yolov5x.pt
  288. x = list(range(256, 1536 + 128, 128)) # x axis (image sizes)
  289. for w in opt.weights if isinstance(opt.weights, list) else [opt.weights]:
  290. f = f'study_{Path(opt.data).stem}_{Path(w).stem}.txt' # filename to save to
  291. y = [] # y axis
  292. for i in x: # img-size
  293. print(f'\nRunning {f} point {i}...')
  294. r, _, t = run(opt.data, weights=w, batch_size=opt.batch_size, imgsz=i, conf_thres=opt.conf_thres,
  295. iou_thres=opt.iou_thres, save_json=opt.save_json, plots=False)
  296. y.append(r + t) # results and times
  297. np.savetxt(f, y, fmt='%10.4g') # save
  298. os.system('zip -r study.zip study_*.txt')
  299. plot_study_txt(x=x) # plot
  300. if __name__ == "__main__":
  301. opt = parse_opt()
  302. main(opt)