"""ML1 · 30 · EXPLORATORIO (enmienda 22-oct, no decide): qué separa DENTRO del mismo órgano (estrato e × división × año × órgano).""" import sys, json; sys.path.insert(0, '/w/py') import numpy as np, pandas as pd from comun import carga, Estrat, boot, CONJ, CAT L, S = carga(); S = S[S.gris == 0].copy() S['est'] = S.exp + '|' + S.cpv_division + '|' + S.anio.astype(str); S['esto'] = S.est + '|' + S.org.astype(str) # solo estratos-órgano con positivos y controles g = S.groupby('esto').y.agg(['sum', 'count']); ok = g[(g['sum'] > 0) & (g['sum'] < g['count'])].index W = S[S.esto.isin(ok)] R = {'estratos_organo_utiles': int(len(ok)), 'positivos': int(W.y.sum()), 'controles': int((1 - W.y).sum()), 'positivos_por_exp': W[W.y == 1].groupby('exp').size().to_dict(), 'univariante_dentro_organo': {}} for c in [c for c in CONJ['D4'] if c not in CAT]: v = L[c].values[W.idx.values]; m = ~np.isnan(v) if m.sum() < 50 or W.y.values[m].sum() < 10: continue e = Estrat(W.esto.values[m], v[m], W.y.values[m]); a = e.auc() d = {'auc': round(a, 4), 'positivos': int(W.y.values[m].sum())} if c in ('baja', 'num_ofertas', 'disp', 'min_rel', 'edad_adj', 'adj_n_prev', 'log_pbl', 'plazo_ofertas', 'dias_adjudicar', 'duracion'): lo, hi, n = boot(e, W.org.values[m], 2000); lo2, hi2, _ = boot(e, W.exp.values[m], 2000); d['ic95_organo'] = [round(lo, 4), round(hi, 4)]; d['ic95_expediente'] = [round(lo2, 4), round(hi2, 4)] d['por_exp'] = {} for k, gg in W[m].groupby('exp'): vv = L[c].values[gg.idx.values] if gg.y.sum() >= 10: d['por_exp'][k] = [round(Estrat(gg.esto.values, vv, gg.y.values).auc(), 4), int(gg.y.sum())] R['univariante_dentro_organo'][c] = d; print(c, d, flush=True) # modelos dentro del órgano (predicciones de 10_modelos, VE y VT) R['modelos_dentro_organo'] = {} for mod in ['P', 'D1', 'D3', 'X1']: meta = json.load(open(f'/w/tmp/pred_{mod}.json')); P = np.load(f'/w/tmp/pred_{mod}.npz') for esq in ['VT', 'VE']: fr = [] for k in meta['claves']: e_, f_ = k.split('|') if e_ != esq: continue a = P[k.replace('/', '_')]; t = S[(S.anio >= 2019) if esq == 'VT' else (S.exp == f_)].copy() t['s'] = t.idx.map(dict(zip(a[:, 0].astype(int), a[:, 1]))); fr.append(t) F = pd.concat(fr); F2 = F[F.esto.isin(ok)] e1 = Estrat(F.est.values, F.s.values, F.y.values); e2 = Estrat(F2.esto.values, F2.s.values, F2.y.values) lo, hi, _ = boot(e2, F2.org.values, 2000); lo2, hi2, _ = boot(e2, F2.exp.values, 2000) d = {'auc_estrato': round(e1.auc(), 4), 'auc_dentro_organo': round(e2.auc(), 4), 'ic95_organo': [round(lo, 4), round(hi, 4)], 'ic95_expediente': [round(lo2, 4), round(hi2, 4)], 'por_exp_dentro_organo': {k: [round(Estrat(gg.esto.values, gg.s.values, gg.y.values).auc(), 4), int(gg.y.sum())] for k, gg in F2.groupby('exp') if gg.y.sum() >= 10}} R['modelos_dentro_organo'][f'{mod}_{esq}'] = d; print(mod, esq, d, flush=True) json.dump(R, open('/w/salidas/30_exploratorio.json', 'w'), indent=1, ensure_ascii=False)