josedolot commited on
Commit
ffe5ce9
·
1 Parent(s): 794aa23

Upload val.py

Browse files
Files changed (1) hide show
  1. val.py +508 -0
val.py ADDED
@@ -0,0 +1,508 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ import argparse
4
+ from tqdm.autonotebook import tqdm
5
+ import os
6
+
7
+ from utils import smp_metrics
8
+ from utils.utils import ConfusionMatrix, postprocess, scale_coords, process_batch, ap_per_class, fitness, \
9
+ save_checkpoint, DataLoaderX, BBoxTransform, ClipBoxes, boolean_string, Params
10
+ from backbone import HybridNetsBackbone
11
+ from hybridnets.dataset import BddDataset
12
+ from torchvision import transforms
13
+
14
+
15
+ @torch.no_grad()
16
+ def val(model, optimizer, val_generator, params, opt, writer, epoch, step, best_fitness, best_loss, best_epoch):
17
+ model.eval()
18
+ loss_regression_ls = []
19
+ loss_classification_ls = []
20
+ loss_segmentation_ls = []
21
+ jdict, stats, ap, ap_class = [], [], [], []
22
+ iou_thresholds = torch.linspace(0.5, 0.95, 10).cuda() # iou vector for [email protected]:0.95
23
+ num_thresholds = iou_thresholds.numel()
24
+ names = {i: v for i, v in enumerate(params.obj_list)}
25
+ nc = len(names)
26
+ seen = 0
27
+ confusion_matrix = ConfusionMatrix(nc=nc)
28
+ s = ('%15s' + '%11s' * 14) % (
29
+ 'Class', 'Images', 'Labels', 'P', 'R', '[email protected]', '[email protected]:.95', 'mIoU', 'mF1', 'fIoU', 'sIoU', 'rIoU', 'rF1', 'lIoU', 'lF1')
30
+ dt, p, r, f1, mp, mr, map50, map = [0.0, 0.0, 0.0], 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
31
+ iou_ls = [[] for _ in range(3)]
32
+ f1_ls = [[] for _ in range(3)]
33
+ regressBoxes = BBoxTransform()
34
+ clipBoxes = ClipBoxes()
35
+
36
+ val_loader = tqdm(val_generator)
37
+ for iter, data in enumerate(val_loader):
38
+ imgs = data['img']
39
+ annot = data['annot']
40
+ seg_annot = data['segmentation']
41
+ filenames = data['filenames']
42
+ shapes = data['shapes']
43
+
44
+ if opt.num_gpus == 1:
45
+ imgs = imgs.cuda()
46
+ annot = annot.cuda()
47
+ seg_annot = seg_annot.cuda()
48
+
49
+ cls_loss, reg_loss, seg_loss, regression, classification, anchors, segmentation = model(imgs, annot,
50
+ seg_annot,
51
+ obj_list=params.obj_list)
52
+ cls_loss = cls_loss.mean()
53
+ reg_loss = reg_loss.mean()
54
+ seg_loss = seg_loss.mean()
55
+
56
+ if opt.cal_map:
57
+ out = postprocess(imgs.detach(),
58
+ torch.stack([anchors[0]] * imgs.shape[0], 0).detach(), regression.detach(),
59
+ classification.detach(),
60
+ regressBoxes, clipBoxes,
61
+ 0.001, 0.6) # 0.5, 0.3
62
+
63
+ for i in range(annot.size(0)):
64
+ seen += 1
65
+ labels = annot[i]
66
+ labels = labels[labels[:, 4] != -1]
67
+
68
+ ou = out[i]
69
+ nl = len(labels)
70
+
71
+ pred = np.column_stack([ou['rois'], ou['scores']])
72
+ pred = np.column_stack([pred, ou['class_ids']])
73
+ pred = torch.from_numpy(pred).cuda()
74
+
75
+ target_class = labels[:, 4].tolist() if nl else [] # target class
76
+
77
+ if len(pred) == 0:
78
+ if nl:
79
+ stats.append((torch.zeros(0, num_thresholds, dtype=torch.bool),
80
+ torch.Tensor(), torch.Tensor(), target_class))
81
+ # print("here")
82
+ continue
83
+
84
+ if nl:
85
+ pred[:, :4] = scale_coords(imgs[i][1:], pred[:, :4], shapes[i][0], shapes[i][1])
86
+ labels = scale_coords(imgs[i][1:], labels, shapes[i][0], shapes[i][1])
87
+ correct = process_batch(pred, labels, iou_thresholds)
88
+ if opt.plots:
89
+ confusion_matrix.process_batch(pred, labels)
90
+ else:
91
+ correct = torch.zeros(pred.shape[0], num_thresholds, dtype=torch.bool)
92
+ stats.append((correct.cpu(), pred[:, 4].cpu(), pred[:, 5].cpu(), target_class))
93
+
94
+ # print(stats)
95
+
96
+ # Visualization
97
+ # seg_0 = segmentation[i]
98
+ # # print('bbb', seg_0.shape)
99
+ # seg_0 = torch.argmax(seg_0, dim = 0)
100
+ # # print('before', seg_0.shape)
101
+ # seg_0 = seg_0.cpu().numpy()
102
+ # #.transpose(1, 2, 0)
103
+ # # print(seg_0.shape)
104
+ # anh = np.zeros((384,640,3))
105
+ # anh[seg_0 == 0] = (255,0,0)
106
+ # anh[seg_0 == 1] = (0,255,0)
107
+ # anh[seg_0 == 2] = (0,0,255)
108
+ # anh = np.uint8(anh)
109
+ # cv2.imwrite('segmentation-{}.jpg'.format(filenames[i]),anh)
110
+
111
+ # Convert segmentation tensor --> 3 binary 0 1
112
+ # batch_size, num_classes, height, width
113
+ _, segmentation = torch.max(segmentation, 1)
114
+ # _, seg_annot = torch.max(seg_annot, 1)
115
+ seg = torch.zeros((seg_annot.size(0), 3, 384, 640), dtype=torch.int32)
116
+ seg[:, 0, ...][segmentation == 0] = 1
117
+ seg[:, 1, ...][segmentation == 1] = 1
118
+ seg[:, 2, ...][segmentation == 2] = 1
119
+
120
+ tp_seg, fp_seg, fn_seg, tn_seg = smp_metrics.get_stats(seg.cuda(), seg_annot.long().cuda(),
121
+ mode='multilabel', threshold=None)
122
+
123
+ iou = smp_metrics.iou_score(tp_seg, fp_seg, fn_seg, tn_seg, reduction='none')
124
+ # print(iou)
125
+ f1 = smp_metrics.balanced_accuracy(tp_seg, fp_seg, fn_seg, tn_seg, reduction='none')
126
+
127
+ for i in range(len(params.seg_list) + 1):
128
+ iou_ls[i].append(iou.T[i].detach().cpu().numpy())
129
+ f1_ls[i].append(f1.T[i].detach().cpu().numpy())
130
+
131
+ loss = cls_loss + reg_loss + seg_loss
132
+ if loss == 0 or not torch.isfinite(loss):
133
+ continue
134
+
135
+ loss_classification_ls.append(cls_loss.item())
136
+ loss_regression_ls.append(reg_loss.item())
137
+ loss_segmentation_ls.append(seg_loss.item())
138
+
139
+ cls_loss = np.mean(loss_classification_ls)
140
+ reg_loss = np.mean(loss_regression_ls)
141
+ seg_loss = np.mean(loss_segmentation_ls)
142
+ loss = cls_loss + reg_loss + seg_loss
143
+
144
+ print(
145
+ 'Val. Epoch: {}/{}. Classification loss: {:1.5f}. Regression loss: {:1.5f}. Segmentation loss: {:1.5f}. Total loss: {:1.5f}'.format(
146
+ epoch, opt.num_epochs, cls_loss, reg_loss, seg_loss, loss))
147
+ writer.add_scalars('Loss', {'val': loss}, step)
148
+ writer.add_scalars('Regression_loss', {'val': reg_loss}, step)
149
+ writer.add_scalars('Classfication_loss', {'val': cls_loss}, step)
150
+ writer.add_scalars('Segmentation_loss', {'val': seg_loss}, step)
151
+
152
+ if opt.cal_map:
153
+ # print(len(iou_ls[0]))
154
+ iou_score = np.mean(iou_ls)
155
+ # print(iou_score)
156
+ f1_score = np.mean(f1_ls)
157
+
158
+ iou_first_decoder = iou_ls[0] + iou_ls[1]
159
+ iou_first_decoder = np.mean(iou_first_decoder)
160
+
161
+ iou_second_decoder = iou_ls[0] + iou_ls[2]
162
+ iou_second_decoder = np.mean(iou_second_decoder)
163
+
164
+ for i in range(len(params.seg_list) + 1):
165
+ iou_ls[i] = np.mean(iou_ls[i])
166
+ f1_ls[i] = np.mean(f1_ls[i])
167
+
168
+ # Compute statistics
169
+ stats = [np.concatenate(x, 0) for x in zip(*stats)]
170
+ # print(stats[3])
171
+
172
+ # Count detected boxes per class
173
+ # boxes_per_class = np.bincount(stats[2].astype(np.int64), minlength=1)
174
+
175
+ ap50 = None
176
+ save_dir = 'plots'
177
+ os.makedirs(save_dir, exist_ok=True)
178
+
179
+ # Compute metrics
180
+ if len(stats) and stats[0].any():
181
+ p, r, f1, ap, ap_class = ap_per_class(*stats, plot=opt.plots, save_dir=save_dir, names=names)
182
+ ap50, ap = ap[:, 0], ap.mean(1) # [email protected], [email protected]:0.95
183
+ mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean()
184
+ nt = np.bincount(stats[3].astype(np.int64), minlength=1) # number of targets per class
185
+ else:
186
+ nt = torch.zeros(1)
187
+
188
+ # Print results
189
+ print(s)
190
+ pf = '%15s' + '%11i' * 2 + '%11.3g' * 12 # print format
191
+ print(pf % ('all', seen, nt.sum(), mp, mr, map50, map, iou_score, f1_score, iou_first_decoder, iou_second_decoder,
192
+ iou_ls[1], f1_ls[1], iou_ls[2], f1_ls[2]))
193
+
194
+ # Print results per class
195
+ training = True
196
+ if (opt.verbose or (nc < 50 and not training)) and nc > 1 and len(stats):
197
+ for i, c in enumerate(ap_class):
198
+ print(pf % (names[c], seen, nt[c], p[i], r[i], ap50[i], ap[i]))
199
+
200
+ # Plots
201
+ if opt.plots:
202
+ confusion_matrix.plot(save_dir=save_dir, names=list(names.values()))
203
+ confusion_matrix.tp_fp()
204
+
205
+ results = (mp, mr, map50, map, iou_score, f1_score, loss)
206
+ fi = fitness(
207
+ np.array(results).reshape(1, -1)) # weighted combination of [P, R, [email protected], [email protected], iou, f1, loss ]
208
+
209
+ # if calculating map, save by best fitness
210
+ if fi > best_fitness:
211
+ best_fitness = fi
212
+ ckpt = {'epoch': epoch,
213
+ 'step': step,
214
+ 'best_fitness': best_fitness,
215
+ 'model': model,
216
+ 'optimizer': optimizer.state_dict()}
217
+ print("Saving checkpoint with best fitness", fi[0])
218
+ save_checkpoint(ckpt, opt.saved_path, f'hybridnets-d{opt.compound_coef}_{epoch}_{step}_best.pth')
219
+ else:
220
+ # if not calculating map, save by best loss
221
+ if loss + opt.es_min_delta < best_loss:
222
+ best_loss = loss
223
+ best_epoch = epoch
224
+
225
+ save_checkpoint(model, opt.saved_path, f'hybridnets-d{opt.compound_coef}_{epoch}_{step}_best.pth')
226
+
227
+ # Early stopping
228
+ if epoch - best_epoch > opt.es_patience > 0:
229
+ print('[Info] Stop training at epoch {}. The lowest loss achieved is {}'.format(epoch, best_loss))
230
+ writer.close()
231
+ exit(0)
232
+
233
+ model.train()
234
+ return best_fitness, best_loss, best_epoch
235
+
236
+
237
+ @torch.no_grad()
238
+ def val_from_cmd(model, val_generator, params, opt):
239
+ model.eval()
240
+ jdict, stats, ap, ap_class = [], [], [], []
241
+ iou_thresholds = torch.linspace(0.5, 0.95, 10).cuda() # iou vector for [email protected]:0.95
242
+ num_thresholds = iou_thresholds.numel()
243
+ names = {i: v for i, v in enumerate(params.obj_list)}
244
+ nc = len(names)
245
+ seen = 0
246
+ confusion_matrix = ConfusionMatrix(nc=nc)
247
+ s = ('%15s' + '%11s' * 14) % (
248
+ 'Class', 'Images', 'Labels', 'P', 'R', '[email protected]', '[email protected]:.95', 'mIoU', 'mF1', 'fIoU', 'sIoU', 'rIoU', 'rF1', 'lIoU', 'lF1')
249
+ dt, p, r, f1, mp, mr, map50, map = [0.0, 0.0, 0.0], 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
250
+ iou_ls = [[] for _ in range(3)]
251
+ f1_ls = [[] for _ in range(3)]
252
+ regressBoxes = BBoxTransform()
253
+ clipBoxes = ClipBoxes()
254
+
255
+ val_loader = tqdm(val_generator)
256
+ for iter, data in enumerate(val_loader):
257
+ imgs = data['img']
258
+ annot = data['annot']
259
+ seg_annot = data['segmentation']
260
+ filenames = data['filenames']
261
+ shapes = data['shapes']
262
+
263
+ if opt.num_gpus == 1:
264
+ imgs = imgs.cuda()
265
+ annot = annot.cuda()
266
+ seg_annot = seg_annot.cuda()
267
+
268
+ features, regressions, classifications, anchors, segmentation = model(imgs)
269
+
270
+ out = postprocess(imgs.detach(),
271
+ torch.stack([anchors[0]] * imgs.shape[0], 0).detach(), regressions.detach(),
272
+ classifications.detach(),
273
+ regressBoxes, clipBoxes,
274
+ 0.001, 0.6) # 0.5, 0.3
275
+
276
+ # imgs = imgs.permute(0, 2, 3, 1).cpu().numpy()
277
+ # imgs = ((imgs * [0.229, 0.224, 0.225] + [0.485, 0.456, 0.406]) * 255).astype(np.uint8)
278
+ # imgs = [cv2.cvtColor(img, cv2.COLOR_RGB2BGR) for img in imgs]
279
+ # display(out, imgs, ['car'], imshow=False, imwrite=True)
280
+
281
+ # for index, filename in enumerate(filenames):
282
+ # ori_img = cv2.imread('datasets/bdd100k/val/'+filename)
283
+ # if len(out[index]['rois']):
284
+ # for roi in out[index]['rois']:
285
+ # x1,y1,x2,y2 = [int(x) for x in roi]
286
+ # cv2.rectangle(ori_img, (x1,y1), (x2,y2), (255,0,0), 1)
287
+ # cv2.imwrite(filename, ori_img)
288
+
289
+ for i in range(annot.size(0)):
290
+ seen += 1
291
+ labels = annot[i]
292
+ labels = labels[labels[:, 4] != -1]
293
+
294
+ ou = out[i]
295
+ nl = len(labels)
296
+
297
+ pred = np.column_stack([ou['rois'], ou['scores']])
298
+ pred = np.column_stack([pred, ou['class_ids']])
299
+ pred = torch.from_numpy(pred).cuda()
300
+
301
+ target_class = labels[:, 4].tolist() if nl else [] # target class
302
+
303
+ if len(pred) == 0:
304
+ if nl:
305
+ stats.append((torch.zeros(0, num_thresholds, dtype=torch.bool),
306
+ torch.Tensor(), torch.Tensor(), target_class))
307
+ # print("here")
308
+ continue
309
+
310
+ if nl:
311
+ pred[:, :4] = scale_coords(imgs[i][1:], pred[:, :4], shapes[i][0], shapes[i][1])
312
+
313
+ labels = scale_coords(imgs[i][1:], labels, shapes[i][0], shapes[i][1])
314
+
315
+ # ori_img = cv2.imread('datasets/bdd100k_effdet/val/' + filenames[i],
316
+ # cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION | cv2.IMREAD_UNCHANGED)
317
+ # for label in labels:
318
+ # x1, y1, x2, y2 = [int(x) for x in label[:4]]
319
+ # ori_img = cv2.rectangle(ori_img, (x1, y1), (x2, y2), (255, 0, 0), 1)
320
+ # for pre in pred:
321
+ # x1, y1, x2, y2 = [int(x) for x in pre[:4]]
322
+ # # ori_img = cv2.putText(ori_img, str(pre[4].cpu().numpy()), (x1 - 10, y1 - 10),
323
+ # # cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1, cv2.LINE_AA)
324
+ # ori_img = cv2.rectangle(ori_img, (x1, y1), (x2, y2), (0, 255, 0), 1)
325
+
326
+ # cv2.imwrite('pre+label-{}.jpg'.format(filenames[i]), ori_img)
327
+ correct = process_batch(pred, labels, iou_thresholds)
328
+ if opt.plots:
329
+ confusion_matrix.process_batch(pred, labels)
330
+ else:
331
+ correct = torch.zeros(pred.shape[0], num_thresholds, dtype=torch.bool)
332
+ stats.append((correct.cpu(), pred[:, 4].cpu(), pred[:, 5].cpu(), target_class))
333
+
334
+ # print(stats)
335
+
336
+ # Visualization
337
+ # seg_0 = segmentation[i]
338
+ # # print('bbb', seg_0.shape)
339
+ # seg_0 = torch.argmax(seg_0, dim = 0)
340
+ # # print('before', seg_0.shape)
341
+ # seg_0 = seg_0.cpu().numpy()
342
+ # #.transpose(1, 2, 0)
343
+ # # print(seg_0.shape)
344
+ # anh = np.zeros((384,640,3))
345
+ # anh[seg_0 == 0] = (255,0,0)
346
+ # anh[seg_0 == 1] = (0,255,0)
347
+ # anh[seg_0 == 2] = (0,0,255)
348
+ # anh = np.uint8(anh)
349
+ # cv2.imwrite('segmentation-{}.jpg'.format(filenames[i]),anh)
350
+
351
+ # Convert segmentation tensor --> 3 binary 0 1
352
+ # batch_size, num_classes, height, width
353
+ _, segmentation = torch.max(segmentation, 1)
354
+ # _, seg_annot = torch.max(seg_annot, 1)
355
+ seg = torch.zeros((seg_annot.size(0), 3, 384, 640), dtype=torch.int32)
356
+ seg[:, 0, ...][segmentation == 0] = 1
357
+ seg[:, 1, ...][segmentation == 1] = 1
358
+ seg[:, 2, ...][segmentation == 2] = 1
359
+
360
+ tp_seg, fp_seg, fn_seg, tn_seg = smp_metrics.get_stats(seg.cuda(), seg_annot.long().cuda(), mode='multilabel',
361
+ threshold=None)
362
+
363
+ iou = smp_metrics.iou_score(tp_seg, fp_seg, fn_seg, tn_seg, reduction='none')
364
+ # print(iou)
365
+ f1 = smp_metrics.balanced_accuracy(tp_seg, fp_seg, fn_seg, tn_seg, reduction='none')
366
+
367
+ for i in range(len(params.seg_list) + 1):
368
+ iou_ls[i].append(iou.T[i].detach().cpu().numpy())
369
+ f1_ls[i].append(f1.T[i].detach().cpu().numpy())
370
+
371
+ # Visualize
372
+ # for i in range(segmentation.size(0)):
373
+ # if iou_ls[1][iter][i] < 0.4:
374
+ # import cv2
375
+ #
376
+ # ori = cv2.imread('datasets/bdd100k/val/{}'.format(filenames[i]))
377
+ # cv2.imwrite('ori-segmentation-{}-{}.jpg'.format(iter,filenames[i]),ori)
378
+ #
379
+ # gt = seg_annot[i].detach()
380
+ # gt = torch.argmax(gt, dim = 0).cpu().numpy()
381
+ #
382
+ # anh = np.zeros((384,640,3))
383
+ # anh[gt == 0] = (255,0,0)
384
+ # anh[gt == 1] = (0,255,0)
385
+ # anh[gt == 2] = (0,0,255)
386
+ # cv2.imwrite('gt-segmentation-{}-{}.jpg'.format(iter,filenames[i]),anh)
387
+ #
388
+ # seg_0 = seg[i]
389
+ # seg_0 = torch.argmax(seg_0, dim = 0)
390
+ # seg_0 = seg_0.cpu().numpy()
391
+ # anh = np.zeros((384,640,3))
392
+ # anh[seg_0 == 0] = (255,0,0)
393
+ # anh[seg_0 == 1] = (0,255,0)
394
+ # anh[seg_0 == 2] = (0,0,255)
395
+ # anh = np.uint8(anh)
396
+ # cv2.imwrite('segmentation-{}-{}.jpg'.format(iter,filenames[i]),anh)
397
+
398
+ # print(len(iou_ls[0]))
399
+ # print(iou_ls)
400
+ iou_score = np.mean(iou_ls)
401
+ # print(iou_score)
402
+ f1_score = np.mean(f1_ls)
403
+
404
+ iou_first_decoder = iou_ls[0] + iou_ls[1]
405
+ iou_first_decoder = np.mean(iou_first_decoder)
406
+
407
+ iou_second_decoder = iou_ls[0] + iou_ls[2]
408
+ iou_second_decoder = np.mean(iou_second_decoder)
409
+
410
+ for i in range(len(params.seg_list) + 1):
411
+ iou_ls[i] = np.mean(iou_ls[i])
412
+ f1_ls[i] = np.mean(f1_ls[i])
413
+
414
+ # Compute statistics
415
+ stats = [np.concatenate(x, 0) for x in zip(*stats)]
416
+
417
+ # Count detected boxes per class
418
+ # boxes_per_class = np.bincount(stats[2].astype(np.int64), minlength=1)
419
+
420
+ ap50 = None
421
+ save_dir = 'plots'
422
+ os.makedirs(save_dir, exist_ok=True)
423
+
424
+ # Compute metrics
425
+ if len(stats) and stats[0].any():
426
+ p, r, f1, ap, ap_class = ap_per_class(*stats, plot=opt.plots, save_dir=save_dir, names=names)
427
+ ap50, ap = ap[:, 0], ap.mean(1) # [email protected], [email protected]:0.95
428
+ mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean()
429
+ nt = np.bincount(stats[3].astype(np.int64), minlength=1) # number of targets per class
430
+ else:
431
+ nt = torch.zeros(1)
432
+
433
+ # Print results
434
+ print(s)
435
+ pf = '%15s' + '%11i' * 2 + '%11.3g' * 12 # print format
436
+ print(pf % ('all', seen, nt.sum(), mp, mr, map50, map, iou_score, f1_score, iou_first_decoder, iou_second_decoder,
437
+ iou_ls[1], f1_ls[1], iou_ls[2], f1_ls[2]))
438
+
439
+ # Print results per class
440
+ training = False
441
+ if (opt.verbose or (nc < 50 and not training)) and nc > 1 and len(stats):
442
+ for i, c in enumerate(ap_class):
443
+ print(pf % (names[c], seen, nt[c], p[i], r[i], ap50[i], ap[i]))
444
+
445
+ # Plots
446
+ if opt.plots:
447
+ confusion_matrix.plot(save_dir=save_dir, names=list(names.values()))
448
+ confusion_matrix.tp_fp()
449
+
450
+
451
+ if __name__ == "__main__":
452
+ ap = argparse.ArgumentParser()
453
+ ap.add_argument('-p', '--project', type=str, default='coco', help='Project file that contains parameters')
454
+ ap.add_argument('-c', '--compound_coef', type=int, default=0, help='Coefficients of efficientnet backbone')
455
+ ap.add_argument('-w', '--weights', type=str, default=None, help='/path/to/weights')
456
+ ap.add_argument('-n', '--num_workers', type=int, default=12, help='Num_workers of dataloader')
457
+ ap.add_argument('--batch_size', type=int, default=12, help='The number of images per batch among all devices')
458
+ ap.add_argument('-v', '--verbose', type=boolean_string, default=True,
459
+ help='Whether to print results per class when valing')
460
+ ap.add_argument('--plots', type=boolean_string, default=True,
461
+ help='Whether to plot confusion matrix when valing')
462
+ ap.add_argument('--num_gpus', type=int, default=1,
463
+ help='Number of GPUs to be used (0 to use CPU)')
464
+ args = ap.parse_args()
465
+
466
+ compound_coef = args.compound_coef
467
+ project_name = args.project
468
+ weights_path = f'weights/hybridnets-d{compound_coef}.pth' if args.weights is None else args.weights
469
+
470
+ params = Params(f'projects/{project_name}.yml')
471
+ obj_list = params.obj_list
472
+
473
+ valid_dataset = BddDataset(
474
+ params=params,
475
+ is_train=False,
476
+ inputsize=params.model['image_size'],
477
+ transform=transforms.Compose([
478
+ transforms.ToTensor(),
479
+ transforms.Normalize(
480
+ mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
481
+ )
482
+ ])
483
+ )
484
+
485
+ val_generator = DataLoaderX(
486
+ valid_dataset,
487
+ batch_size=args.batch_size,
488
+ shuffle=False,
489
+ num_workers=args.num_workers,
490
+ pin_memory=params.pin_memory,
491
+ collate_fn=BddDataset.collate_fn
492
+ )
493
+
494
+ model = HybridNetsBackbone(compound_coef=compound_coef, num_classes=len(params.obj_list),
495
+ ratios=eval(params.anchors_ratios), scales=eval(params.anchors_scales),
496
+ seg_classes=len(params.seg_list))
497
+
498
+ # print(model)
499
+ try:
500
+ model.load_state_dict(torch.load(weights_path))
501
+ except:
502
+ model.load_state_dict(torch.load(weights_path)['model'])
503
+ model.requires_grad_(False)
504
+
505
+ if args.num_gpus > 0:
506
+ model.cuda()
507
+
508
+ val_from_cmd(model, val_generator, params, args)