"""CPV1 · paso 40 (etl:v2, Python puro): la predicción final de un conjunto, con las temperaturas y umbrales FIJADOS en validación (salidas/35_calibracion.json y, si se da, salidas/36_grupo_val.json). Es lo que hará el job, fila a fila. Uso: python 40_predecir.py MODELO_DIV.json.gz CONJUNTO [--grupo MODELO_GRUPO.json.gz] [--regimen fuera] [--procesos 3] --regimen fuera: todas las filas en el régimen fuera de dominio (pruebas LOSO). Escribe interno/pred/final____.tsv: id, source, anio, organo, regimen, y_div, y_grupo, nfeat, d1 p1 d2 p2 d3 p3 (top-3 con su probabilidad), emitida, g1 pg1 (grupo), grupo_emitido.""" import sys, os, time, json, multiprocessing as mp sys.path.insert(0, '/w/py') import cpvtexto as ct from importlib import import_module p30 = import_module('30_puntuar') T0 = time.time() def log(*a): print(f'[{time.time()-T0:6.0f}s]', *a, flush=True) D = '/w/interno/datos'; P = '/w/interno/pred'; S = '/w/salidas' MD = MG = None CAL = json.load(open(f'{S}/35_calibracion.json')) CALG = json.load(open(f'{S}/36_grupo_val.json')) if os.path.exists(f'{S}/36_grupo_val.json') else None FORZAR = None def _trozo(filas): cache = {} out = [] T = CAL['temperatura']; U = CAL['umbral'] for (idc, src, anio, org, tipo, men, imp, ydiv, ygrp, obj) in filas: ts = ct.terminos(obj) if not ts: continue k = ' '.join(ts) r = cache.get(k) if r is None: r = cache[k] = (MD.texto(k), MG.texto(k) if MG else None) if len(cache) > 100000: cache.clear() (acc, nf), accg = r org_d = ct.desescapa(org) if org else '' cats = ct.rasgos_cat(org_d, tipo, men, imp or None) reg = FORZAR or MD.regimen(src, org_d) top = MD.top(MD.puntuaciones(acc, cats), T[reg], 3) u = U[reg] emit = u is not None and top[0][1] >= u d = [MD.clases[j] for j, _ in top] g1 = pg1 = ''; gemit = False if MG: tg = MG.top(MG.puntuaciones(accg[0], cats), CALG['T_g'], 1)[0] g1 = MG.clases[tg[0]]; pg1 = repr(tg[1]) gemit = emit and g1[:2] == d[0] and CALG['t_g'] is not None and tg[1] >= CALG['t_g'] out.append('\t'.join((idc, src, str(anio), org, reg, ydiv, ygrp, str(nf), tipo, men, d[0], repr(top[0][1]), d[1], repr(top[1][1]), d[2], repr(top[2][1]), '1' if emit else '0', g1, pg1, '1' if gemit else '0'))) return out def main(): global MD, MG, FORZAR ruta, nombre = sys.argv[1], sys.argv[2] procesos = int(sys.argv[sys.argv.index('--procesos') + 1]) if '--procesos' in sys.argv else 3 if '--regimen' in sys.argv: FORZAR = sys.argv[sys.argv.index('--regimen') + 1] MD = ct.Modelo(ct.carga(ruta)) if '--grupo' in sys.argv: MG = ct.Modelo(ct.carga(sys.argv[sys.argv.index('--grupo') + 1])) fich, filtro = p30.conjunto(nombre) # E7, 3-nov (ingeniería, no toca reglas): se lee y se puntúa por bloques de BLOQUE filas (cada bloque ordenado por objeto # para la caché), en vez de cargar todo el conjunto en memoria: O2225 (5,5 M filas) no cabía en 8 GB con el pool. # La salida es la misma fila a fila (el orden de las filas en el TSV puede cambiar; todo lo que lo lee une por id). BLOQUE = 600_000 modelo = os.path.basename(ruta).replace('.json.gz', '') out = f'{P}/final__{modelo}__{nombre.replace(":", "_").replace(",", "+")}' + ('__fuera' if FORZAR else '') n = nl = 0 def bloques(): filas = [] with open(f'{D}/{fich}', encoding='utf-8') as f: cab = f.readline().rstrip('\n').split('\t') I = {c: i for i, c in enumerate(cab)} tiene_y = 'div' in I for l in f: r = l.rstrip('\n').split('\t') anio = int(r[I['anio_ref']]); src = r[I['source']] if not filtro(anio, src): continue filas.append((r[I['id_canonical']], src, anio, r[I['organo_clave']], r[I['tipo_contrato']], r[I['es_menor']], r[I['imp_adj_eur']], r[I['div']] if tiene_y else '', r[I['grupo']] if tiene_y else '', r[I['objeto']])) if len(filas) >= BLOQUE: filas.sort(key=lambda x: x[9]); yield filas; filas = [] if filas: filas.sort(key=lambda x: x[9]); yield filas with open(out + '.tsv.tmp', 'w', encoding='utf-8') as fo: fo.write('id\tsource\tanio\torgano\tregimen\ty_div\ty_grupo\tnfeat\ttipo\tmenor\td1\tp1\td2\tp2\td3\tp3\temitida\tg1\tpg1\tgrupo_emitido\n') with mp.get_context('fork').Pool(procesos) as pool: for filas in bloques(): nl += len(filas) for lineas in pool.imap(_trozo, [filas[i:i + 20000] for i in range(0, len(filas), 20000)], chunksize=1): for x in lineas: fo.write(x + '\n'); n += 1 log(nombre, 'leídas', nl, 'escritas', n) os.replace(out + '.tsv.tmp', out + '.tsv') log('escritas', n, out) if __name__ == '__main__': main()