Datasets:
File size: 8,284 Bytes
74f7b5f | 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 | #!/usr/bin/env python3
"""Evaluate mAP and derive deployment confidence thresholds on the held-out split."""
from __future__ import annotations
import argparse
import json
from collections import defaultdict
from pathlib import Path
import numpy as np
from ultralytics import YOLO
from dataset_utils import label_for_image, split_images
def iou_one_to_many(box: np.ndarray, others: np.ndarray) -> np.ndarray:
if len(others) == 0:
return np.empty(0, dtype=np.float32)
x1 = np.maximum(box[0], others[:, 0])
y1 = np.maximum(box[1], others[:, 1])
x2 = np.minimum(box[2], others[:, 2])
y2 = np.minimum(box[3], others[:, 3])
intersection = np.maximum(0, x2 - x1) * np.maximum(0, y2 - y1)
area_a = max(0, box[2] - box[0]) * max(0, box[3] - box[1])
area_b = np.maximum(0, others[:, 2] - others[:, 0]) * np.maximum(0, others[:, 3] - others[:, 1])
return intersection / np.maximum(area_a + area_b - intersection, 1e-9)
def read_ground_truth(path: Path, width: int, height: int) -> dict[int, np.ndarray]:
rows: defaultdict[int, list[list[float]]] = defaultdict(list)
if path.is_file():
for line in path.read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
class_id_text, cx_text, cy_text, w_text, h_text = line.split()
class_id = int(class_id_text)
cx, cy, box_w, box_h = map(float, (cx_text, cy_text, w_text, h_text))
rows[class_id].append(
[
(cx - box_w / 2) * width,
(cy - box_h / 2) * height,
(cx + box_w / 2) * width,
(cy + box_h / 2) * height,
]
)
return {key: np.asarray(value, dtype=np.float32) for key, value in rows.items()}
def operational_metrics(
model: YOLO,
images: list[Path],
root: Path,
names: dict[int, str],
split: str,
imgsz: int,
device: str,
batch: int,
conf_floor: float,
match_iou: float,
gates: dict,
) -> dict:
predictions: defaultdict[int, list[tuple[float, int]]] = defaultdict(list)
gt_totals: CounterLike = defaultdict(int)
results = model.predict(
source=[str(path) for path in images],
imgsz=imgsz,
conf=conf_floor,
iou=0.7,
max_det=100,
device=device,
batch=batch,
stream=True,
verbose=False,
)
for image, result in zip(images, results, strict=True):
height, width = result.orig_shape
ground_truth = read_ground_truth(label_for_image(image, root, split), width, height)
for class_id, boxes in ground_truth.items():
gt_totals[class_id] += len(boxes)
matched = {class_id: np.zeros(len(boxes), dtype=bool) for class_id, boxes in ground_truth.items()}
if result.boxes is None:
continue
boxes = result.boxes.xyxy.cpu().numpy()
confidences = result.boxes.conf.cpu().numpy()
classes = result.boxes.cls.cpu().numpy().astype(int)
for index in np.argsort(-confidences):
class_id = int(classes[index])
candidates = ground_truth.get(class_id, np.empty((0, 4), dtype=np.float32))
overlaps = iou_one_to_many(boxes[index], candidates)
is_tp = 0
if len(overlaps):
order = np.argsort(-overlaps)
for gt_index in order:
if overlaps[gt_index] < match_iou:
break
if not matched[class_id][gt_index]:
matched[class_id][gt_index] = True
is_tp = 1
break
predictions[class_id].append((float(confidences[index]), is_tp))
per_class = {}
all_passed = True
for class_id, name in names.items():
ranked = sorted(predictions[class_id], reverse=True)
total_gt = int(gt_totals[class_id])
tp = 0
fp = 0
best = None
minimum_precision = float(gates[name]["min_precision"])
minimum_recall = float(gates[name]["min_recall"])
for confidence, is_tp in ranked:
tp += is_tp
fp += 1 - is_tp
precision = tp / max(1, tp + fp)
recall = tp / max(1, total_gt)
if precision >= minimum_precision and (best is None or recall > best["recall"]):
best = {
"confidence": confidence,
"precision": precision,
"recall": recall,
"tp": tp,
"fp": fp,
"fn": total_gt - tp,
}
if best is None:
best = {"confidence": 1.0, "precision": 1.0, "recall": 0.0, "tp": 0, "fp": 0, "fn": total_gt}
passed = best["precision"] >= minimum_precision and best["recall"] >= minimum_recall
all_passed &= passed
per_class[name] = best | {
"ground_truth_objects": total_gt,
"predictions_above_floor": len(ranked),
"minimum_precision": minimum_precision,
"minimum_recall": minimum_recall,
"passed": passed,
}
return {"gates_passed": all_passed, "per_class": per_class}
CounterLike = dict[int, int]
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--model", type=Path, required=True)
parser.add_argument("--data", type=Path, required=True)
parser.add_argument("--output-dir", type=Path, required=True)
parser.add_argument("--gates", type=Path, default=Path(__file__).with_name("quality_gates.json"))
parser.add_argument("--split", default="val", choices=("train", "val", "test"))
parser.add_argument("--device", default="0")
parser.add_argument("--imgsz", type=int, default=960)
parser.add_argument("--batch", type=int, default=16)
parser.add_argument("--workers", type=int, default=8)
parser.add_argument("--conf-floor", type=float, default=0.001)
parser.add_argument("--match-iou", type=float, default=0.5)
args = parser.parse_args()
args.output_dir.mkdir(parents=True, exist_ok=True)
gates = json.loads(args.gates.read_text(encoding="utf-8"))
images, root, names = split_images(args.data, args.split)
if not images:
raise SystemExit(f"no images found in {args.split} split")
model = YOLO(str(args.model.resolve()))
metrics = model.val(
data=str(args.data.resolve()),
split=args.split,
imgsz=args.imgsz,
batch=args.batch,
device=args.device,
workers=args.workers,
conf=args.conf_floor,
iou=0.7,
plots=True,
project=str(args.output_dir.parent.resolve()),
name=args.output_dir.name,
exist_ok=True,
verbose=True,
)
standard = {}
for class_id, name in names.items():
precision, recall, ap50, map_50_95 = (float(value) for value in metrics.class_result(class_id))
standard[name] = {
"precision_at_max_f1": precision,
"recall_at_max_f1": recall,
"ap50": ap50,
"map50_95": map_50_95,
}
(args.output_dir / "metrics.csv").write_text(metrics.to_csv(), encoding="utf-8")
operating = operational_metrics(
model, images, root, names, args.split, args.imgsz, args.device,
args.batch, args.conf_floor, args.match_iou, gates,
)
summary = {
"model": str(args.model.resolve()),
"data": str(args.data.resolve()),
"split": args.split,
"images": len(images),
"imgsz": args.imgsz,
"match_iou": args.match_iou,
"standard_ultralytics_metrics": standard,
"operational_quality_gate": operating,
"recommended_confidence_by_class": {
name: values["confidence"] for name, values in operating["per_class"].items()
},
}
text = json.dumps(summary, ensure_ascii=False, indent=2) + "\n"
(args.output_dir / "quality_gate.json").write_text(text, encoding="utf-8")
print(text, end="")
if not operating["gates_passed"]:
raise SystemExit("quality gate failed; do not start full-dataset inference")
if __name__ == "__main__":
main()
|