"""EJ1 · 41 · AUC con IC por bootstrap de conglomerados (2.000 réplicas, semilla 20261022) con numpy, para las unidades que guarda 40. Imagen con pandas/numpy (sin duckdb). Reescribe salidas/40_validaciones.json añadiendo ic95, ic_bonferroni6 y veredicto (regla X2, §6b).""" import json, glob import numpy as np, pyarrow.parquet as pq SEM = 20261022; B = 2000 def auc_w(sc_sorted_groups, y, w): # sc ordenado; grupos de empates g (índice de grupo por unidad, creciente) pass R = json.load(open('/w/salidas/40_validaciones.json')) def prep(path): t = pq.read_table(path).to_pandas() o = np.argsort(t['sc'].to_numpy(), kind='mergesort'); sc = t['sc'].to_numpy()[o]; y = t['y'].to_numpy()[o] _, g = np.unique(sc, return_inverse=True) cl_codes, cl = np.unique(t['cl'].to_numpy()[o], return_inverse=True) return y, g, cl, len(cl_codes) def auc_pesos(y, g, w): ng = g.max() + 1 w1 = np.bincount(g, weights=w * (y == 1), minlength=ng); w0 = np.bincount(g, weights=w * (y == 0), minlength=ng) W1, W0 = w1.sum(), w0.sum() if W1 == 0 or W0 == 0: return np.nan below0 = np.cumsum(w0) - w0 return float((w1 * (below0 + 0.5 * w0)).sum() / (W1 * W0)) def bootstrap(path): y, g, cl, K = prep(path) a0 = auc_pesos(y, g, np.ones(len(y))) rnd = np.random.default_rng(SEM); vals = [] for _ in range(B): cnt = np.bincount(rnd.integers(0, K, K), minlength=K) v = auc_pesos(y, g, cnt[cl].astype(float)) if v == v: vals.append(v) vals = np.sort(np.array(vals)); m = len(vals) lo, hi = vals[int(0.025 * m)], vals[int(0.975 * m) - 1]; lob, hib = vals[int(0.0042 * m)], vals[int(0.9958 * m) - 1] ver = 'FUNCIONA' if (a0 >= 0.65 and lob > 0.55) else (('NULO' + (' (invertido, no se interpreta)' if a0 < 0.45 else '')) if a0 <= 0.55 else 'débil') return round(a0, 4), [round(lo, 4), round(hi, 4)], [round(lob, 4), round(hib, 4)], ver def recorrer(o): if isinstance(o, dict): if 'id' in o and isinstance(o.get('id'), str) and o['id'].startswith('u') and 'auc' in o: a0, ic, icb, ver = bootstrap(f"/w/interno/val_{o['id']}.parquet") assert abs(a0 - o['auc']) < 1e-3, (o, a0) o['ic95'] = ic; o['ic_bonferroni6'] = icb; o['veredicto'] = ver print(o['etiqueta'], a0, ic, ver, flush=True) for v in o.values(): recorrer(v) elif isinstance(o, list): for v in o: recorrer(v) recorrer(R) json.dump(R, open('/w/salidas/40_validaciones.json', 'w'), ensure_ascii=False, indent=1, default=str)