File size: 19,021 Bytes
24aaa76 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 | """Statistics of eval_spec.json: S01 cluster bootstrap, S02 paired bootstrap, S03 paired permutation test, S04 Holm,
S05 rare-event rule, M14 quantiles, M26 calibration.
All resampling works on per-cluster sums: one resample draws K clusters with replacement (a multinomial count vector), and a
ratio metric is (sum of drawn numerators) / (sum of drawn denominators), the ratio estimator of Bisani and Ney 2004 (not a mean of
cluster rates). The weight chunks are a deterministic function of (seed, K, chunk start): two arms scored on the same set with
the same sorted cluster list see the SAME resamples, which is what the paired tests need.
"""
import math
import numpy as np
SEED_BASE = 20261121
B_DEFAULT = 10000
CHUNK = 500
MIN_EVENTS = 30 # S05: a rate with a denominator below this is reported as counts only
COVERAGE_GRID = np.round(np.arange(0.05, 1.0001, 0.05), 2)
def _trap(y, x):
"""Trapezoid rule (numpy 2 renamed trapz to trapezoid)."""
f = getattr(np, "trapezoid", None) or np.trapz
return float(f(y, x))
def weight_chunks(K, B=B_DEFAULT, seed=SEED_BASE, chunk=CHUNK):
"""Yields (start, counts) with counts of shape (n, K): multinomial cluster counts of n resamples."""
p = np.full(K, 1.0 / K)
for c0 in range(0, B, chunk):
n = min(chunk, B - c0)
rng = np.random.default_rng([seed, K, c0])
yield c0, rng.multinomial(K, p, size=n).astype(np.float64)
_WCACHE = {}
def weights_full(K, B=B_DEFAULT, seed=SEED_BASE, max_elems=1.0e8):
"""All B resamples as one float32 (B, K) matrix when it is small enough (kept for the last (K, B, seed) asked for),
else None (callers then iterate weight_chunks). Same numbers as the chunks."""
key = (K, B, seed)
if key in _WCACHE:
return _WCACHE[key]
if B * K > max_elems:
return None
W = np.concatenate([w for _, w in weight_chunks(K, B, seed)]).astype(np.float32)
_WCACHE.clear()
_WCACHE[key] = W
return W
def boot_matmul(idx, M, K, B=B_DEFAULT, seed=SEED_BASE):
"""Resampled sums: (W[:, idx] @ M) for the (len(idx), c) matrix M of per-cluster columns. Returns (B, c) float64."""
M = np.asarray(M, dtype=np.float64)
idx = np.asarray(idx, dtype=np.int64)
out = np.zeros((B, M.shape[1]), dtype=np.float64)
if len(idx) == 0:
return out
W = weights_full(K, B, seed)
if W is not None:
return W[:, idx].astype(np.float64) @ M
for c0, Wc in weight_chunks(K, B, seed):
out[c0:c0 + Wc.shape[0]] = Wc[:, idx] @ M
return out
def ratio_ci(num_reps, den_reps, level=95.0):
"""Percentile interval of the ratio replicates; invalid replicates (zero denominator) are dropped."""
with np.errstate(divide="ignore", invalid="ignore"):
r = num_reps / den_reps
r = r[np.isfinite(r)]
if len(r) < 20:
return None, None, int(len(r))
a = (100.0 - level) / 2.0
lo, hi = np.percentile(r, [a, 100.0 - a])
return float(lo), float(hi), int(len(r))
def paired_ratio_difference(num_x, den_x, num_y, den_y, B=B_DEFAULT, seed=SEED_BASE):
"""Paired cluster bootstrap of X against Y (S02). Inputs: per-cluster numerators and denominators of the SAME sorted cluster
list, one pair of arrays per system. Returns dict with the point estimates, the replicate arrays d_rel = CER_X/CER_Y - 1
and d_abs = CER_X - CER_Y, the 95% percentile intervals and the one-sided bootstrap p-value for 'X is better' (d_rel < 0)."""
num_x, den_x, num_y, den_y = [np.asarray(a, dtype=np.float64) for a in (num_x, den_x, num_y, den_y)]
K = len(num_x)
cer_x, cer_y = num_x.sum() / den_x.sum(), num_y.sum() / den_y.sum()
rel, ab = [], []
for c0, W in weight_chunks(K, B, seed):
with np.errstate(divide="ignore", invalid="ignore"):
cx = (W @ num_x) / (W @ den_x)
cy = (W @ num_y) / (W @ den_y)
rel.append(cx / cy - 1.0)
ab.append(cx - cy)
rel = np.concatenate(rel)
ab = np.concatenate(ab)
ok = np.isfinite(rel)
relv = rel[ok]
res = {"kind": "form_bootstrap", "cer_x": float(cer_x), "cer_y": float(cer_y), "d_rel": float(cer_x / cer_y - 1.0) if cer_y > 0 else None,
"d_abs": float(cer_x - cer_y), "B": int(B), "valid_replicates": int(ok.sum()), "K": int(K)}
if len(relv) >= 20:
res["d_rel_ci95"] = [float(np.percentile(relv, 2.5)), float(np.percentile(relv, 97.5))]
res["d_abs_ci95"] = [float(np.percentile(ab[ok], 2.5)), float(np.percentile(ab[ok], 97.5))]
res["p_better"] = float((1 + np.sum(relv >= 0.0)) / (len(relv) + 1)) # H0: d >= 0 (X not better)
res["prob_improvement"] = float(np.mean(relv < 0.0))
res["_rel_reps"] = relv
else:
res["d_rel_ci95"] = res["d_abs_ci95"] = res["p_better"] = res["prob_improvement"] = None
res["_rel_reps"] = relv
return res
def _seed_mean_reps(nums, dens, W):
"""Mean over seeds of the resampled per-seed pooled CER. nums, dens: lists with one per-cluster array per seed."""
acc = 0.0
with np.errstate(divide="ignore", invalid="ignore"):
for n_, d_ in zip(nums, dens):
acc = acc + (W @ n_) / (W @ d_)
return acc / len(nums)
def paired_seed_mean_difference(nums_x, dens_x, nums_y, dens_y, B=B_DEFAULT, seed=SEED_BASE):
"""Form-bootstrap comparison of seed-averaged CERs (clarification G1 style: percentile interval, no seed variance). Each argument is
a list with one per-cluster array per seed (one or two seeds). The same cluster resample is applied to every seed of both arms.
Returns the same keys as paired_ratio_difference."""
nums_x = [np.asarray(a, dtype=np.float64) for a in nums_x]
dens_x = [np.asarray(a, dtype=np.float64) for a in dens_x]
nums_y = [np.asarray(a, dtype=np.float64) for a in nums_y]
dens_y = [np.asarray(a, dtype=np.float64) for a in dens_y]
K = len(nums_x[0])
cx = float(np.mean([n.sum() / d.sum() for n, d in zip(nums_x, dens_x)]))
cy = float(np.mean([n.sum() / d.sum() for n, d in zip(nums_y, dens_y)]))
rel, ab = [], []
for c0, W in weight_chunks(K, B, seed):
mx, my = _seed_mean_reps(nums_x, dens_x, W), _seed_mean_reps(nums_y, dens_y, W)
with np.errstate(divide="ignore", invalid="ignore"):
rel.append(mx / my - 1.0)
ab.append(mx - my)
rel, ab = np.concatenate(rel), np.concatenate(ab)
ok = np.isfinite(rel)
res = {"kind": "form_bootstrap_seed_mean", "cer_x": cx, "cer_y": cy, "d_rel": cx / cy - 1.0 if cy > 0 else None, "d_abs": cx - cy, "B": int(B),
"valid_replicates": int(ok.sum()), "K": int(K), "n_seeds_x": len(nums_x), "n_seeds_y": len(nums_y)}
if ok.sum() >= 20:
res["d_rel_ci95"] = [float(np.percentile(rel[ok], 2.5)), float(np.percentile(rel[ok], 97.5))]
res["d_abs_ci95"] = [float(np.percentile(ab[ok], 2.5)), float(np.percentile(ab[ok], 97.5))]
res["p_better"] = float((1 + np.sum(rel[ok] >= 0.0)) / (ok.sum() + 1))
res["prob_improvement"] = float(np.mean(rel[ok] < 0.0))
else:
res["d_rel_ci95"] = res["d_abs_ci95"] = res["p_better"] = res["prob_improvement"] = None
res["_rel_reps"] = rel[ok]
return res
def paired_two_seed_t(nums_x, dens_x, nums_y, dens_y, B=B_DEFAULT, seed=SEED_BASE):
"""Version 3 section 1 as written, for two arms that both have at least two seeds (amendment 3.3 D4).
d = mean_X CER / mean_Y CER - 1 over seeds. Variance of d = form-bootstrap variance of d on seed-averaged values (the same cluster
resample for all seeds) + s^2 x (1/n_X + 1/n_Y), s = pooled relative seed standard deviation of the two arms on this endpoint
(sample SD of the per-seed CERs divided by their mean, pooled with weights n - 1). Intervals use the t quantile with the pooled
seed degrees of freedom (n_X - 1) + (n_Y - 1). One-sided p for 'X is better' (H0: d >= 0) = T_df(d / SE). The seed term is applied as
written in the rule (without the ratio factor of the delta method)."""
from scipy import stats as sps
base = paired_seed_mean_difference(nums_x, dens_x, nums_y, dens_y, B=B, seed=seed)
cers_x = [float(n.sum() / d.sum()) for n, d in zip(nums_x, dens_x)]
cers_y = [float(n.sum() / d.sum()) for n, d in zip(nums_y, dens_y)]
nx, ny = len(cers_x), len(cers_y)
reps = base["_rel_reps"]
var_boot = float(np.var(reps, ddof=1)) if len(reps) > 2 else float("nan")
rsd2, dfs = [], []
for c in (cers_x, cers_y):
if len(c) >= 2 and np.mean(c) > 0:
rsd2.append(float(np.var(c, ddof=1) / np.mean(c) ** 2))
dfs.append(len(c) - 1)
df = int(sum(dfs))
s2 = float(sum(r * d for r, d in zip(rsd2, dfs)) / df) if df else 0.0
var_tot = var_boot + s2 * (1.0 / nx + 1.0 / ny)
se = float(np.sqrt(var_tot)) if np.isfinite(var_tot) and var_tot > 0 else None
d = base["d_rel"]
res = {k: base[k] for k in ("cer_x", "cer_y", "d_rel", "d_abs", "B", "K")}
res.update({"kind": "two_seed_t", "n_seeds_x": nx, "n_seeds_y": ny, "seed_cers_x": cers_x, "seed_cers_y": cers_y, "var_bootstrap": var_boot,
"relative_seed_sd_squared_pooled": s2, "df": df, "se": se, "label": "form bootstrap plus seed variance, t quantile (version 3 section 1)"})
if se is not None and df > 0 and d is not None:
t975 = float(sps.t.ppf(0.975, df))
res["t_quantile_97_5"] = t975
res["d_rel_ci95"] = [d - t975 * se, d + t975 * se]
res["p_better"] = float(sps.t.cdf(d / se, df))
res["prob_improvement"] = None
res["d_abs"] = base["d_abs"]
res["d_abs_ci95"] = None
else:
res["d_rel_ci95"] = res["p_better"] = res["d_abs_ci95"] = res["prob_improvement"] = None
res["_rel_reps"] = None
return res
def holm_bound_t(d, se, df, rank, m, alpha=0.05):
"""Holm-adjusted upper bound with the t quantile (version 3 section 1): d + t_{1 - alpha/(m+1-k), df} x SE."""
from scipy import stats as sps
return float(d + sps.t.ppf(1.0 - alpha / (m + 1 - rank), df) * se)
def permutation_pvalue(num_x, num_y, den, R=B_DEFAULT, seed=SEED_BASE):
"""S03: approximate randomisation at cluster level. In each round every cluster swaps the two systems' outputs with
probability 0.5; the statistic is the difference of the two pooled error rates. Two-sided p = (1 + #{|d*| >= |d|}) / (R + 1).
The reference length (den) is the same for both systems."""
num_x, num_y, den = [np.asarray(a, dtype=np.float64) for a in (num_x, num_y, den)]
K = len(num_x)
diff = num_x - num_y
tot = den.sum()
obs = abs(diff.sum() / tot)
hits = 0
done = 0
for c0 in range(0, R, CHUNK):
n = min(CHUNK, R - c0)
rng = np.random.default_rng([seed, K, c0, 1])
signs = rng.integers(0, 2, size=(n, K)) * 2 - 1
stat = np.abs(signs @ diff) / tot
hits += int(np.sum(stat >= obs - 1e-15))
done += n
return float((1 + hits) / (done + 1))
def holm_adjust(pvalues, alpha=0.05):
"""S04 Holm step-down. pvalues: dict name -> p. Returns dict name -> {p, rank, threshold, reject}: order the p-values,
find the smallest k with p(k) > alpha/(m+1-k); H(1)..H(k-1) are rejected, the rest are not."""
names = sorted(pvalues, key=lambda k: (pvalues[k], k))
m = len(names)
out = {}
stopped = False
for k, name in enumerate(names, start=1):
thr = alpha / (m + 1 - k)
rej = (not stopped) and pvalues[name] <= thr
if not rej:
stopped = True
out[name] = {"p": pvalues[name], "rank": k, "threshold": thr, "reject": bool(rej), "m": m}
return out
def holm_bound(rel_reps, rank, m, alpha=0.05):
"""Upper bound of d reported for an endpoint at Holm rank k: the (1 - alpha/(m+1-k)) percentile of the replicates (S04)."""
q = 100.0 * (1.0 - alpha / (m + 1 - rank))
return float(np.percentile(rel_reps, q))
def rare_event(k, n):
"""S05: below MIN_EVENTS the rate is reported as 'k of n' only."""
return n < MIN_EVENTS
# ---- weighted quantiles (M14) --------------------------------------------------------------------------------------
def quantiles_ci(values, cl_idx, K, qs=(0.5, 0.9, 0.99), B=B_DEFAULT, seed=SEED_BASE, chunk=200):
"""Point estimates (numpy 'linear') and 95% cluster-bootstrap intervals (weighted step quantile) of the quantiles of
per-crop values. cl_idx: cluster index of each crop."""
v = np.asarray(values, dtype=np.float64)
n = len(v)
if n == 0:
return {}
cl_idx = np.asarray(cl_idx, dtype=np.int64)
order = np.argsort(v, kind="stable")
vs = v[order]
cs = cl_idx[order]
reps = {q: [] for q in qs}
for c0, W in weight_chunks(K, B, seed, chunk=chunk):
w = W[:, cs]
cum = np.cumsum(w, axis=1)
tot = cum[:, -1]
for q in qs:
tgt = q * tot
pos = (cum >= tgt[:, None]).argmax(axis=1)
reps[q].append(vs[pos])
out = {}
for q in qs:
r = np.concatenate(reps[q])
out["q%g" % q] = {"value": float(np.quantile(v, q)), "lo": float(np.percentile(r, 2.5)),
"hi": float(np.percentile(r, 97.5))}
return out
# ---- calibration (M26) ---------------------------------------------------------------------------------------------
def ece_equal_mass(conf, correct, w=None, bins=15):
conf = np.asarray(conf, dtype=np.float64)
correct = np.asarray(correct, dtype=np.float64)
n = len(conf)
if n == 0:
return float("nan")
w = np.ones(n) if w is None else np.asarray(w, dtype=np.float64)
order = np.argsort(conf, kind="stable")
ws, cs, ac = w[order], conf[order], correct[order]
cum = np.cumsum(ws)
tot = cum[-1]
mid = (cum - ws / 2.0) / tot
b = np.minimum(np.floor(bins * mid).astype(int), bins - 1)
sw_c = np.bincount(b, weights=ws * cs, minlength=bins)
sw_a = np.bincount(b, weights=ws * ac, minlength=bins)
return float(np.abs(sw_a - sw_c).sum() / tot)
def ece_equal_width(conf, correct, w=None, bins=15):
conf = np.asarray(conf, dtype=np.float64)
correct = np.asarray(correct, dtype=np.float64)
n = len(conf)
if n == 0:
return float("nan")
w = np.ones(n) if w is None else np.asarray(w, dtype=np.float64)
b = np.minimum(np.floor(np.clip(conf, 0, 1) * bins).astype(int), bins - 1)
sw_c = np.bincount(b, weights=w * conf, minlength=bins)
sw_a = np.bincount(b, weights=w * correct, minlength=bins)
return float(np.abs(sw_a - sw_c).sum() / w.sum())
def risk_coverage(conf, dist, reflen, w=None, grid=COVERAGE_GRID):
"""Risk-coverage curve: keep the top share c of crops by confidence (descending, stable) and report the pooled CER of the
kept crops. Returns (risks at grid, area under the curve by the trapezoid rule over the grid)."""
conf = np.asarray(conf, dtype=np.float64)
n = len(conf)
w = np.ones(n) if w is None else np.asarray(w, dtype=np.float64)
order = np.argsort(-conf, kind="stable")
ws = w[order]
cumw = np.cumsum(ws)
cd = np.cumsum(ws * np.asarray(dist, dtype=np.float64)[order])
cr = np.cumsum(ws * np.asarray(reflen, dtype=np.float64)[order])
pos = np.minimum(np.searchsorted(cumw, grid * cumw[-1] - 1e-12, side="left"), n - 1)
with np.errstate(divide="ignore", invalid="ignore"):
risk = cd[pos] / cr[pos]
return risk, _trap(risk, grid)
def calibration_point(conf, correct, correct_ed1, dist, reflen):
conf = np.asarray(conf, dtype=np.float64)
risk, aurc = risk_coverage(conf, dist, reflen)
return {
"n": int(len(conf)),
"ece_equal_mass_15": ece_equal_mass(conf, correct),
"ece_equal_width_15": ece_equal_width(conf, correct),
"ed_ece_1": ece_equal_mass(conf, correct_ed1),
"brier": float(np.mean((conf - np.asarray(correct, dtype=np.float64)) ** 2)),
"mean_conf": float(conf.mean()), "accuracy": float(np.mean(correct)),
"risk_coverage": {"coverage": [float(c) for c in COVERAGE_GRID], "cer": [None if not np.isfinite(r) else float(r) for r in risk]},
"aurc": aurc,
}
def calibration_ci(conf, correct, dist, reflen, cl_idx, K, B=2000, seed=SEED_BASE, chunk=100):
"""Cluster-bootstrap intervals of ECE (equal mass, equal width) and of the area under the risk-coverage curve.
B is smaller than for the ratio metrics (2,000 against 10,000) because each replicate needs a sort-free but crop-level
pass; this is a stated deviation from S01."""
conf = np.asarray(conf, dtype=np.float64)
correct = np.asarray(correct, dtype=np.float64)
dist = np.asarray(dist, dtype=np.float64)
reflen = np.asarray(reflen, dtype=np.float64)
cl_idx = np.asarray(cl_idx, dtype=np.int64)
n = len(conf)
o_asc = np.argsort(conf, kind="stable")
o_desc = np.argsort(-conf, kind="stable")
bins = 15
ece_m, ece_w, aurc = [], [], []
for c0, W in weight_chunks(K, B, seed, chunk=chunk):
w = W[:, cl_idx]
r = w.shape[0]
tot = w.sum(axis=1)
# equal-width bins
bw = np.minimum(np.floor(np.clip(conf, 0, 1) * bins).astype(int), bins - 1)
idx_w = (np.arange(r)[:, None] * bins + bw[None, :]).ravel()
sc = np.bincount(idx_w, weights=(w * conf).ravel(), minlength=r * bins).reshape(r, bins)
sa = np.bincount(idx_w, weights=(w * correct).ravel(), minlength=r * bins).reshape(r, bins)
ece_w.append(np.abs(sa - sc).sum(axis=1) / tot)
# equal-mass bins
ws = w[:, o_asc]
cum = np.cumsum(ws, axis=1)
mid = (cum - ws / 2.0) / tot[:, None]
bm = np.minimum(np.floor(bins * mid).astype(int), bins - 1)
idx_m = (np.arange(r)[:, None] * bins + bm).ravel()
sc = np.bincount(idx_m, weights=(ws * conf[o_asc][None, :]).ravel(), minlength=r * bins).reshape(r, bins)
sa = np.bincount(idx_m, weights=(ws * correct[o_asc][None, :]).ravel(), minlength=r * bins).reshape(r, bins)
ece_m.append(np.abs(sa - sc).sum(axis=1) / tot)
# risk-coverage area
wd = w[:, o_desc]
cumw = np.cumsum(wd, axis=1)
cd = np.cumsum(wd * dist[o_desc][None, :], axis=1)
cr = np.cumsum(wd * reflen[o_desc][None, :], axis=1)
for k in range(r):
pos = np.minimum(np.searchsorted(cumw[k], COVERAGE_GRID * cumw[k, -1] - 1e-12, side="left"), n - 1)
with np.errstate(divide="ignore", invalid="ignore"):
risk = cd[k, pos] / cr[k, pos]
aurc.append(_trap(risk, COVERAGE_GRID))
out = {}
for name, arr in (("ece_equal_mass_15", np.concatenate(ece_m)), ("ece_equal_width_15", np.concatenate(ece_w)),
("aurc", np.asarray(aurc))):
arr = arr[np.isfinite(arr)]
out[name] = {"lo": float(np.percentile(arr, 2.5)), "hi": float(np.percentile(arr, 97.5)), "B": int(B)} if len(arr) >= 20 else None
return out
def safe_div(a, b):
return a / b if b else float("nan")
def isnan(x):
return x is None or (isinstance(x, float) and math.isnan(x))
|