f7a262ac9a
Build & push images / images (push) Successful in 6m31s
apps/trainer (parking-trainer): inspect / train / evaluate / publish. Reads the wash collector's SQLite + crops read-only off its volume; time split (validation = newest slice); thin classes dropped; damped class weights; `features` mode (frozen ImageNet backbone, on-disk feature cache, seconds to retrain) and `finetune` mode (light augmentation). CPU-only torch from PyTorch's wheel index. ONNX export checked against the torch model; NO model file below the validation floor (exit 3, report still written); exit 2 = not enough labels. `evaluate` scores a shipped model on labels reviewed after training + the unlabelled pile; `publish` PUTs a version folder to a Gitea generic package. Light core deps; the `train` extra is heavy — CI syncs without it, torch tests skip. apps/vision: BodyTypeClassifier (bodytype.onnx + sidecar = the preprocessing contract: crop margin, input size, RGB 0-255, normalisation inside the graph) and RefinedVehicleDetector over YOLOX — refines only `car` or a class the classifier trained on, min-confidence, `detector_class` on the result; path set but no file = phase B off without an error; a broken file is a health detail. models/bodytype.version (tracked, empty) pins the published version the Dockerfile fetches at build (BuildKit secret; a pin that cannot be fetched fails the build). Verified: a trainer model gives identical probabilities inside the vision service; both images built and smoke-tested. Delivery: parking-trainer image in build-images.yml, the `trainer` compose profile on the collector stack (CPU, read-only data, TRAINER_OUT), commented TRAINER_OUT/PUBLISH_TOKEN in the wash-collector stack, .dockerignore for both Python contexts, trainer deps synced in CI. Wiki: bodytype-classifier-training rewritten as built (+ one fleet model not per site, secrets/access, where the crops live), opencv-anpr-service §Phase B, vision-review-outbox, vision-service-packaging, fleet-deployment-komodo, index, log. Claude-Session: https://claude.ai/code/session_01FWncR69HgGPuei1dLrW3cU
153 lines
5.4 KiB
Python
153 lines
5.4 KiB
Python
"""Metrics + the human-readable report. The owner reads this BEFORE anything ships; the
|
|
floor decision is made on these numbers. Pure Python, no torch."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import asdict, dataclass, field
|
|
from typing import Any
|
|
|
|
|
|
@dataclass
|
|
class ClassMetrics:
|
|
support: int
|
|
recall: float # of the true members, how many the model caught
|
|
precision: float # of the model's picks, how many were right
|
|
|
|
|
|
@dataclass
|
|
class Metrics:
|
|
n: int
|
|
accuracy: float
|
|
macro_recall: float
|
|
per_class: dict[str, ClassMetrics]
|
|
confusion: list[list[int]] # rows = true class, cols = predicted, in `classes` order
|
|
camera_agreement: float | None = None # how often the model equals the detector's class
|
|
onnx_agreement: float | None = None # exported graph vs the torch model, argmax
|
|
extra: dict[str, Any] = field(default_factory=dict)
|
|
|
|
def to_dict(self) -> dict[str, Any]:
|
|
return asdict(self)
|
|
|
|
|
|
def compute_metrics(
|
|
classes: tuple[str, ...] | list[str],
|
|
y_true: list[int],
|
|
y_pred: list[int],
|
|
camera: list[str] | None = None,
|
|
) -> Metrics:
|
|
k = len(classes)
|
|
conf = [[0] * k for _ in range(k)]
|
|
for t, p in zip(y_true, y_pred, strict=True):
|
|
conf[t][p] += 1
|
|
per: dict[str, ClassMetrics] = {}
|
|
recalls: list[float] = []
|
|
for i, c in enumerate(classes):
|
|
support = sum(conf[i])
|
|
tp = conf[i][i]
|
|
picked = sum(conf[r][i] for r in range(k))
|
|
recall = tp / support if support else 0.0
|
|
precision = tp / picked if picked else 0.0
|
|
per[c] = ClassMetrics(support=support, recall=recall, precision=precision)
|
|
if support:
|
|
recalls.append(recall)
|
|
n = len(y_true)
|
|
acc = sum(1 for t, p in zip(y_true, y_pred, strict=True) if t == p) / n if n else 0.0
|
|
agree = None
|
|
if camera is not None and n:
|
|
agree = sum(1 for p, cam in zip(y_pred, camera, strict=True) if classes[p] == cam) / n
|
|
return Metrics(
|
|
n=n,
|
|
accuracy=acc,
|
|
macro_recall=sum(recalls) / len(recalls) if recalls else 0.0,
|
|
per_class=per,
|
|
confusion=conf,
|
|
camera_agreement=agree,
|
|
)
|
|
|
|
|
|
def _pct(x: float | None) -> str:
|
|
return "—" if x is None else f"{x * 100:.1f} %"
|
|
|
|
|
|
def render_report(
|
|
*,
|
|
version: str,
|
|
trained_at: str,
|
|
mode: str,
|
|
backbone: str,
|
|
epochs: int,
|
|
classes: tuple[str, ...] | list[str],
|
|
train_counts: dict[str, int],
|
|
val_counts: dict[str, int],
|
|
dropped: dict[str, int],
|
|
missing_files: int,
|
|
weights: list[float],
|
|
metrics: Metrics,
|
|
min_accuracy: float,
|
|
written: bool,
|
|
notes: list[str] | None = None,
|
|
) -> str:
|
|
lines: list[str] = []
|
|
verdict = "MODEL WRITTEN" if written else "MODEL NOT WRITTEN — below the floor"
|
|
lines.append(f"# Body-type classifier {version}")
|
|
lines.append("")
|
|
lines.append(
|
|
f"**{verdict}** · validation accuracy {_pct(metrics.accuracy)} vs floor {_pct(min_accuracy)}"
|
|
)
|
|
lines.append("")
|
|
lines.append(f"- trained: {trained_at}")
|
|
lines.append(f"- mode: {mode} · backbone: {backbone} · epochs: {epochs}")
|
|
lines.append(f"- classes ({len(classes)}): {', '.join(classes)}")
|
|
lines.append(
|
|
f"- labels: {sum(train_counts.values())} train · {sum(val_counts.values())} validation "
|
|
"(validation = the NEWEST slice, by time seen)"
|
|
)
|
|
if dropped:
|
|
lines.append(
|
|
"- dropped (too few labels this run): "
|
|
+ ", ".join(f"{c} ({n})" for c, n in sorted(dropped.items()))
|
|
)
|
|
if missing_files:
|
|
lines.append(f"- labelled rows whose crop is missing on disk (skipped): {missing_files}")
|
|
lines.append("")
|
|
lines.append("## Validation")
|
|
lines.append("")
|
|
lines.append(f"- accuracy: {_pct(metrics.accuracy)} on {metrics.n} crops")
|
|
lines.append(f"- macro recall (each class counted equally): {_pct(metrics.macro_recall)}")
|
|
if metrics.camera_agreement is not None:
|
|
lines.append(
|
|
f"- agrees with the detector's coarse class: {_pct(metrics.camera_agreement)} "
|
|
"(informational — the detector only knows car/truck/bus/motorcycle)"
|
|
)
|
|
if metrics.onnx_agreement is not None:
|
|
lines.append(
|
|
f"- exported ONNX matches the trained model on validation: {_pct(metrics.onnx_agreement)}"
|
|
)
|
|
lines.append("")
|
|
lines.append("| class | train | val | recall | precision | loss weight |")
|
|
lines.append("|---|---:|---:|---:|---:|---:|")
|
|
for c, w in zip(classes, weights, strict=True):
|
|
m = metrics.per_class[c]
|
|
lines.append(
|
|
f"| {c} | {train_counts.get(c, 0)} | {m.support} | {_pct(m.recall) if m.support else '—'} | "
|
|
f"{_pct(m.precision) if m.support else '—'} | {w:.2f} |"
|
|
)
|
|
lines.append("")
|
|
lines.append("## Confusion (rows = reviewer's label, columns = model)")
|
|
lines.append("")
|
|
lines.append("| | " + " | ".join(classes) + " |")
|
|
lines.append("|---|" + "---:|" * len(classes))
|
|
for c, row in zip(classes, metrics.confusion, strict=True):
|
|
lines.append(f"| **{c}** | " + " | ".join(str(n) for n in row) + " |")
|
|
lines.append("")
|
|
if notes:
|
|
lines.append("## Notes")
|
|
lines.append("")
|
|
lines.extend(f"- {n}" for n in notes)
|
|
lines.append("")
|
|
lines.append(
|
|
"The flag on the booth records, it never bills: even a model that passes the floor is "
|
|
"advisory (the site threshold gates the flag)."
|
|
)
|
|
return "\n".join(lines) + "\n"
|