"""CPV1 · paso 35 (worker, numpy): elección, poda, temperaturas y umbrales en VALIDACIÓN (pre-registro §4.3 y §5), sobre las puntuaciones del evaluador de Python puro (paso 30). Nunca lee una ventana de prueba. Uso: python 35_calibrar.py rejilla | poda MODELO_BASE | calibrar MODELO_VAL LOSO_PREFIJO""" import sys, json, math import numpy as np P = '/w/interno/pred'; S = '/w/salidas' REJILLA = [round(0.30 + 0.01 * i, 2) for i in range(70)] def carga(base): h = json.load(open(f'{P}/{base}.json')) K = h['K']; cl = {c: i for i, c in enumerate(h['clases'])} sc = np.fromfile(f'{P}/{base}.scores.bin', dtype=np.float64).reshape(-1, K) src, reg, y, org = [], [], [], [] with open(f'{P}/{base}.meta.tsv', encoding='utf-8') as f: f.readline() for l in f: r = l.rstrip('\n').split('\t') src.append(r[1]); reg.append(r[4]); y.append(cl.get(r[5], -1)); org.append(r[3]) assert len(y) == sc.shape[0], (len(y), sc.shape) return {'sc': sc, 'src': np.array(src), 'reg': np.array(reg), 'y': np.array(y), 'org': np.array(org), 'K': K} def nll(sc, y, w, T): z = sc / T m = z.max(1, keepdims=True) lse = (m[:, 0] + np.log(np.exp(z - m).sum(1))) lp = z[np.arange(len(y)), np.maximum(y, 0)] - lse lp = np.where(y >= 0, lp, -50.0) return -(w * lp).sum() / w.sum() def ajusta_T(sc, y, w): a, b = -3.0, 3.0 g = (math.sqrt(5) - 1) / 2 c, d = b - g * (b - a), a + g * (b - a) fc, fd = nll(sc, y, w, math.exp(c)), nll(sc, y, w, math.exp(d)) while b - a > 1e-6: if fc < fd: b, d, fd = d, c, fc; c = b - g * (b - a); fc = nll(sc, y, w, math.exp(c)) else: a, c, fc = c, d, fd; d = a + g * (b - a); fd = nll(sc, y, w, math.exp(d)) return math.exp((a + b) / 2) def conf_pred(sc, T): z = sc / T z = z - z.max(1, keepdims=True) e = np.exp(z) p = e / e.sum(1, keepdims=True) pred = p.argmax(1) return p[np.arange(len(pred)), pred], pred, p def umbral(conf, ok, w): """El menor t de la rejilla con exactitud ≥ 0,90 para todo t' ≥ t (sin filas con confianza ≥ t': se da por cumplido).""" acc = [] for t in REJILLA: m = conf >= t den = w[m].sum() acc.append(None if den <= 0 else (w[m] * ok[m]).sum() / den) t_ok = None for t, a in zip(reversed(REJILLA), reversed(acc)): if a is None or a >= 0.90: t_ok = t else: break if t_ok is None: return None, acc return t_ok, acc def ece(conf, ok, w, n=15): b = np.minimum((conf * n).astype(int), n - 1) tot = w.sum(); e = 0.0 for i in range(n): m = b == i if m.any(): e += w[m].sum() / tot * abs((w[m] * ok[m]).sum() / w[m].sum() - (w[m] * conf[m]).sum() / w[m].sum()) return e def resumen(sc, y, w, T): conf, pred, p = conf_pred(sc, T) ok = (pred == y).astype(float) top3 = np.argsort(-p, axis=1)[:, :3] ok3 = (top3 == y[:, None]).any(1).astype(float) t, _ = umbral(conf, ok, w) m = conf >= t if t is not None else np.zeros(len(conf), bool) return {'n': int(len(y)), 'T': T, 'top1': float((w * ok).sum() / w.sum()), 'top3': float((w * ok3).sum() / w.sum()), 'ece': float(ece(conf, ok, w)), 'umbral_90': t, 'cobertura_90': float(w[m].sum() / w.sum()), 'exactitud_emitida': float((w[m] * ok[m]).sum() / w[m].sum()) if m.any() else None} def rejilla(): out = {} for cfg in ['v22_F1_a4e-6', 'v22_F1_a1e-6', 'v22_F2_a4e-6', 'v22_F2_a1e-6']: d = carga(f'{cfg}_t0__E2023') r = {} for reg in ('en', 'fuera'): m = d['reg'] == reg w = np.ones(m.sum()) T = ajusta_T(d['sc'][m], d['y'][m], w) r[reg] = resumen(d['sc'][m], d['y'][m], w, T) r['metrica'] = (r['en']['cobertura_90'] + r['fuera']['cobertura_90']) / 2 out[cfg] = r print(cfg, json.dumps(r), flush=True) pref = ['v22_F1_a4e-6', 'v22_F1_a1e-6', 'v22_F2_a4e-6', 'v22_F2_a1e-6'] mejor = max(out[c]['metrica'] for c in pref) elegido = next(c for c in pref if out[c]['metrica'] >= mejor - 0.005) out['elegido'] = elegido json.dump(out, open(f'{S}/35_rejilla.json', 'w'), indent=1) print('elegido', elegido) def poda(base): out = {} for tau in ('0', '0.01', '0.03', '0.1'): d = carga(f'{base}_t{tau}__E2023') m = d['reg'] == 'en' w = np.ones(m.sum()) T = ajusta_T(d['sc'][m], d['y'][m], w) out[tau] = resumen(d['sc'][m], d['y'][m], w, T) print(tau, json.dumps(out[tau]), flush=True) ref = out['0'] tau_ok = '0' for tau in ('0.01', '0.03', '0.1'): if ref['top1'] - out[tau]['top1'] <= 0.003 and ref['cobertura_90'] - out[tau]['cobertura_90'] <= 0.003: tau_ok = tau out['elegido'] = tau_ok json.dump(out, open(f'{S}/35_poda.json', 'w'), indent=1) print('τ elegido', tau_ok) def calibrar(base_val, prefijo_loso, fuentes): d = carga(f'{base_val}__E2023') m = d['reg'] == 'en' w = np.ones(m.sum()) T_en = ajusta_T(d['sc'][m], d['y'][m], w) r_en = resumen(d['sc'][m], d['y'][m], w, T_en) scs, ys, ws, por = [], [], [], {} for s in fuentes: e = carga(f'{prefijo_loso}{s}_t{base_val.split("_t")[-1]}__E2023_{s}') assert (e['reg'] == 'fuera').all() or True n = len(e['y']) scs.append(e['sc']); ys.append(e['y']); ws.append(np.full(n, 1.0 / n)) por[s] = n sc = np.vstack(scs); y = np.concatenate(ys); w = np.concatenate(ws) T_f = ajusta_T(sc, y, w) r_f = resumen(sc, y, w, T_f) conf, pred, _ = conf_pred(sc, T_f) ok = (pred == y).astype(float) off = 0; por_fuente = {} for s in fuentes: n = por[s]; c = conf[off:off + n]; o = ok[off:off + n]; mm = c >= r_f['umbral_90'] por_fuente[s] = {'n': n, 'top1': float(o.mean()), 'cobertura': float(mm.mean()), 'exactitud_emitida': float(o[mm].mean()) if mm.any() else None} off += n out = {'en': r_en, 'fuera_loso': r_f, 'fuera_por_fuente': por_fuente, 'temperatura': {'en': T_en, 'fuera': T_f}, 'umbral': {'en': r_en['umbral_90'], 'fuera': r_f['umbral_90']}} json.dump(out, open(f'{S}/35_calibracion.json', 'w'), indent=1) print(json.dumps(out, indent=1)) if __name__ == '__main__': if sys.argv[1] == 'rejilla': rejilla() elif sys.argv[1] == 'poda': poda(sys.argv[2]) elif sys.argv[1] == 'calibrar': calibrar(sys.argv[2], sys.argv[3], sys.argv[4].split(','))