Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

test.py 13 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
  1. import argparse
  2. import json
  3. from torch.utils.data import DataLoader
  4. from utils import google_utils
  5. from utils.datasets import *
  6. from utils.utils import *
  7. def test(data,
  8. weights=None,
  9. batch_size=16,
  10. imgsz=640,
  11. conf_thres=0.001,
  12. iou_thres=0.6, # for NMS
  13. save_json=False,
  14. single_cls=False,
  15. augment=False,
  16. verbose=False,
  17. model=None,
  18. dataloader=None,
  19. merge=False):
  20. # Initialize/load model and set device
  21. if model is None:
  22. training = False
  23. device = torch_utils.select_device(opt.device, batch_size=batch_size)
  24. half = device.type != 'cpu' # half precision only supported on CUDA
  25. # Remove previous
  26. for f in glob.glob('test_batch*.jpg'):
  27. os.remove(f)
  28. # Load model
  29. google_utils.attempt_download(weights)
  30. model = torch.load(weights, map_location=device)['model'].float() # load to FP32
  31. torch_utils.model_info(model)
  32. model.fuse()
  33. model.to(device)
  34. if half:
  35. model.half() # to FP16
  36. # Multi-GPU disabled, incompatible with .half()
  37. # if device.type != 'cpu' and torch.cuda.device_count() > 1:
  38. # model = nn.DataParallel(model)
  39. else: # called by train.py
  40. training = True
  41. device = next(model.parameters()).device # get model device
  42. # half disabled https://github.com/ultralytics/yolov5/issues/99
  43. half = False # device.type != 'cpu' and torch.cuda.device_count() == 1
  44. if half:
  45. model.half() # to FP16
  46. # Configure
  47. model.eval()
  48. with open(data) as f:
  49. data = yaml.load(f, Loader=yaml.FullLoader) # model dict
  50. nc = 1 if single_cls else int(data['nc']) # number of classes
  51. iouv = torch.linspace(0.5, 0.95, 10).to(device) # iou vector for mAP@0.5:0.95
  52. # iouv = iouv[0].view(1) # comment for mAP@0.5:0.95
  53. niou = iouv.numel()
  54. # Dataloader
  55. if dataloader is None: # not training
  56. img = torch.zeros((1, 3, imgsz, imgsz), device=device) # init img
  57. _ = model(img.half() if half else img) if device.type != 'cpu' else None # run once
  58. merge = opt.merge # use Merge NMS
  59. path = data['test'] if opt.task == 'test' else data['val'] # path to val/test images
  60. dataset = LoadImagesAndLabels(path,
  61. imgsz,
  62. batch_size,
  63. rect=True, # rectangular inference
  64. single_cls=opt.single_cls, # single class mode
  65. stride=int(max(model.stride)), # model stride
  66. pad=0.5) # padding
  67. batch_size = min(batch_size, len(dataset))
  68. nw = min([os.cpu_count(), batch_size if batch_size > 1 else 0, 8]) # number of workers
  69. dataloader = DataLoader(dataset,
  70. batch_size=batch_size,
  71. num_workers=nw,
  72. pin_memory=True,
  73. collate_fn=dataset.collate_fn)
  74. seen = 0
  75. names = model.names if hasattr(model, 'names') else model.module.names
  76. coco91class = coco80_to_coco91_class()
  77. s = ('%20s' + '%12s' * 6) % ('Class', 'Images', 'Targets', 'P', 'R', 'mAP@.5', 'mAP@.5:.95')
  78. p, r, f1, mp, mr, map50, map, t0, t1 = 0., 0., 0., 0., 0., 0., 0., 0., 0.
  79. loss = torch.zeros(3, device=device)
  80. jdict, stats, ap, ap_class = [], [], [], []
  81. for batch_i, (img, targets, paths, shapes) in enumerate(tqdm(dataloader, desc=s)):
  82. img = img.to(device)
  83. img = img.half() if half else img.float() # uint8 to fp16/32
  84. img /= 255.0 # 0 - 255 to 0.0 - 1.0
  85. targets = targets.to(device)
  86. nb, _, height, width = img.shape # batch size, channels, height, width
  87. whwh = torch.Tensor([width, height, width, height]).to(device)
  88. # Disable gradients
  89. with torch.no_grad():
  90. # Run model
  91. t = torch_utils.time_synchronized()
  92. inf_out, train_out = model(img, augment=augment) # inference and training outputs
  93. t0 += torch_utils.time_synchronized() - t
  94. # Compute loss
  95. if training: # if model has loss hyperparameters
  96. loss += compute_loss([x.float() for x in train_out], targets, model)[1][:3] # GIoU, obj, cls
  97. # Run NMS
  98. t = torch_utils.time_synchronized()
  99. output = non_max_suppression(inf_out, conf_thres=conf_thres, iou_thres=iou_thres, merge=merge)
  100. t1 += torch_utils.time_synchronized() - t
  101. # Statistics per image
  102. for si, pred in enumerate(output):
  103. labels = targets[targets[:, 0] == si, 1:]
  104. nl = len(labels)
  105. tcls = labels[:, 0].tolist() if nl else [] # target class
  106. seen += 1
  107. if pred is None:
  108. if nl:
  109. stats.append((torch.zeros(0, niou, dtype=torch.bool), torch.Tensor(), torch.Tensor(), tcls))
  110. continue
  111. # Append to text file
  112. # with open('test.txt', 'a') as file:
  113. # [file.write('%11.5g' * 7 % tuple(x) + '\n') for x in pred]
  114. # Clip boxes to image bounds
  115. clip_coords(pred, (height, width))
  116. # Append to pycocotools JSON dictionary
  117. if save_json:
  118. # [{"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236}, ...
  119. image_id = int(Path(paths[si]).stem.split('_')[-1])
  120. box = pred[:, :4].clone() # xyxy
  121. scale_coords(img[si].shape[1:], box, shapes[si][0], shapes[si][1]) # to original shape
  122. box = xyxy2xywh(box) # xywh
  123. box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner
  124. for p, b in zip(pred.tolist(), box.tolist()):
  125. jdict.append({'image_id': image_id,
  126. 'category_id': coco91class[int(p[5])],
  127. 'bbox': [round(x, 3) for x in b],
  128. 'score': round(p[4], 5)})
  129. # Assign all predictions as incorrect
  130. correct = torch.zeros(pred.shape[0], niou, dtype=torch.bool, device=device)
  131. if nl:
  132. detected = [] # target indices
  133. tcls_tensor = labels[:, 0]
  134. # target boxes
  135. tbox = xywh2xyxy(labels[:, 1:5]) * whwh
  136. # Per target class
  137. for cls in torch.unique(tcls_tensor):
  138. ti = (cls == tcls_tensor).nonzero().view(-1) # prediction indices
  139. pi = (cls == pred[:, 5]).nonzero().view(-1) # target indices
  140. # Search for detections
  141. if pi.shape[0]:
  142. # Prediction to target ious
  143. ious, i = box_iou(pred[pi, :4], tbox[ti]).max(1) # best ious, indices
  144. # Append detections
  145. for j in (ious > iouv[0]).nonzero():
  146. d = ti[i[j]] # detected target
  147. if d not in detected:
  148. detected.append(d)
  149. correct[pi[j]] = ious[j] > iouv # iou_thres is 1xn
  150. if len(detected) == nl: # all targets already located in image
  151. break
  152. # Append statistics (correct, conf, pcls, tcls)
  153. stats.append((correct.cpu(), pred[:, 4].cpu(), pred[:, 5].cpu(), tcls))
  154. # Plot images
  155. if batch_i < 1:
  156. f = 'test_batch%g_gt.jpg' % batch_i # filename
  157. plot_images(img, targets, paths, f, names) # ground truth
  158. f = 'test_batch%g_pred.jpg' % batch_i
  159. plot_images(img, output_to_target(output, width, height), paths, f, names) # predictions
  160. # Compute statistics
  161. stats = [np.concatenate(x, 0) for x in zip(*stats)] # to numpy
  162. if len(stats):
  163. p, r, ap, f1, ap_class = ap_per_class(*stats)
  164. p, r, ap50, ap = p[:, 0], r[:, 0], ap[:, 0], ap.mean(1) # [P, R, AP@0.5, AP@0.5:0.95]
  165. mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean()
  166. nt = np.bincount(stats[3].astype(np.int64), minlength=nc) # number of targets per class
  167. else:
  168. nt = torch.zeros(1)
  169. # Print results
  170. pf = '%20s' + '%12.3g' * 6 # print format
  171. print(pf % ('all', seen, nt.sum(), mp, mr, map50, map))
  172. # Print results per class
  173. if verbose and nc > 1 and len(stats):
  174. for i, c in enumerate(ap_class):
  175. print(pf % (names[c], seen, nt[c], p[i], r[i], ap50[i], ap[i]))
  176. # Print speeds
  177. t = tuple(x / seen * 1E3 for x in (t0, t1, t0 + t1)) + (imgsz, imgsz, batch_size) # tuple
  178. if not training:
  179. print('Speed: %.1f/%.1f/%.1f ms inference/NMS/total per %gx%g image at batch-size %g' % t)
  180. # Save JSON
  181. if save_json and map50 and len(jdict):
  182. imgIds = [int(Path(x).stem.split('_')[-1]) for x in dataloader.dataset.img_files]
  183. f = 'detections_val2017_%s_results.json' % \
  184. (weights.split(os.sep)[-1].replace('.pt', '') if weights else '') # filename
  185. print('\nCOCO mAP with pycocotools... saving %s...' % f)
  186. with open(f, 'w') as file:
  187. json.dump(jdict, file)
  188. try:
  189. from pycocotools.coco import COCO
  190. from pycocotools.cocoeval import COCOeval
  191. # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb
  192. cocoGt = COCO(glob.glob('../coco/annotations/instances_val*.json')[0]) # initialize COCO ground truth api
  193. cocoDt = cocoGt.loadRes(f) # initialize COCO pred api
  194. cocoEval = COCOeval(cocoGt, cocoDt, 'bbox')
  195. cocoEval.params.imgIds = imgIds # image IDs to evaluate
  196. cocoEval.evaluate()
  197. cocoEval.accumulate()
  198. cocoEval.summarize()
  199. map, map50 = cocoEval.stats[:2] # update results (mAP@0.5:0.95, mAP@0.5)
  200. except:
  201. print('WARNING: pycocotools must be installed with numpy==1.17 to run correctly. '
  202. 'See https://github.com/cocodataset/cocoapi/issues/356')
  203. # Return results
  204. maps = np.zeros(nc) + map
  205. for i, c in enumerate(ap_class):
  206. maps[c] = ap[i]
  207. return (mp, mr, map50, map, *(loss.cpu() / len(dataloader)).tolist()), maps, t
  208. if __name__ == '__main__':
  209. parser = argparse.ArgumentParser(prog='test.py')
  210. parser.add_argument('--weights', type=str, default='weights/yolov5s.pt', help='model.pt path')
  211. parser.add_argument('--data', type=str, default='data/coco128.yaml', help='*.data path')
  212. parser.add_argument('--batch-size', type=int, default=32, help='size of each image batch')
  213. parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
  214. parser.add_argument('--conf-thres', type=float, default=0.001, help='object confidence threshold')
  215. parser.add_argument('--iou-thres', type=float, default=0.65, help='IOU threshold for NMS')
  216. parser.add_argument('--save-json', action='store_true', help='save a cocoapi-compatible JSON results file')
  217. parser.add_argument('--task', default='val', help="'val', 'test', 'study'")
  218. parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  219. parser.add_argument('--single-cls', action='store_true', help='treat as single-class dataset')
  220. parser.add_argument('--augment', action='store_true', help='augmented inference')
  221. parser.add_argument('--merge', action='store_true', help='use Merge NMS')
  222. parser.add_argument('--verbose', action='store_true', help='report mAP by class')
  223. opt = parser.parse_args()
  224. opt.img_size = check_img_size(opt.img_size)
  225. opt.save_json = opt.save_json or opt.data.endswith('coco.yaml')
  226. opt.data = check_file(opt.data) # check file
  227. print(opt)
  228. # task = 'val', 'test', 'study'
  229. if opt.task in ['val', 'test']: # (default) run normally
  230. test(opt.data,
  231. opt.weights,
  232. opt.batch_size,
  233. opt.img_size,
  234. opt.conf_thres,
  235. opt.iou_thres,
  236. opt.save_json,
  237. opt.single_cls,
  238. opt.augment,
  239. opt.verbose)
  240. elif opt.task == 'study': # run over a range of settings and save/plot
  241. for weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt', 'yolov3-spp.pt']:
  242. f = 'study_%s_%s.txt' % (Path(opt.data).stem, Path(weights).stem) # filename to save to
  243. x = list(range(352, 832, 64)) # x axis
  244. y = [] # y axis
  245. for i in x: # img-size
  246. print('\nRunning %s point %s...' % (f, i))
  247. r, _, t = test(opt.data, weights, opt.batch_size, i, opt.conf_thres, opt.iou_thres, opt.save_json)
  248. y.append(r + t) # results and times
  249. np.savetxt(f, y, fmt='%10.4g') # save
  250. os.system('zip -r study.zip study_*.txt')
  251. # plot_study_txt(f, x) # plot
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...