""" eval_detector.py — score a trained YOLO detector against held-out floors. Reports the measures in plain English: • Units detected = recall (TP / (TP+FN)) • False positives = predicted boxes with no real unit • False negatives = real units missed • Precision = TP / (TP+FP) • Correct location = mean IoU of matched boxes + mAP@0.5 / mAP@0.5:0.95 • Type correctly classified = accuracy on matched boxes (trivial while 1 type) A prediction matches a ground-truth box when IoU >= --iou-match (default 0.5). Usage: python eval_detector.py --weights runs_hvac/yolo_hvac/weights/best.pt \ --dataset dataset_typed/dataset.yaml [--conf 0.25] [--imgsz 1280] """ from __future__ import annotations import argparse from pathlib import Path import yaml from PIL import Image from ultralytics import YOLO Image.MAX_IMAGE_PIXELS = None def iou(a, b): ax1, ay1, ax2, ay2 = a bx1, by1, bx2, by2 = b ix1, iy1 = max(ax1, bx1), max(ay1, by1) ix2, iy2 = min(ax2, bx2), min(ay2, by2) iw, ih = max(0, ix2 - ix1), max(0, iy2 - iy1) inter = iw * ih if inter == 0: return 0.0 union = (ax2 - ax1) * (ay2 - ay1) + (bx2 - bx1) * (by2 - by1) - inter return inter / union if union else 0.0 def load_gt(label_path: Path, W: int, H: int): boxes = [] if not label_path.exists(): return boxes for line in label_path.read_text(encoding="utf-8").splitlines(): parts = line.split() if len(parts) != 5: continue cls, xc, yc, w, h = parts xc, yc, w, h = float(xc) * W, float(yc) * H, float(w) * W, float(h) * H boxes.append((int(cls), [xc - w / 2, yc - h / 2, xc + w / 2, yc + h / 2])) return boxes def main() -> None: ap = argparse.ArgumentParser(description="Evaluate YOLO detector on held-out floors") ap.add_argument("--weights", type=Path, required=True) ap.add_argument("--dataset", type=Path, default=Path("dataset_typed/dataset.yaml")) ap.add_argument("--conf", type=float, default=0.25) ap.add_argument("--imgsz", type=int, default=1280) ap.add_argument("--iou-match", type=float, default=0.5) args = ap.parse_args() cfg = yaml.safe_load(args.dataset.read_text(encoding="utf-8")) root = Path(cfg["path"]) val_img_dir = root / cfg["val"] val_lbl_dir = root / cfg["val"].replace("images", "labels") names = cfg["names"] model = YOLO(str(args.weights)) # ── headline metrics via ultralytics (mAP, P, R) ───────────────────────── print("=" * 64) print(" Ultralytics validation (standard detection metrics)") print("=" * 64) metrics = model.val(data=str(args.dataset), imgsz=args.imgsz, conf=args.conf, verbose=False) box = metrics.box print(f" Precision (mean): {box.mp:.3f}") print(f" Recall (mean): {box.mr:.3f} <- 'units detected' rate") print(f" mAP@0.5: {box.map50:.3f}") print(f" mAP@0.5:0.95: {box.map:.3f} <- localization tightness") # ── per-floor TP/FP/FN + mean IoU (plain-English breakdown) ────────────── print("\n" + "=" * 64) print(f" Per-floor detection (IoU match >= {args.iou_match}, conf >= {args.conf})") print("=" * 64) tot_tp = tot_fp = tot_fn = 0 iou_sum = 0.0 type_ok = 0 print(f" {'floor image':46s} {'TP':>3} {'FP':>3} {'FN':>3} {'meanIoU':>8}") for img_path in sorted(val_img_dir.glob("*.jpg")): with Image.open(img_path) as im: W, H = im.size gt = load_gt(val_lbl_dir / f"{img_path.stem}.txt", W, H) res = model(str(img_path), imgsz=args.imgsz, conf=args.conf, verbose=False)[0] preds = [] for b in res.boxes: xy = b.xyxy[0].tolist() preds.append((int(b.cls[0]), xy)) matched_gt = set() tp = fp = 0 floor_iou = 0.0 for pcls, pbox in preds: best_j, best_iou = -1, args.iou_match for j, (gcls, gbox) in enumerate(gt): if j in matched_gt: continue v = iou(pbox, gbox) if v >= best_iou: best_j, best_iou = j, v if best_j >= 0: tp += 1 matched_gt.add(best_j) floor_iou += best_iou if gt[best_j][0] == pcls: type_ok += 1 else: fp += 1 fn = len(gt) - len(matched_gt) tot_tp += tp; tot_fp += fp; tot_fn += fn; iou_sum += floor_iou miou = floor_iou / tp if tp else 0.0 print(f" {img_path.stem[:46]:46s} {tp:>3} {fp:>3} {fn:>3} {miou:>8.3f}") prec = tot_tp / (tot_tp + tot_fp) if (tot_tp + tot_fp) else 0.0 rec = tot_tp / (tot_tp + tot_fn) if (tot_tp + tot_fn) else 0.0 f1 = 2 * prec * rec / (prec + rec) if (prec + rec) else 0.0 print(" " + "-" * 62) print(f" TOTAL TP={tot_tp} FP={tot_fp} FN={tot_fn}") print(f" Units detected (recall): {rec:.1%}") print(f" Precision (1 - false-pos): {prec:.1%}") print(f" F1: {f1:.3f}") print(f" Correct location (mean IoU): {iou_sum / tot_tp:.3f}" if tot_tp else " Correct location: n/a (no true positives)") print(f" Type correctly classified: " f"{type_ok}/{tot_tp} = {type_ok/tot_tp:.1%}" if tot_tp else " Type acc: n/a") if len(names) == 1: print(" (type acc is trivially 100% while only one unit type exists)") if __name__ == "__main__": main()