|
|
@ -22,7 +22,6 @@ class DetectionValidator(BaseValidator):
|
|
|
|
self.data_dict = yaml_load(check_file(self.args.data), append_filename=True) if self.args.data else None
|
|
|
|
self.data_dict = yaml_load(check_file(self.args.data), append_filename=True) if self.args.data else None
|
|
|
|
self.is_coco = False
|
|
|
|
self.is_coco = False
|
|
|
|
self.class_map = None
|
|
|
|
self.class_map = None
|
|
|
|
self.targets = None
|
|
|
|
|
|
|
|
self.metrics = DetMetrics(save_dir=self.save_dir, plot=self.args.plots)
|
|
|
|
self.metrics = DetMetrics(save_dir=self.save_dir, plot=self.args.plots)
|
|
|
|
self.iouv = torch.linspace(0.5, 0.95, 10) # iou vector for mAP@0.5:0.95
|
|
|
|
self.iouv = torch.linspace(0.5, 0.95, 10) # iou vector for mAP@0.5:0.95
|
|
|
|
self.niou = self.iouv.numel()
|
|
|
|
self.niou = self.iouv.numel()
|
|
|
@ -30,13 +29,13 @@ class DetectionValidator(BaseValidator):
|
|
|
|
def preprocess(self, batch):
|
|
|
|
def preprocess(self, batch):
|
|
|
|
batch["img"] = batch["img"].to(self.device, non_blocking=True)
|
|
|
|
batch["img"] = batch["img"].to(self.device, non_blocking=True)
|
|
|
|
batch["img"] = (batch["img"].half() if self.args.half else batch["img"].float()) / 255
|
|
|
|
batch["img"] = (batch["img"].half() if self.args.half else batch["img"].float()) / 255
|
|
|
|
self.nb, _, self.height, self.width = batch["img"].shape # batch size, channels, height, width
|
|
|
|
for k in ["batch_idx", "cls", "bboxes"]:
|
|
|
|
self.targets = torch.cat((batch["batch_idx"].view(-1, 1), batch["cls"].view(-1, 1), batch["bboxes"]), 1)
|
|
|
|
batch[k] = batch[k].to(self.device)
|
|
|
|
self.targets = self.targets.to(self.device)
|
|
|
|
|
|
|
|
height, width = batch["img"].shape[2:]
|
|
|
|
nb, _, height, width = batch["img"].shape
|
|
|
|
self.targets[:, 2:] *= torch.tensor((width, height, width, height), device=self.device) # to pixels
|
|
|
|
batch["bboxes"] *= torch.tensor((width, height, width, height), device=self.device) # to pixels
|
|
|
|
self.lb = [self.targets[self.targets[:, 0] == i, 1:]
|
|
|
|
self.lb = [torch.cat([batch["cls"], batch["bboxes"]], dim=-1)[batch["batch_idx"] == i]
|
|
|
|
for i in range(self.nb)] if self.args.save_hybrid else [] # for autolabelling
|
|
|
|
for i in range(nb)] if self.args.save_hybrid else [] # for autolabelling
|
|
|
|
|
|
|
|
|
|
|
|
return batch
|
|
|
|
return batch
|
|
|
|
|
|
|
|
|
|
|
@ -69,36 +68,39 @@ class DetectionValidator(BaseValidator):
|
|
|
|
def update_metrics(self, preds, batch):
|
|
|
|
def update_metrics(self, preds, batch):
|
|
|
|
# Metrics
|
|
|
|
# Metrics
|
|
|
|
for si, pred in enumerate(preds):
|
|
|
|
for si, pred in enumerate(preds):
|
|
|
|
labels = self.targets[self.targets[:, 0] == si, 1:]
|
|
|
|
idx = batch["batch_idx"] == si
|
|
|
|
nl, npr = labels.shape[0], pred.shape[0] # number of labels, predictions
|
|
|
|
cls = batch["cls"][idx]
|
|
|
|
|
|
|
|
bbox = batch["bboxes"][idx]
|
|
|
|
|
|
|
|
nl, npr = cls.shape[0], pred.shape[0] # number of labels, predictions
|
|
|
|
shape = batch["ori_shape"][si]
|
|
|
|
shape = batch["ori_shape"][si]
|
|
|
|
# path = batch["shape"][si][0]
|
|
|
|
|
|
|
|
correct_bboxes = torch.zeros(npr, self.niou, dtype=torch.bool, device=self.device) # init
|
|
|
|
correct_bboxes = torch.zeros(npr, self.niou, dtype=torch.bool, device=self.device) # init
|
|
|
|
self.seen += 1
|
|
|
|
self.seen += 1
|
|
|
|
|
|
|
|
|
|
|
|
if npr == 0:
|
|
|
|
if npr == 0:
|
|
|
|
if nl:
|
|
|
|
if nl:
|
|
|
|
self.stats.append((correct_bboxes, *torch.zeros((2, 0), device=self.device), labels[:, 0]))
|
|
|
|
self.stats.append((correct_bboxes, *torch.zeros((2, 0), device=self.device), cls.squeeze(-1)))
|
|
|
|
if self.args.plots:
|
|
|
|
if self.args.plots:
|
|
|
|
self.confusion_matrix.process_batch(detections=None, labels=labels[:, 0])
|
|
|
|
self.confusion_matrix.process_batch(detections=None, labels=cls.squeeze(-1))
|
|
|
|
continue
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
|
|
# Predictions
|
|
|
|
# Predictions
|
|
|
|
if self.args.single_cls:
|
|
|
|
if self.args.single_cls:
|
|
|
|
pred[:, 5] = 0
|
|
|
|
pred[:, 5] = 0
|
|
|
|
predn = pred.clone()
|
|
|
|
predn = pred.clone()
|
|
|
|
ops.scale_boxes(batch["img"][si].shape[1:], predn[:, :4], shape) # native-space pred
|
|
|
|
ops.scale_boxes(batch["img"][si].shape[1:], predn[:, :4], shape,
|
|
|
|
|
|
|
|
ratio_pad=batch["ratio_pad"][si]) # native-space pred
|
|
|
|
|
|
|
|
|
|
|
|
# Evaluate
|
|
|
|
# Evaluate
|
|
|
|
if nl:
|
|
|
|
if nl:
|
|
|
|
tbox = ops.xywh2xyxy(labels[:, 1:5]) # target boxes
|
|
|
|
tbox = ops.xywh2xyxy(bbox) # target boxes
|
|
|
|
ops.scale_boxes(batch["img"][si].shape[1:], tbox, shape) # native-space labels
|
|
|
|
ops.scale_boxes(batch["img"][si].shape[1:], tbox, shape,
|
|
|
|
labelsn = torch.cat((labels[:, 0:1], tbox), 1) # native-space labels
|
|
|
|
ratio_pad=batch["ratio_pad"][si]) # native-space labels
|
|
|
|
|
|
|
|
labelsn = torch.cat((cls, tbox), 1) # native-space labels
|
|
|
|
correct_bboxes = self._process_batch(predn, labelsn)
|
|
|
|
correct_bboxes = self._process_batch(predn, labelsn)
|
|
|
|
# TODO: maybe remove these `self.` arguments as they already are member variable
|
|
|
|
# TODO: maybe remove these `self.` arguments as they already are member variable
|
|
|
|
if self.args.plots:
|
|
|
|
if self.args.plots:
|
|
|
|
self.confusion_matrix.process_batch(predn, labelsn)
|
|
|
|
self.confusion_matrix.process_batch(predn, labelsn)
|
|
|
|
self.stats.append((correct_bboxes, pred[:, 4], pred[:, 5], labels[:, 0])) # (conf, pcls, tcls)
|
|
|
|
self.stats.append((correct_bboxes, pred[:, 4], pred[:, 5], cls.squeeze(-1))) # (conf, pcls, tcls)
|
|
|
|
|
|
|
|
|
|
|
|
# Save
|
|
|
|
# Save
|
|
|
|
if self.args.save_json:
|
|
|
|
if self.args.save_json:
|
|
|
@ -111,12 +113,10 @@ class DetectionValidator(BaseValidator):
|
|
|
|
if len(stats) and stats[0].any():
|
|
|
|
if len(stats) and stats[0].any():
|
|
|
|
self.metrics.process(*stats)
|
|
|
|
self.metrics.process(*stats)
|
|
|
|
self.nt_per_class = np.bincount(stats[-1].astype(int), minlength=self.nc) # number of targets per class
|
|
|
|
self.nt_per_class = np.bincount(stats[-1].astype(int), minlength=self.nc) # number of targets per class
|
|
|
|
fitness = {"fitness": self.metrics.fitness()}
|
|
|
|
return self.metrics.results_dict
|
|
|
|
metrics = dict(zip(self.metric_keys, self.metrics.mean_results()))
|
|
|
|
|
|
|
|
return {**metrics, **fitness}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def print_results(self):
|
|
|
|
def print_results(self):
|
|
|
|
pf = '%22s' + '%11i' * 2 + '%11.3g' * len(self.metric_keys) # print format
|
|
|
|
pf = '%22s' + '%11i' * 2 + '%11.3g' * len(self.metrics.keys) # print format
|
|
|
|
self.logger.info(pf % ("all", self.seen, self.nt_per_class.sum(), *self.metrics.mean_results()))
|
|
|
|
self.logger.info(pf % ("all", self.seen, self.nt_per_class.sum(), *self.metrics.mean_results()))
|
|
|
|
if self.nt_per_class.sum() == 0:
|
|
|
|
if self.nt_per_class.sum() == 0:
|
|
|
|
self.logger.warning(
|
|
|
|
self.logger.warning(
|
|
|
@ -166,18 +166,13 @@ class DetectionValidator(BaseValidator):
|
|
|
|
hyp=dict(self.args),
|
|
|
|
hyp=dict(self.args),
|
|
|
|
cache=False,
|
|
|
|
cache=False,
|
|
|
|
pad=0.5,
|
|
|
|
pad=0.5,
|
|
|
|
rect=self.args.rect,
|
|
|
|
rect=True,
|
|
|
|
workers=self.args.workers,
|
|
|
|
workers=self.args.workers,
|
|
|
|
prefix=colorstr(f'{self.args.mode}: '),
|
|
|
|
prefix=colorstr(f'{self.args.mode}: '),
|
|
|
|
shuffle=False,
|
|
|
|
shuffle=False,
|
|
|
|
seed=self.args.seed)[0] if self.args.v5loader else \
|
|
|
|
seed=self.args.seed)[0] if self.args.v5loader else \
|
|
|
|
build_dataloader(self.args, batch_size, img_path=dataset_path, stride=gs, mode="val")[0]
|
|
|
|
build_dataloader(self.args, batch_size, img_path=dataset_path, stride=gs, mode="val")[0]
|
|
|
|
|
|
|
|
|
|
|
|
# TODO: align with train loss metrics
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
|
|
|
def metric_keys(self):
|
|
|
|
|
|
|
|
return ["metrics/precision(B)", "metrics/recall(B)", "metrics/mAP50(B)", "metrics/mAP50-95(B)"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def plot_val_samples(self, batch, ni):
|
|
|
|
def plot_val_samples(self, batch, ni):
|
|
|
|
plot_images(batch["img"],
|
|
|
|
plot_images(batch["img"],
|
|
|
|
batch["batch_idx"],
|
|
|
|
batch["batch_idx"],
|
|
|
@ -226,7 +221,7 @@ class DetectionValidator(BaseValidator):
|
|
|
|
eval.evaluate()
|
|
|
|
eval.evaluate()
|
|
|
|
eval.accumulate()
|
|
|
|
eval.accumulate()
|
|
|
|
eval.summarize()
|
|
|
|
eval.summarize()
|
|
|
|
stats[self.metric_keys[-1]], stats[self.metric_keys[-2]] = eval.stats[:2] # update mAP50-95 and mAP50
|
|
|
|
stats[self.metrics.keys[-1]], stats[self.metrics.keys[-2]] = eval.stats[:2] # update mAP50-95 and mAP50
|
|
|
|
except Exception as e:
|
|
|
|
except Exception as e:
|
|
|
|
self.logger.warning(f'pycocotools unable to run: {e}')
|
|
|
|
self.logger.warning(f'pycocotools unable to run: {e}')
|
|
|
|
return stats
|
|
|
|
return stats
|
|
|
|