"""Statistics used in the paper, each in its own small function. 1. tray_bootstrap - confidence intervals that respect trays. Crops from one tray were photographed together, so they are not independent. Instead of resampling single crops we resample whole TRAYS (with replacement, inside each class so every class stays present), add up the per-tray counts and recompute the score. We repeat this 2,000 times and take the 2.5% and 97.5% points. The same resamples can be reused for two models, which makes their difference "paired". 2. mcnemar_exact - did two models differ on the crops where exactly one of them was right? 3. holm - correction when many comparisons are made at once. """ import numpy as np from scipy.stats import binomtest from .metrics import f1_from_counts SEED = 509 N_RESAMPLES = 2000 class TrayBootstrap: """Prepare the tray structure once, then compute scores and intervals for any predictions.""" def __init__(self, y_true, trays, classes, n_resamples=N_RESAMPLES, seed=SEED, n_classes=8): self.y = np.asarray(y_true) self.n_classes = n_classes names = sorted(set(trays)) index = {t: i for i, t in enumerate(names)} self.tray_of_crop = np.array([index[t] for t in trays]) self.n_trays = len(names) # which class does each tray belong to? (every tray holds one class) tray_class = np.zeros(self.n_trays, dtype=int) for crop_tray, c in zip(self.tray_of_crop, np.asarray(classes)): tray_class[crop_tray] = c # one weight vector per resample: how many times each tray is drawn rng = np.random.default_rng(seed) groups = [np.where(tray_class == c)[0] for c in np.unique(tray_class)] self.weights = np.zeros((n_resamples, self.n_trays)) for b in range(n_resamples): for g in groups: self.weights[b] += np.bincount(rng.choice(g, len(g)), minlength=self.n_trays) def _per_tray_counts(self, y_pred): """tp, fp, fn per tray and class: arrays of shape (n_trays, n_classes).""" y_pred = np.asarray(y_pred) shape = (self.n_trays, self.n_classes) tp, fp, fn = np.zeros(shape), np.zeros(shape), np.zeros(shape) for c in range(self.n_classes): np.add.at(tp[:, c], self.tray_of_crop, (y_pred == c) & (self.y == c)) np.add.at(fp[:, c], self.tray_of_crop, (y_pred == c) & (self.y != c)) np.add.at(fn[:, c], self.tray_of_crop, (y_pred != c) & (self.y == c)) return tp, fp, fn def resampled_scores(self, y_pred, score): """`score` is a function (tp, fp, fn) -> number. Returns (point estimate, array over resamples).""" tp, fp, fn = self._per_tray_counts(y_pred) point = score(tp.sum(0), fp.sum(0), fn.sum(0)) boot = np.array([score(w @ tp, w @ fp, w @ fn) for w in self.weights]) return point, boot def interval(self, boot): """95% interval from the resampled scores.""" return tuple(np.percentile(boot, [2.5, 97.5])) def macro_f1_score(tp, fp, fn): return float(f1_from_counts(tp, fp, fn).mean()) def hd_f1_score(tp, fp, fn): return float(f1_from_counts(tp, fp, fn)[6]) # class 6 = HD def mcnemar_exact(y_true, pred_a, pred_b): """Exact McNemar test. Looks only at crops where exactly one model is correct.""" y_true, a, b = np.asarray(y_true), np.asarray(pred_a), np.asarray(pred_b) a_only = int(np.sum((a == y_true) & (b != y_true))) b_only = int(np.sum((a != y_true) & (b == y_true))) if a_only + b_only == 0: return 1.0 return float(binomtest(a_only, a_only + b_only, 0.5).pvalue) def holm(p_values): """Holm's correction: sort the p-values, multiply the smallest by n, the next by n-1, ..., keep them increasing.""" p = np.asarray(p_values, dtype=float) order = np.argsort(p) adjusted = np.empty_like(p) running = 0.0 for rank, i in enumerate(order): running = max(running, (len(p) - rank) * p[i]) adjusted[i] = min(1.0, running) return adjusted