coredd-bench / src /coredd /perturbation.py
witrin's picture
Pool metrics by default and derive score and interval from the MC draws
7deba50 verified
Raw
History Blame Contribute Delete
4.12 kB
"""Monte-Carlo label-uncertainty interval, metric-agnostic.
Score and interval are both statistics of the same Monte Carlo run: each draw samples
an alpha and a gamma rate per stratum from their Beta posteriors, then keeps each
marked node with probability ``1 - alpha`` of its stratum and adds each unmarked node
with probability ``gamma`` of its stratum, and scores the metric against the perturbed
truth. The prediction is held fixed; only the truth moves. The score is the mean over
the draws, the band their [2.5%, 97.5%] quantile.
Aggregation over changes comes in two forms. Pooled (the default) scores the metric
once per draw over the nodes of every change concatenated into one population, so a
draw that strips a change of its defective nodes keeps the change in as negatives.
Per-case (``pooled=False``) scores each change separately and averages, dropping
changes where the metric is undefined (NaN).
This mirrors the evaluation notebook's ``theta_star`` with one change: the prediction is
the caller's real one, not a synthetic detector, so there is no skill grid -- one
prediction per change, one score per draw.
"""
from __future__ import annotations
from dataclasses import dataclass
import numpy as np
from coredd.metrics import is_rank
from coredd.noise import NoiseModel
@dataclass(frozen=True)
class Change:
"""One change reduced to its candidate nodes for scoring.
``y_true`` marks the released defective nodes, ``y_pred`` the predicted ones,
``scores`` the per-node prediction score (for rank metrics), and ``bin`` the
confidence stratum of each node.
"""
y_true: np.ndarray # bool (n,)
y_pred: np.ndarray # bool (n,)
scores: np.ndarray # float (n,)
bin: np.ndarray # int (n,)
def interval(
changes: list[Change],
metric,
noise: NoiseModel,
*,
draws: int = 10_000,
band: tuple[float, float] = (0.025, 0.975),
pooled: bool = True,
rng: np.random.Generator,
) -> tuple[float, tuple[float, float]]:
"""Return the point score and the label-uncertainty band over the changes."""
rank = is_rank(metric)
index = noise.index()
alpha_ab = noise.alpha_beta()
gamma_ab = noise.gamma_beta()
prepared = []
for change in changes:
rows = np.array([index[int(b)] for b in change.bin], dtype=int)
prediction = change.scores if rank else change.y_pred
prepared.append((change.y_true, prediction, rows))
def evaluate(y_true: np.ndarray, prediction: np.ndarray) -> float:
return float(metric(y_true, prediction))
def rates() -> tuple[np.ndarray, np.ndarray]:
alpha = rng.beta(alpha_ab[:, 0], alpha_ab[:, 1])
gamma = rng.beta(gamma_ab[:, 0], gamma_ab[:, 1])
return alpha, gamma
def perturb(y_true: np.ndarray, rows: np.ndarray,
alpha: np.ndarray, gamma: np.ndarray) -> np.ndarray:
keep = rng.random(y_true.size) > alpha[rows]
add = rng.random(y_true.size) < gamma[rows]
return np.where(y_true, keep, add)
agg = np.empty(draws, dtype=float)
if pooled:
y_true = np.concatenate([t for t, _, _ in prepared])
prediction = np.concatenate([p for _, p, _ in prepared])
rows = np.concatenate([r for _, _, r in prepared])
for m in range(draws):
alpha, gamma = rates()
agg[m] = evaluate(perturb(y_true, rows, alpha, gamma), prediction)
else:
for m in range(draws):
alpha, gamma = rates()
agg[m] = _mean([
evaluate(perturb(y_true, rows, alpha, gamma), prediction)
for y_true, prediction, rows in prepared
])
if np.isnan(agg).all():
return float("nan"), (float("nan"), float("nan"))
lo, hi = np.nanquantile(agg, band)
return float(np.nanmean(agg)), (float(lo), float(hi))
def _mean(values: list[float]) -> float:
"""Mean over changes, ignoring NaN (a metric undefined for a change is dropped)."""
array = np.asarray(values, dtype=float)
if np.isnan(array).all():
return float("nan")
return float(np.nanmean(array))