"""MOD-REC · paso 35: el modelo (P) de producción para la web (pre-registro 2 §1: entrenado con todas las celdas ≤ 2025, la receta de MP1 (d) v2) + 50 reajustes por bootstrap de órganos para el intervalo (como MP1 (d)) + su validación (de salidas/30_P.json) + 300 vectores de prueba (solo campos del anuncio, sin claves) con su p de sklearn para el test de la web. Imagen bquantagents-worker, sin red. Salida: /w/salidas/35_recurso_pliego_modelo.json y /w/salidas/35_vectores.json. """ import json, hashlib, sys import numpy as np, pandas as pd sys.argv = ['30_modelos.py', 'P'] import importlib.util spec = importlib.util.spec_from_file_location('m30', '/w/py/30_modelos.py') # reutiliza las funciones de la implementación 1 sin ejecutar su programa principal: se carga el texto hasta «inf = » src = open('/w/py/30_modelos.py').read().split("\ninf = {'modelo'")[0] g = {'__name__': 'm30'} exec(compile(src, '30_modelos.py', 'exec'), g) d, F0, CATS, num_mp1 = g['d'], g['F0'], g['CATS'], g['num_mp1'] from sklearn.linear_model import LogisticRegression from sklearn.model_selection import GroupKFold from scipy.special import logit TR = (d['T'] <= 2025).to_numpy() F = F0.copy(); NUM = list(F.columns) CAT_NIV = {}; Cd = pd.DataFrame(index=d.index) for c in CATS: v = d[c].astype('string').fillna('∅') cnt = v[TR].value_counts(); niv = sorted([x for x, n in cnt.items() if n >= 30]); CAT_NIV[c] = niv Cd[c] = v.where(v.isin(niv), 'otros') MU = F.loc[TR].mean().to_numpy(); SD = F.loc[TR].std(ddof=0).to_numpy(); SD[SD == 0] = 1 def X(mask): Z = (F.loc[mask, NUM].to_numpy(float) - MU) / SD Dm = [np.column_stack([(Cd.loc[mask, c].to_numpy() == lv).astype(float) for lv in CAT_NIV[c] + ['otros']]) for c in CATS] return np.column_stack([Z] + Dm) y = d['y'].to_numpy(float); w = d['w'].to_numpy(float); grp = d['org'].to_numpy() Xtr = X(TR) aj = lambda Xa, ya, wa: LogisticRegression(C=0.1, solver='lbfgs', max_iter=5000).fit(Xa, ya, sample_weight=wa) m = aj(Xtr, y[TR], w[TR]) oof = np.zeros(TR.sum()) for a, b in GroupKFold(n_splits=5).split(Xtr, y[TR], grp[TR]): oof[b] = aj(Xtr[a], y[TR][a], w[TR][a]).predict_proba(Xtr[b])[:, 1] platt = LogisticRegression(C=1e6).fit(logit(np.clip(oof, 1e-6, 1 - 1e-6))[:, None], y[TR], sample_weight=w[TR]) prev = json.load(open('/w/priv/modelo_P.json')) assert np.allclose(prev['coef'], m.coef_[0], atol=1e-12) and abs(prev['intercept'] - m.intercept_[0]) < 1e-12, 'no es el modelo de producción' rng = np.random.default_rng(20261103) gtr = pd.factorize(grp[TR])[0]; G = gtr.max() + 1 boot = [] for bb in range(50): mult = np.bincount(rng.integers(0, G, G), minlength=G)[gtr].astype(float) mb = aj(Xtr, y[TR], w[TR] * mult) boot.append({'coef': [round(float(x), 12) for x in mb.coef_[0]], 'intercept': round(float(mb.intercept_[0]), 12)}) val = json.load(open('/w/salidas/30_P.json')) i2 = json.load(open('/w/salidas/31_impl2_P.json')) def resumen(r): return {'auc': round(r['auc']['p'], 4), 'ic': [round(x, 4) for x in r['auc_ic']['p']], 'n': r['n_test'], 'positivas': r['pos_test'], 'base_organo_cpv': round(r['auc']['b1'], 4), 'solo_importe': round(r['auc']['b3'], 4), 'delta_base': round(r['delta']['b1']['delta'], 4), 'delta_base_ic': [round(x, 4) for x in r['delta']['b1']['ic']], 'o_e': round(r['o_e'], 3), 'pendiente': round(r['pendiente'], 3), 'max_dif_deciles_puntos': round(max(abs(x['dif_puntos']) for x in r['deciles']), 2), 'deciles': [{'decil': int(x['q']) + 1, 'n': int(x['n']), 'predicha': round(x['predicha'], 6), 'observada': round(x['observada'], 6)} for x in r['deciles']]} modelo = {'version': 'recurso-pliego-v1', 'receta': 'MP1 (d) v2: logística L2 C = 0,1 + Platt por validación cruzada 5 por órgano', 'prerregistro_md5': '029a3fe9dfd38db9f830f1c546e3fdeb', 'construccion': 'unified_20261101 (código 93b4f8f)', 'entrenamiento': {'anios': '2022-2025', 'licitaciones': int(TR.sum()), 'positivas': int(y[TR].sum()), 'comunidades': sorted(d.loc[TR, 'ccaa'].unique().tolist())}, 'NUM': NUM, 'CATS': CATS, 'CAT_NIV': CAT_NIV, 'MU': [round(float(x), 12) for x in MU], 'SD': [round(float(x), 12) for x in SD], 'coef': [round(float(x), 12) for x in m.coef_[0]], 'intercept': round(float(m.intercept_[0]), 12), 'platt': {'a': round(float(platt.coef_[0][0]), 12), 'b': round(float(platt.intercept_[0]), 12)}, 'bootstrap': boot, 'validacion': {'2025': resumen(val['t2025']), '2024': resumen(val['t2024']), 'segunda_implementacion_max_dif_auc': round(max(abs(val[t]['auc']['p_raw'] - i2[t]['auc']) for t in ('t2025', 't2024')), 4)}, 'versiones': {'sklearn': g['sklearn'].__version__, 'numpy': np.__version__, 'pandas': pd.__version__}} txt = json.dumps(modelo, ensure_ascii=False, sort_keys=True) modelo['md5'] = hashlib.md5(txt.encode()).hexdigest() json.dump(modelo, open('/w/salidas/35_recurso_pliego_modelo.json', 'w'), ensure_ascii=False, indent=1) # vectores de prueba: 300 filas (100 de las de p más alta), solo los campos del anuncio que lee la web CAMPOS = ['pbl_exp', 'pbl_lote', 've_exp', 'dur', 'plazo', 'n_lotes_an', 'sara', 'ue', 'cpv_n_div', 'n_crit', 'suman100', 'n_sin_tipo', 'peso_jv', 'peso_suma', 'peso_precio', 'pcap', 'ppt', 'proc_nat', 'tram', 'tipo_contrato', 'cpv_div', 'tipo_organo', 'ccaa', 'mes_pub'] pall = platt.predict_proba(logit(np.clip(m.predict_proba(X(np.ones(len(d), bool)))[:, 1], 1e-6, 1 - 1e-6))[:, None])[:, 1] orden = np.argsort(-pall) idx = list(orden[:100]) + list(np.random.default_rng(7).choice(len(d), 200, replace=False)) def limpio(v): if v is None or (isinstance(v, float) and np.isnan(v)) or v is pd.NA: return None if isinstance(v, (np.integer,)): return int(v) if isinstance(v, (np.floating,)): return float(v) if isinstance(v, (np.bool_,)): return bool(v) return v vec = [{'campos': {c: limpio(d.iloc[i][c]) for c in CAMPOS}, 'p': float(pall[i])} for i in idx] json.dump(vec, open('/w/salidas/35_vectores.json', 'w'), ensure_ascii=False, indent=0, default=str) print('md5', modelo['md5'], 'n', TR.sum(), 'p max', pall.max(), 'p mediana', np.median(pall))