"""Offline paired ranking diagnosis. Oracle thresholds are never deployment policy.""" import numpy as np def curve(scores, positives, negatives): scores = np.asarray(scores) if scores.ndim != 1 or not np.isfinite(scores).all() or not len(scores): raise ValueError("Finite nonempty score vector required") masks = dict(positives, **negatives) if not positives or not negatives or len(masks) != len(positives) + len(negatives): raise ValueError("Distinct positive and negative cohort names required") for mask in masks.values(): if mask.dtype != bool or mask.shape != scores.shape: raise ValueError("Aligned boolean cohort masks required") fg = np.logical_or.reduce(list(positives.values())) bg = np.zeros_like(fg) for mask in negatives.values(): if np.any(mask & (fg | bg)): raise ValueError("Negative cohorts must be disjoint from paint and each other") bg |= mask known = fg | bg if not known.any(): raise ValueError("No reviewed support") idx = np.flatnonzero(known) idx = idx[np.argsort(-scores[idx], kind="stable")] sorted_scores = scores[idx] ends = np.r_[np.flatnonzero(sorted_scores[:-1] != sorted_scores[1:]), len(idx) - 1] return { "thresholds": np.r_[np.inf, sorted_scores[ends].astype(np.float64)], "counts": {k: np.r_[0, np.cumsum(m[idx], dtype=np.int64)[ends]] for k, m in masks.items()}, "support": {k: int(m.sum()) for k, m in masks.items()}, "positive_names": list(positives), "negative_names": list(negatives), } def point(c, index): t = float(c["thresholds"][index]) return dict( threshold=None if np.isinf(t) else t, counts={k: int(v[index]) for k, v in c["counts"].items()}, rates={ k: float(v[index] / c["support"][k]) if c["support"][k] else None for k, v in c["counts"].items() }, ) def at_threshold(c, threshold): if not np.isfinite(threshold): raise ValueError("Finite threshold required") return point(c, int(np.flatnonzero(c["thresholds"] >= threshold)[-1])) def matched(c, budgets): if set(budgets) != set(c["negative_names"]): raise ValueError("One explicit budget for every negative cohort required") valid = np.ones(len(c["thresholds"]), dtype=bool) for name, budget in budgets.items(): if ( isinstance(budget, bool) or not isinstance(budget, (int, np.integer)) or not 0 <= budget <= c["support"][name] ): raise ValueError("Integer false-positive budgets within support required") valid &= c["counts"][name] <= budget return point(c, int(np.flatnonzero(valid)[-1])) def ranking( c, positive, negative_names, grid=(0, 0.0001, 0.0005, 0.001, 0.002, 0.005, 0.01, 0.02, 0.05, 0.1, 1), ): tp = c["counts"][positive] fp = sum(c["counts"][n] for n in negative_names) npos = c["support"][positive] nneg = sum(c["support"][n] for n in negative_names) if not npos or not nneg: return dict(positives=npos, negatives=nneg, ap=None, auc=None, points=[]) recall = tp / npos fpr = fp / nneg precision = np.divide(tp, tp + fp, out=np.ones(len(tp), dtype=float), where=tp + fp > 0) ap = float(np.sum(np.diff(recall) * precision[1:])) auc = float(np.sum(np.diff(fpr) * (recall[1:] + recall[:-1]) * 0.5)) points = [] for rate in grid: budget = int(np.floor(rate * nneg)) i = int(np.flatnonzero(fp <= budget)[-1]) points.append( dict( budget=budget, fp=int(fp[i]), tp=int(tp[i]), precision=float(precision[i]), recall=float(recall[i]), ) ) return dict(positives=npos, negatives=nneg, ap=ap, auc=auc, points=points) def paired(old, new, positives, negatives): if np.shape(old) != np.shape(new): raise ValueError("Paired score shapes differ") curves = {k: curve(s, positives, negatives) for k, s in [("old", old), ("new", new)]} assert curves["old"]["support"] == curves["new"]["support"] fixed = {k: at_threshold(c, 0) for k, c in curves.items()} budgets = {k: fixed["old"]["counts"][k] for k in negatives} oracle = {k: matched(c, budgets) for k, c in curves.items()} summaries = {} for origin, c in curves.items(): summaries[origin] = {} for name in positives: summaries[origin][name] = {} for part, names in [(k, [k]) for k in negatives] + [("combined", list(negatives))]: summary = ranking(c, name, names) if name not in ["overall", "weak"] or part != "combined": summary.pop("points") summaries[origin][name][part] = summary return dict( support=curves["old"]["support"], fixed=fixed, budgets=budgets, oracle=oracle, ranking=summaries, )