Download code/train_ball.py from d9993r/CRICKET: direct link, hf CLI and curl.
- Browser
- Download file 7.69 kB
-
https://huggingface.co/datasets/d9993r/CRICKET/resolve/main/code/train_ball.py
- Command line
-
hf download hf://datasets/d9993r/CRICKET/code/train_ball.py
-
curl -L -o train_ball.py https://huggingface.co/datasets/d9993r/CRICKET/resolve/main/code/train_ball.py
7.69 kB
| #!/usr/bin/env python3 | |
| """Fine-tune a cricket ball detector from reviewer clicks (standard section 9.2). | |
| python code/train_ball.py export # results/training/ball_dataset (YOLO format) | |
| python code/train_ball.py train --epochs 40 # -> models/ball_cricket_vN.pt | |
| python code/train_ball.py eval # stock vs fine-tuned on held-out frames | |
| then set models.det_weights in code/config.yaml to the new file and rerun analyze (--force) | |
| CPU training of the nano model on a few hundred frames takes roughly an hour with | |
| 16 threads; a free Colab/Kaggle GPU takes minutes (see code/docs/train_ball_on_colab.md). | |
| The split is by SOURCE VIDEO so the evaluation is not fooled by near-duplicate frames.""" | |
| import argparse | |
| import hashlib | |
| import json | |
| import shutil | |
| import sys | |
| from pathlib import Path | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| from common import absp, load_config, rel, write_json # noqa: E402 | |
| from review import load_review # noqa: E402 | |
| def labelled_frames(R): | |
| man = {m["id"]: m for m in json.load(open(R / "labeling" / "manifest.json"))} | |
| latest = {} | |
| for r in sorted((r for r in load_review(R) if r["kind"] == "ball_label"), key=lambda r: r["created_at"]): | |
| latest[r["field"]] = r["value"] | |
| return [(man[k], v) for k, v in latest.items() if k in man] | |
| def split_of(source_id): | |
| return "val" if int(hashlib.md5(source_id.encode()).hexdigest(), 16) % 5 == 0 else "train" | |
| def export(cfg): | |
| R = cfg["_paths"]["results"] | |
| rows = labelled_frames(R) | |
| if len(rows) < 20: | |
| raise SystemExit(f"only {len(rows)} labelled frames; label at least ~100 in the Ball labels tab first") | |
| out = R / "training" / "ball_dataset" | |
| shutil.rmtree(out, ignore_errors=True) | |
| key = "source_id" | |
| if len({m["source_id"] for m, _ in rows}) < 2: # one video only: hold out whole deliveries instead | |
| key = "delivery_id" | |
| print(" ! all labels come from one video: splitting by delivery (weaker test; label a second video)") | |
| splits = {m[key]: split_of(m[key]) for m, _ in rows} | |
| if "val" not in splits.values(): # make sure something is held out | |
| biggest = max(set(splits), key=lambda s: sum(m[key] == s for m, _ in rows)) | |
| splits[biggest] = "val" | |
| if "train" not in splits.values() and len(splits) > 1: | |
| splits[sorted(splits)[0]] = "train" | |
| counts = {"train": [0, 0], "val": [0, 0]} | |
| for m, v in rows: | |
| sp = splits[m[key]] | |
| (out / "images" / sp).mkdir(parents=True, exist_ok=True) | |
| (out / "labels" / sp).mkdir(parents=True, exist_ok=True) | |
| shutil.copy(absp(m["image"]), out / "images" / sp / f"{m['id']}.jpg") | |
| W, H = m["size"] | |
| lines = "" | |
| if v.get("visible") is not False: | |
| r = float(v.get("r") or max(5.0, 0.008 * W)) | |
| lines = f"0 {v['x'] / W:.6f} {v['y'] / H:.6f} {2 * r / W:.6f} {2 * r / H:.6f}\n" | |
| counts[sp][0] += 1 | |
| else: | |
| counts[sp][1] += 1 | |
| (out / "labels" / sp / f"{m['id']}.txt").write_text(lines) | |
| (out / "data.yaml").write_text(f"path: {out.resolve()}\ntrain: images/train\nval: images/val\nnames:\n 0: ball\n") | |
| write_json(out / "split.json", {"by": key, "sources": splits, | |
| "counts": {k: {"with_ball": a, "no_ball": b} for k, (a, b) in counts.items()}}) | |
| print(f"dataset -> {rel(out)} train {counts['train']} val {counts['val']} ([with ball, no ball])") | |
| return out | |
| def train(cfg, epochs, imgsz, device): | |
| from ultralytics import YOLO | |
| from vision import pick_device | |
| R, M = cfg["_paths"]["results"], cfg["_paths"]["models"] | |
| data = R / "training" / "ball_dataset" / "data.yaml" | |
| if not data.exists(): | |
| export(cfg) | |
| dev = pick_device(device)[0] if device == "auto" else device | |
| base = M / "yolo11n.pt" | |
| model = YOLO(str(base if base.exists() else "yolo11n.pt")) | |
| res = model.train(data=str(data), epochs=epochs, imgsz=imgsz, device=dev, batch=8 if dev == "cpu" else 16, | |
| project=str(R / "training" / "runs"), name="ball", exist_ok=False, patience=15, verbose=False) | |
| best = Path(res.save_dir) / "weights" / "best.pt" | |
| n = 1 + len(list(M.glob("ball_cricket_v*.pt"))) | |
| dst = M / f"ball_cricket_v{n}.pt" | |
| shutil.copy(best, dst) | |
| print(f"saved {rel(dst)}. Next: python code/train_ball.py eval --weights {rel(dst)}") | |
| return dst | |
| def _detect(model, img, imgsz, classes, conf): | |
| r = model.predict(img, imgsz=imgsz, conf=conf, classes=classes, verbose=False, device="cpu")[0] | |
| if r.boxes is None or len(r.boxes) == 0: | |
| return [] | |
| return [((b[0] + b[2]) / 2, (b[1] + b[3]) / 2, float(c)) for b, c in zip(r.boxes.xyxy.cpu().numpy(), r.boxes.conf.cpu().numpy())] | |
| def evaluate(cfg, weights, imgsz, conf, all_frames=False): | |
| import cv2 | |
| import numpy as np | |
| from ultralytics import YOLO | |
| R, M = cfg["_paths"]["results"], cfg["_paths"]["models"] | |
| rows = labelled_frames(R) | |
| sp = json.load(open(R / "training" / "ball_dataset" / "split.json"))["sources"] if not all_frames and \ | |
| (R / "training" / "ball_dataset" / "split.json").exists() else None | |
| by = json.load(open(R / "training" / "ball_dataset" / "split.json")).get("by", "source_id") if sp else "source_id" | |
| rows = [(m, v) for m, v in rows if all_frames or sp is None or sp.get(m[by]) == "val"] | |
| models = {"stock_coco": (YOLO(str(M / "yolo11n.pt")), [32])} | |
| if weights: | |
| fm = YOLO(str(weights)) | |
| models["finetuned"] = (fm, [i for i, n in fm.names.items() if str(n).lower() == "ball" or str(n).lower().endswith(" ball")] or None) | |
| out = {"frames": len(rows), "with_ball": sum(v.get("visible") is not False for _, v in rows), | |
| "weights": str(weights) if weights else None, "imgsz": imgsz, "conf": conf} | |
| for name, (model, classes) in models.items(): | |
| tp = fn = fp = 0; errs = [] | |
| for m, v in rows: | |
| img = cv2.imread(str(absp(m["image"]))) | |
| dets = _detect(model, img, imgsz, classes, conf) | |
| if v.get("visible") is False: | |
| fp += len(dets); continue | |
| r = float(v.get("r") or max(5.0, 0.008 * m["size"][0])) | |
| d = [np.hypot(x - v["x"], y - v["y"]) for x, y, _ in dets] | |
| if d and min(d) <= max(2 * r, 12): | |
| tp += 1; errs.append(min(d)); fp += len(dets) - 1 | |
| else: | |
| fn += 1; fp += len(dets) | |
| out[name] = {"recall": round(tp / max(1, tp + fn), 3), "precision": round(tp / max(1, tp + fp), 3), | |
| "mean_center_error_px": round(float(np.mean(errs)), 1) if errs else None, "tp": tp, "fn": fn, "fp": fp} | |
| write_json(R / "qa" / "ball_eval.json", out) | |
| print(json.dumps(out, indent=2)) | |
| return out | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("cmd", choices=["export", "train", "eval"]) | |
| ap.add_argument("--epochs", type=int, default=40) | |
| ap.add_argument("--imgsz", type=int, default=960) | |
| ap.add_argument("--device", default="auto") | |
| ap.add_argument("--weights") | |
| ap.add_argument("--conf", type=float, default=0.15) | |
| ap.add_argument("--all-frames", action="store_true", help="evaluate on every labelled frame, not just val") | |
| a = ap.parse_args() | |
| cfg = load_config() | |
| if a.cmd == "export": | |
| export(cfg) | |
| elif a.cmd == "train": | |
| train(cfg, a.epochs, a.imgsz, a.device) | |
| else: | |
| w = a.weights or (sorted(cfg["_paths"]["models"].glob("ball_cricket_v*.pt")) or [None])[-1] | |
| evaluate(cfg, absp(w) if w and not Path(w).is_absolute() else w, a.imgsz, a.conf, a.all_frames) | |
| if __name__ == "__main__": | |
| main() | |