"""CPV1-v2 · paso 35 (worker, numpy; el de la v1 sin rejilla ni poda, que la v2 no repite): temperaturas y umbrales en VALIDACIÓN (pre-registro v2 §0.6): T_en y t_en en E 2025 en dominio con M_en ≤ 2024; T_fu y t_fu en la unión LOSO de 2025 (M_fu ≤ 2024 sin S, medido en S-2025, pesos 1/n_S). Nunca lee 2026. Uso: python 35_calibrar.py calibrar MODELO_EN_VAL LOSO_PREFIJO FUENTES(coma)""" 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 calibrar(base_val, prefijo_loso, fuentes): d = carga(f'{base_val}__E2025') 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]}__E2025_{s}') 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 = {'version': 'cpv1v2', 'modelo_en_val': base_val, 'loso_prefijo': prefijo_loso, 'fuentes_loso': fuentes, '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] == 'calibrar': calibrar(sys.argv[2], sys.argv[3], sys.argv[4].split(','))