Buckets:
| """J2 kill-condition baseline: detect-then-count (YOLOv8n, ultralytics) on the SAME pseudo-slide split as train_j2.py. | |
| Counts = detections per class with confidence >= a per-class threshold chosen on val to minimise count MAE (the | |
| fairest possible counting rule for a detector). Evaluated with train_j2.evaluate (identical metrics and decision | |
| rules, positive threshold calibrated the same way). Reports single-thread CPU latency at the same image size, so the | |
| comparison is at matched latency, as Addendum J requires. | |
| Env: as train_j2.py (DATA, OUT, SPLIT, HOLDOUT_DEVICE, SEED, EPOCHS, BS) + IMGSZ (default 1536). | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import os | |
| import sys | |
| import time | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| import train_j2 as T # noqa: E402 (shares split, pseudo-slides, evaluate) | |
| IMGSZ = int(os.environ.get("IMGSZ", "1536")) | |
| def write_yolo(rows, P, root, split): | |
| (root / split / "images").mkdir(parents=True, exist_ok=True); (root / split / "labels").mkdir(parents=True, exist_ok=True) | |
| for r in rows.itertuples(): | |
| src = T.DATA / "images" / r.image | |
| dst = root / split / "images" / r.image | |
| if not dst.exists(): | |
| os.symlink(src.resolve(), dst) | |
| with open(root / split / "labels" / (Path(r.image).stem + ".txt"), "w") as f: | |
| for c, x, y, bw, bh in P.get(r.image, []): | |
| f.write(f"{int(c)} {x / r.w:.6f} {y / r.h:.6f} {bw / r.w:.6f} {bh / r.h:.6f}\n") | |
| def det_counts(model, rows, conf_min=0.05): | |
| out = [] | |
| for r in rows.itertuples(): | |
| res = model.predict(str(T.DATA / "images" / r.image), imgsz=IMGSZ, conf=conf_min, max_det=3000, verbose=False)[0] | |
| out.append((r.image, res.boxes.cls.cpu().numpy().astype(int), res.boxes.conf.cpu().numpy())) | |
| return out | |
| def counts_at(dets, thr): | |
| return pd.DataFrame([(im, float(((c == 0) & (s >= thr[0])).sum()), float(((c == 1) & (s >= thr[1])).sum())) | |
| for im, c, s in dets], columns=["image", "pred_parasite", "pred_wbc"]) | |
| def main(): | |
| from ultralytics import YOLO | |
| M = T.pseudo_slides(pd.read_csv(T.DATA / "manifest.csv")) | |
| M = M[(M.n_parasite + M.n_wbc) > 0].copy() # unannotated images excluded (see train_j2.py) | |
| Pt = pd.read_csv(T.DATA / "points.csv") | |
| P = {k: g[["cls", "x", "y", "bw", "bh"]].to_numpy(np.float32) for k, g in Pt.groupby("image")} | |
| tr, va, te = T.make_split(M) | |
| root = T.OUT / "yolo_data" | |
| for rows, sp in ((tr, "train"), (va, "val")): | |
| write_yolo(rows, P, root, sp) | |
| (root / "data.yaml").write_text(f"path: {root.resolve()}\ntrain: train/images\nval: val/images\nnames: ['parasite', 'wbc']\n") | |
| model = YOLO("yolov8n.pt") | |
| model.train(data=str(root / "data.yaml"), epochs=T.EPOCHS, imgsz=IMGSZ, batch=T.BS, seed=T.SEED, max_det=3000, | |
| project=str(T.OUT / "yolo_runs"), name=f"s{T.SEED}", exist_ok=True, verbose=False) | |
| dv = det_counts(model, va) | |
| grid = np.round(np.arange(0.05, 0.96, 0.05), 2) | |
| best = {} | |
| for k, col in ((0, "n_parasite"), (1, "n_wbc")): | |
| errs = [] | |
| for g in grid: | |
| C = counts_at(dv, (g, g)).merge(va[["image", col]], on="image") | |
| errs.append(float((C.iloc[:, 1 + k] - C[col]).abs().mean())) | |
| best[k] = float(grid[int(np.argmin(errs))]) | |
| pv = counts_at(dv, (best[0], best[1])).merge(va[["image", "n_parasite"]], on="image") | |
| neg = pv[pv.n_parasite == 0].pred_parasite | |
| t_pos = float(np.quantile(neg, 0.95)) + 1e-6 if len(neg) >= 10 else 0.5 | |
| D, m = T.evaluate(counts_at(det_counts(model, te), (best[0], best[1])), te, t_pos) | |
| tag = f"det_{T.SPLIT}{('_' + T.HOLD.replace(' ', '_')) if T.SPLIT == 'device' else ''}_s{T.SEED}" | |
| D.to_csv(T.OUT / f"{tag}_per_image.csv", index=False) | |
| import torch | |
| torch.set_num_threads(1) | |
| cpu = YOLO(model.ckpt_path if getattr(model, "ckpt_path", None) else "yolov8n.pt") | |
| x = str(T.DATA / "images" / te.image.iloc[0]) | |
| cpu.predict(x, imgsz=IMGSZ, device="cpu", verbose=False); t0 = time.time() | |
| for _ in range(3): | |
| cpu.predict(x, imgsz=IMGSZ, device="cpu", verbose=False) | |
| lat = (time.time() - t0) / 3 | |
| info = {"split": T.SPLIT, "holdout_device": T.HOLD, "seed": T.SEED, "conf_thresholds": best, "t_pos": t_pos, | |
| "test": m, "cpu_1thread_s_per_image": round(lat, 3), "params": sum(p.numel() for p in model.model.parameters())} | |
| (T.OUT / f"{tag}.json").write_text(json.dumps(info, indent=1)) | |
| print("DET_RESULT " + json.dumps({"tag": tag, **m, "cpu_s": info["cpu_1thread_s_per_image"]}), flush=True) | |
| if __name__ == "__main__": | |
| main() | |
Xet Storage Details
- Size:
- 4.69 kB
- Xet hash:
- e85ee7a3517de2200a95ed0846a982228e8755e4e23e611bf2abb7bebc33de50
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.