DmitryPlant's picture
Deploy local
e04bbc2 verified
Raw History Blame Contribute Delete
5.19 kB
"""Precision / recall by greedy nearest-centroid matching.
Two matchers, chosen per request:
``relative_radius`` — tolerance is ``frac x R_gt``, where ``R_gt`` is the radius
of a circle with the same area as that ground-truth object. Scale-invariant,
which this dataset needs: slices run 263x157 to 3648x2736 and the median object
radius is 159 px.
``fixed_px`` — a flat pixel tolerance. Kept so clients still sending
``match_radius`` keep working, but it is the wrong default here: only 5% of
objects are smaller than 20 px, so for the other 95% the tolerance is narrower
than the object it is meant to land inside. The shipped model reads F1 0.065 at
20 px while scoring mask mAP50 0.71 on the very same predictions.
``ml/bench.py`` imports this module, so a benchmark number and a number on
screen are the same number.
"""
from math import hypot, pi
from typing import Any, Iterable, Literal, Sequence
import cv2
import numpy as np
Center = tuple[float, float]
MatcherKind = Literal["fixed_px", "relative_radius"]
MATCHER_FIXED_PX: MatcherKind = "fixed_px"
MATCHER_RELATIVE_RADIUS: MatcherKind = "relative_radius"
#: Tolerance = this x the ground-truth object's own equivalent radius. 0.5 means
#: "the detection landed on that object". Mirrored in ``frontend/lib/eval.ts``.
MATCH_FRAC_DEFAULT = 0.5
#: Legacy flat tolerance, in pixels. Mis-calibrated here — see the module docstring.
MATCH_RADIUS_DEFAULT_PX = 20.0
#: A polygon needs three points before it encloses any area.
MIN_CONTOUR_POINTS = 3
def equivalent_radius(contour: Sequence[Sequence[float]]) -> float:
"""Radius of a circle with the same area as the polygon."""
c = np.asarray(contour, dtype=np.float32).reshape(-1, 1, 2)
return float((max(cv2.contourArea(c), 1.0) / pi) ** 0.5)
def _greedy_match(
pred_centers: Sequence[Center],
targets: Sequence[tuple[Center, float]],
) -> int:
"""Count predictions landing within their nearest free target's tolerance.
Nearest-first; each target is consumed at most once, so two detections on
one object score one hit and one false positive.
"""
used = [False] * len(targets)
tp = 0
for px, py in pred_centers:
best_j, best_d = -1, float("inf")
for j, ((gx, gy), tol) in enumerate(targets):
if used[j]:
continue
d = hypot(px - gx, py - gy)
if d <= tol and d < best_d:
best_j, best_d = j, d
if best_j >= 0:
used[best_j] = True
tp += 1
return tp
def _summarize(tp: int, n_pred: int, n_gt: int) -> dict[str, float | int]:
"""Counts plus precision / recall, with no vacuous perfect scores.
A run that predicted nothing used to report precision 1.0, and a run scored
against empty ground truth used to report recall 1.0 — both read as success
on screen. An undefined ratio is reported as 0.0, matching how ``bench.py``
aggregates a fold. Only genuinely empty-vs-empty stays 1.0.
"""
fp = n_pred - tp
fn = n_gt - tp
if n_pred == 0 and n_gt == 0:
return {"tp": 0, "fp": 0, "fn": 0, "precision": 1.0, "recall": 1.0}
precision = tp / (tp + fp) if (tp + fp) else 0.0
recall = tp / (tp + fn) if (tp + fn) else 0.0
return {
"tp": tp, "fp": fp, "fn": fn,
"precision": round(precision, 4),
"recall": round(recall, 4),
}
def score(
run_centers: Iterable[Center],
gt_centers: Iterable[Center],
match_radius: float,
) -> dict[str, float | int]:
"""Flat-pixel tolerance. Legacy — prefer :func:`score_relative`."""
preds = [tuple(c) for c in run_centers]
targets = [(tuple(c), match_radius) for c in gt_centers]
return _summarize(_greedy_match(preds, targets), len(preds), len(targets))
def score_relative(
run_centers: Iterable[Center],
gt_bundles: Iterable[dict[str, Any]],
frac: float = MATCH_FRAC_DEFAULT,
) -> dict[str, float | int]:
"""Tolerance scales with each ground-truth object's own size.
Ground-truth entries without a real polygon are dropped rather than matched
at an invented tolerance, so they count in neither the numerator nor the
denominator.
"""
preds = [tuple(c) for c in run_centers]
targets = [
(tuple(b["center"]), equivalent_radius(b["contour"]) * frac)
for b in gt_bundles
if len(b.get("contour") or []) >= MIN_CONTOUR_POINTS
]
return _summarize(_greedy_match(preds, targets), len(preds), len(targets))
def match(
run_centers: Iterable[Center],
gt_bundles: Iterable[dict[str, Any]],
kind: MatcherKind,
param: float,
) -> dict[str, float | int]:
"""Dispatch to the requested matcher. ``param`` is a fraction or pixels."""
bundles = list(gt_bundles)
if kind == MATCHER_RELATIVE_RADIUS:
return score_relative(run_centers, bundles, frac=param)
if kind == MATCHER_FIXED_PX:
return score(run_centers, [b["center"] for b in bundles], match_radius=param)
raise ValueError(f"unknown matcher kind: {kind!r}")