Download models/detector_metrics.py from ZenoNing/ConsDrive: direct link, hf CLI and curl.
- Browser
- Download file 7.69 kB
-
https://huggingface.co/ZenoNing/ConsDrive/resolve/main/models/detector_metrics.py
- Command line
-
hf download hf://ZenoNing/ConsDrive/models/detector_metrics.py
-
curl -L -o detector_metrics.py https://huggingface.co/ZenoNing/ConsDrive/resolve/main/models/detector_metrics.py
7.69 kB
| """Detection metrics in the terms of the tracker acceptance criteria (BEV, per range bin). | |
| Predictions are matched greedily by score to the nearest unmatched labelled box within | |
| 1.5 m + 5 % of its range. Recall is reported against two ground truths: "positive" (bank-visible | |
| and hit by the lidar, what the detector is trained on) and "bank" (bank-visible only, what the | |
| oracle stage-3 model was given). A false positive is a prediction within range that matches no | |
| labelled box at all, so detections of uncertain/ignored boxes are not counted against it. | |
| """ | |
| import numpy as np | |
| from dataloader.detection_data import CAMERA_X, is_positive | |
| from dataloader.detection_labels import ( | |
| OBJ_BANK_VISIBLE, OBJ_CLASS, OBJ_SPEED, OBJ_X, OBJ_Y, OBJ_YAW, | |
| ) | |
| RANGE_BINS = ((0, 10), (10, 20), (20, 30), (30, 40), (40, 50)) | |
| CLASS_NAMES = ("car", "walker", "static") | |
| def match(pred_xy, pred_score, gt_xy, gt_range): | |
| """Greedy score-ordered matching; returns gt index per prediction (-1 unmatched).""" | |
| assigned = np.full(len(pred_xy), -1, dtype=np.int64) | |
| if len(pred_xy) == 0 or len(gt_xy) == 0: | |
| return assigned | |
| dist = np.linalg.norm(pred_xy[:, None] - gt_xy[None], axis=-1) | |
| gate = 1.5 + 0.05 * gt_range | |
| taken = np.zeros(len(gt_xy), dtype=bool) | |
| for p in np.argsort(-pred_score): | |
| d = np.where(taken | (dist[p] > gate), np.inf, dist[p]) | |
| g = int(np.argmin(d)) | |
| if np.isfinite(d[g]): | |
| assigned[p] = g | |
| taken[g] = True | |
| return assigned | |
| class DetectionMetrics: | |
| def __init__(self, max_range=50.0, thresholds=(0.2, 0.3, 0.4, 0.5)): | |
| self.max_range = max_range | |
| self.thresholds = thresholds | |
| self.frames = 0 | |
| self.gt = [] # per labelled box: range, class, positive, bank, speed, matched-at-threshold..., errors | |
| self.fp = {t: 0 for t in thresholds} | |
| self.errors = [] # matched positives at the 0.3 threshold: range, class, pos err, lon, lat, vel err, speed, yaw err | |
| def add(self, gt_rows, det): | |
| """gt_rows [N, OBJ_DIM] numpy; det: decoded dict of tensors for one image.""" | |
| self.frames += 1 | |
| det = {k: v.detach().float().cpu().numpy() for k, v in det.items()} | |
| gt_xy = gt_rows[:, [OBJ_X, OBJ_Y]].astype(np.float64) | |
| gt_range = np.hypot(gt_xy[:, 0] - CAMERA_X, gt_xy[:, 1]) | |
| pos = is_positive(gt_rows, self.max_range) | |
| bank = (gt_rows[:, OBJ_BANK_VISIBLE] > 0.5) & (gt_range <= self.max_range) | |
| pred_xy = np.stack((det["x"], det["y"]), -1).astype(np.float64) | |
| pred_range = np.hypot(pred_xy[:, 0] - CAMERA_X, pred_xy[:, 1]) | |
| matched = {} | |
| for t in self.thresholds: | |
| keep = det["score"] >= t | |
| a = match(pred_xy[keep], det["score"][keep], gt_xy, gt_range) | |
| hit = np.zeros(len(gt_rows), dtype=bool) | |
| hit[a[a >= 0]] = True | |
| matched[t] = hit | |
| self.fp[t] += int(((a < 0) & (pred_range[keep] <= self.max_range)).sum()) | |
| if t == 0.3: | |
| idx = np.flatnonzero(keep) | |
| for p, g in zip(idx[a >= 0], a[a >= 0]): | |
| if not pos[g]: | |
| continue | |
| d = pred_xy[p] - gt_xy[g] | |
| ray = gt_xy[g] - (CAMERA_X, 0.0) | |
| ray /= max(np.linalg.norm(ray), 1e-6) | |
| gv = gt_rows[g, OBJ_SPEED] * np.array((np.cos(gt_rows[g, OBJ_YAW]), np.sin(gt_rows[g, OBJ_YAW]))) | |
| yaw_err = abs((det["yaw"][p] - gt_rows[g, OBJ_YAW] + np.pi) % (2 * np.pi) - np.pi) | |
| self.errors.append((gt_range[g], gt_rows[g, OBJ_CLASS], np.linalg.norm(d), d @ ray, | |
| abs(d[0] * -ray[1] + d[1] * ray[0]), | |
| np.linalg.norm((det["vx"][p], det["vy"][p]) - gv), gt_rows[g, OBJ_SPEED], | |
| yaw_err, det["depth_sigma"][p], int(det["cls"][p] == gt_rows[g, OBJ_CLASS]))) | |
| for g in range(len(gt_rows)): | |
| self.gt.append((gt_range[g], gt_rows[g, OBJ_CLASS], pos[g], bank[g], gt_rows[g, OBJ_SPEED], | |
| *[matched[t][g] for t in self.thresholds])) | |
| def summary(self): | |
| gt = np.asarray(self.gt, dtype=np.float64).reshape(-1, 5 + len(self.thresholds)) | |
| err = np.asarray(self.errors, dtype=np.float64).reshape(-1, 10) | |
| out = dict(frames=self.frames, fp_per_frame={t: self.fp[t] / max(self.frames, 1) for t in self.thresholds}) | |
| k30 = 5 + self.thresholds.index(0.3) | |
| for c, name in enumerate(CLASS_NAMES): | |
| rows = {} | |
| for lo, hi in RANGE_BINS: | |
| sel = (gt[:, 1] == c) & (gt[:, 0] >= lo) & (gt[:, 0] < hi) | |
| p, b = sel & (gt[:, 2] > 0), sel & (gt[:, 3] > 0) | |
| e = err[(err[:, 1] == c) & (err[:, 0] >= lo) & (err[:, 0] < hi)] | |
| rows[f"{lo}-{hi}"] = dict( | |
| n_pos=int(p.sum()), recall_pos=float(gt[p, k30].mean()) if p.any() else None, | |
| recall_bank=float(gt[b, k30].mean()) if b.any() else None, | |
| pos_err_med=float(np.median(e[:, 2])) if len(e) else None, | |
| pos_err_p90=float(np.percentile(e[:, 2], 90)) if len(e) else None, | |
| lon_err_med=float(np.median(np.abs(e[:, 3]))) if len(e) else None, | |
| lat_err_med=float(np.median(e[:, 4])) if len(e) else None, | |
| vel_err_med=float(np.median(e[:, 5])) if len(e) else None, | |
| cls_acc=float(e[:, 9].mean()) if len(e) else None) | |
| p50 = (gt[:, 1] == c) & (gt[:, 2] > 0) | |
| rows["recall_pos_0-50_by_threshold"] = { | |
| t: float(gt[p50, 5 + i].mean()) if p50.any() else None for i, t in enumerate(self.thresholds)} | |
| out[name] = rows | |
| cars = err[err[:, 1] == 0] | |
| if len(cars): | |
| speed_bins = {} | |
| for lo, hi in ((0, 0.5), (0.5, 5), (5, 10), (10, 20)): | |
| s = cars[(cars[:, 6] >= lo) & (cars[:, 6] < hi)] | |
| if len(s): | |
| speed_bins[f"{lo}-{hi}"] = dict(n=len(s), vel_err_med=float(np.median(s[:, 5])), | |
| vel_err_p90=float(np.percentile(s[:, 5], 90)), | |
| yaw_err_med_deg=float(np.degrees(np.median(s[:, 7])))) | |
| out["car_velocity_by_speed"] = speed_bins | |
| return out | |
| def format_summary(s): | |
| lines = [f"frames {s['frames']} FP/frame " + " ".join(f"@{t}: {v:.3f}" for t, v in s["fp_per_frame"].items())] | |
| for name in CLASS_NAMES: | |
| lines.append(f"{name:7s} range n_pos rec_pos rec_bank err_med err_p90 lon lat vel_err cls_acc") | |
| for key, r in s[name].items(): | |
| if key.startswith("recall_pos_0-50"): | |
| lines.append(" recall_pos 0-50 by threshold: " + " ".join( | |
| f"@{t}: {v:.3f}" for t, v in r.items() if v is not None)) | |
| continue | |
| f = lambda v, w=6, p=2: (f"{v:{w}.{p}f}" if v is not None else " " * (w - 1) + "-") # noqa: E731 | |
| lines.append(f" {key:6s} {r['n_pos']:6d} {f(r['recall_pos'], 6, 3)} {f(r['recall_bank'], 6, 3)} " | |
| f"{f(r['pos_err_med'])} {f(r['pos_err_p90'])} {f(r['lon_err_med'], 5)} " | |
| f"{f(r['lat_err_med'], 5)} {f(r['vel_err_med'])} {f(r['cls_acc'], 5)}") | |
| for key, r in s.get("car_velocity_by_speed", {}).items(): | |
| lines.append(f"car speed {key:7s} n={r['n']:6d} vel_err med {r['vel_err_med']:.2f} p90 {r['vel_err_p90']:.2f}" | |
| f" yaw_err med {r['yaw_err_med_deg']:.1f} deg") | |
| return "\n".join(lines) | |