"""ML1 · 20 · métricas, IC bootstrap, diagnósticos y veredicto (DEFINICIONES_PREVIAS §5-§7). Escribe salidas/metricas.json, salidas/importancias.csv, tmp/roc.json.""" import sys, json, time; sys.path.insert(0, '/w/py') import numpy as np, pandas as pd from sklearn.metrics import average_precision_score from comun import carga, Estrat, boot, CONJ, CAT, SEM T0 = time.time() def log(*a): print(f"[{time.time()-T0:6.0f}s]", *a, flush=True) L, S0 = carga() B = 2000 def evalframe(mod): meta = json.load(open(f'/w/tmp/pred_{mod}.json')); P = np.load(f'/w/tmp/pred_{mod}.npz') S = S0 if mod == 'S1' else S0[S0.gris == 0] fr = [] for k in meta['claves']: esq, fold = k.split('|'); a = P[k.replace('/', '_')] if esq == 'VT': m = S.anio >= 2019 elif esq == 'VE': m = S.exp == fold else: m = S.cpv_division == fold t = S[m].copy(); t['s'] = t.idx.map(dict(zip(a[:, 0].astype(int), a[:, 1]))); t['esq'] = esq; t['fold'] = fold assert t.s.notna().all(), k fr.append(t) F = pd.concat(fr, ignore_index=True); F['est'] = F.exp + '|' + F.cpv_division + '|' + F.anio.astype(str) return F def bloque(F, con_boot=True, estr='est', ap=False): e = Estrat(F[estr].values, F.s.values, F.y.values); a = e.auc() r = {'auc': round(a, 4), 'positivos': int(F.y.sum()), 'controles': int((1 - F.y).sum()), 'estratos': int(F[estr].nunique())} if con_boot: lo1, hi1, n1 = boot(e, F.exp.values, B); lo2, hi2, n2 = boot(e, F.org.values, B) r.update({'ic95_expediente': [round(lo1, 4), round(hi1, 4)], 'n_expedientes': n1, 'ic95_organo': [round(lo2, 4), round(hi2, 4)], 'n_organos': n2, 'ic95_decide': [round(min(lo1, lo2), 4), round(max(hi1, hi2), 4)]}) if ap: r['auc_pr'] = round(float(average_precision_score(F.y, F.s)), 4); r['prevalencia'] = round(float(F.y.mean()), 5) # IC de la AUC-PR por expediente y por órgano (pesos) for nom, g in (('expediente', F.exp.values), ('organo', F.org.values)): u, gi = np.unique(g, return_inverse=True); rng = np.random.default_rng(SEM); v = [] for _ in range(B if len(F) < 400000 else 500): cnt = rng.multinomial(len(u), np.full(len(u), 1 / len(u))).astype(float); w = cnt[gi] if (w * F.y.values).sum() > 0: v.append(average_precision_score(F.y.values, F.s.values, sample_weight=w)) r[f'auc_pr_ic95_{nom}'] = [round(float(np.quantile(v, .025)), 4), round(float(np.quantile(v, .975)), 4)] return r def por(F, col, con_boot=False): out = {} for k, g in F.groupby(col): if g.y.sum() == 0 or (1 - g.y).sum() == 0: continue e = Estrat(g.est.values, g.s.values, g.y.values); a = e.auc() d = {'auc': round(a, 4), 'positivos': int(g.y.sum()), 'controles': int((1 - g.y).sum()), 'auc_pr': round(float(average_precision_score(g.y, g.s)), 4), 'prevalencia': round(float(g.y.mean()), 5)} if con_boot: lo, hi, n = boot(e, g.org.values, B); d['ic95_organo'] = [round(lo, 4), round(hi, 4)] out[k] = d return out R = {'prerregistro_md5': open('/w/DEFINICIONES_PREVIAS.md5').read().split()[0], 'B': B, 'semilla': SEM, 'modelos': {}} ROC = {} def roc_pts(F): # ROC sobre el percentil del lote entre los controles de su estrato (boceto) q = np.empty(len(F)) for _, ii in F.groupby('est').indices.items(): s = F.s.values[ii]; c = np.sort(s[F.y.values[ii] == 0]) if len(c) == 0: q[ii] = np.nan; continue q[ii] = (np.searchsorted(c, s, 'left') + np.searchsorted(c, s, 'right')) / 2 / len(c) qp = q[F.y.values == 1]; qp = qp[~np.isnan(qp)] t = np.linspace(0, 1, 101) return {'fpr': t.tolist(), 'tpr': [float((qp >= 1 - x).mean()) for x in t]} for mod in ['P', 'I2', 'LR', 'D1', 'D3', 'D4', 'S1']: try: F = evalframe(mod) except FileNotFoundError: log('falta', mod); continue M = {} for esq in ['VT', 'VE', 'VM']: G = F[F.esq == esq] if not len(G): continue principal = mod in ('P', 'I2', 'LR') d = {'conjunta': bloque(G, con_boot=True, ap=(mod == 'P' and esq in ('VT', 'VE')))} d['dentro_organo_D2'] = bloque(G.assign(est2=G.est + '|' + G.org.astype(str)), con_boot=(mod == 'P'), estr='est2') if esq == 'VE': d['por_expediente'] = por(G, 'exp', con_boot=(mod == 'P')) d['mediana_expedientes'] = round(float(np.median([v['auc'] for v in d['por_expediente'].values()])), 4) if esq == 'VM': d['por_division'] = por(G, 'cpv_division', con_boot=(mod == 'P')) d['mediana_divisiones'] = round(float(np.median([v['auc'] for v in d['por_division'].values()])), 4) if esq == 'VT': d['por_expediente'] = por(G, 'exp', con_boot=(mod == 'P')) if mod == 'P': G3 = G[(G.y == 0) | G.vars.str.contains('V3')] d['solo_V3_S2'] = bloque(G3, con_boot=True) ROC[esq] = roc_pts(G) M[esq] = d; log(mod, esq, d['conjunta']['auc'], d['conjunta'].get('ic95_decide'), d.get('mediana_expedientes'), d.get('mediana_divisiones')) R['modelos'][mod] = M # univariantes (sin modelo): sobre todos los estratos y sobre la prueba temporal S = S0[S0.gris == 0].copy(); S['est'] = S.exp + '|' + S.cpv_division + '|' + S.anio.astype(str) uni = [] num = [c for c in CONJ['D4'] if c not in CAT] cob_pos = {} for c in num: v = L[c].values[S.idx.values]; ok = ~np.isnan(v) a_all = Estrat(S.est.values[ok], v[ok], S.y.values[ok]).auc() if ok.any() else np.nan m2 = ok & (S.anio.values >= 2019) a_vt = Estrat(S.est.values[m2], v[m2], S.y.values[m2]).auc() if m2.any() else np.nan yy = S.y.values uni.append({'variable': c, 'auc_univariante_todos': round(float(a_all), 4), 'auc_univariante_VT': round(float(a_vt), 4), 'cobertura_positivos': round(float(ok[yy == 1].mean()), 3), 'cobertura_controles': round(float(ok[yy == 0].mean()), 3), 'mediana_positivos': float(np.nanmedian(v[yy == 1])) if ok[yy == 1].any() else None, 'mediana_controles': float(np.nanmedian(v[yy == 0])) if ok[yy == 0].any() else None}) for c in CAT: tab = pd.crosstab(L[c].values[S.idx.values], S.y.values, normalize='columns') R.setdefault('categoricas', {})[c] = {str(k): {'positivos': round(float(r.get(1, 0)), 3), 'controles': round(float(r.get(0, 0)), 3)} for k, r in tab.iterrows()} perm = json.load(open('/w/tmp/perm_P_VT.json')) U = pd.DataFrame(uni).set_index('variable') I = pd.DataFrame(perm['importancias']).set_index('variable').join(U, how='outer').sort_values('caida_auc_media', ascending=False) I.to_csv('/w/salidas/importancias.csv', float_format='%.4f') R['permutacion_auc_base_VT'] = perm['auc_base'] # calibración C = json.load(open('/w/tmp/cal_P_VT.json')); cal = np.array(C['cal']); raw = np.array(C['raw']); y = np.array(C['y']) dec = pd.qcut(pd.Series(cal).rank(method='first'), 10, labels=False) tabla = [{'decil': int(k) + 1, 'n': int((dec == k).sum()), 'predicho': round(float(cal[dec == k].mean()), 5), 'observado': round(float(y[dec == k].mean()), 5)} for k in range(10)] ece = sum(t['n'] * abs(t['predicho'] - t['observado']) for t in tabla) / len(y) R['calibracion_VT'] = {'brier_bruto': round(float(((raw - y) ** 2).mean()), 6), 'brier_isotonica': round(float(((cal - y) ** 2).mean()), 6), 'brier_referencia_prevalencia': round(float(((y.mean() - y) ** 2).mean()), 6), 'ece_isotonica': round(float(ece), 6), 'prevalencia_prueba': round(float(y.mean()), 5), 'prevalencia_entreno': round(C['prev_entreno'], 5), 'media_predicha_isotonica': round(float(cal.mean()), 5), 'deciles': tabla, 'top1pct': {'n': int(len(y) // 100), 'observado': round(float(y[np.argsort(-cal)][:len(y) // 100].mean()), 4)}} # veredicto (§7) P = R['modelos']['P']; I2 = R['modelos'].get('I2', {}); D1 = R['modelos'].get('D1', {}) vt = P['VT']['conjunta']; ve_med = P['VE']['mediana_expedientes']; ve = P['VE']['conjunta'] d_vt = abs(I2['VT']['conjunta']['auc'] - vt['auc']) if I2 else None; d_ve = abs(I2['VE']['conjunta']['auc'] - ve['auc']) if I2 else None c_ok = d_vt is not None and d_vt <= 0.02 and d_ve <= 0.02 a = vt['ic95_decide'][0] > 0.65; b = ve_med > 0.60 if a and b and c_ok: ver = 'pasa' elif c_ok and ((vt['auc'] >= 0.60 and vt['ic95_decide'][0] > 0.55) or ve_med > 0.60): ver = 'cota' else: ver = 'no pasa' inv = vt['ic95_decide'][1] < 0.5 share = {e: round((D1[e]['conjunta']['auc'] - 0.5) / (P[e]['conjunta']['auc'] - 0.5), 3) if D1 and abs(P[e]['conjunta']['auc'] - 0.5) > 1e-9 else None for e in ('VT', 'VE')} ve_organo = (P['VE']['dentro_organo_D2']['auc'] < 0.55) or (share['VT'] is not None and share['VT'] >= 0.9 and share['VE'] >= 0.9) R['veredicto'] = {'criterio_a_VT_lim_inf_gt_065': [vt['ic95_decide'][0], a], 'criterio_b_VE_mediana_gt_060': [ve_med, b], 'criterio_c_I2_dif': [d_vt, d_ve, c_ok], 'veredicto': ver, 'invertido_VT': inv, 'D1_fraccion_de_AUC_menos_medio': share, 've_organo_o_tamano': bool(ve_organo)} json.dump(R, open('/w/salidas/metricas.json', 'w'), indent=1, ensure_ascii=False, default=lambda o: o.item() if hasattr(o, 'item') else str(o)) json.dump(ROC, open('/w/tmp/roc.json', 'w')) log('veredicto', R['veredicto'])