acc8c371bc
models/cama/seer_survival is the SEER survival pipeline as Hamilton dataflows, with the interval LR and network keeping their per-interval fits and surviving an interval without deaths. models/cama/survival is the scenario: it indexes the total cohort at the first invasive biopsy report (steps/indexing.py), derives the covariates and the outcome from the cohort's events, fits the interval survival, writes the five routines and publishes the population curves (analisis/curvas.json) with the version. An estimate may carry the model's own index date.
1421 lines
62 KiB
Python
1421 lines
62 KiB
Python
import matplotlib
|
|
matplotlib.use("Agg")
|
|
def _guardar_figs(pref):
|
|
"""Equivalente a lo que hacia el cuaderno al mostrar figuras: las guarda en ./figuras/ y las cierra."""
|
|
import os, re
|
|
import matplotlib.pyplot as _plt
|
|
global _NFIG
|
|
for _n in list(_plt.get_fignums()):
|
|
_f = _plt.figure(_n)
|
|
if not _f.axes: continue
|
|
_t = _f._suptitle.get_text() if getattr(_f, "_suptitle", None) is not None else (_f.axes[0].get_title() or "figura")
|
|
_slug = re.sub(r"[^A-Za-z0-9]+", "_", _t).strip("_")[:50] or "figura"
|
|
_NFIG += 1
|
|
os.makedirs("figuras", exist_ok=True)
|
|
_f.savefig(f"figuras/{pref}_{_NFIG:02d}_{_slug}.png", dpi=150, bbox_inches="tight")
|
|
_plt.close("all")
|
|
_NFIG = 0
|
|
|
|
import numpy as np
|
|
import pandas as pd
|
|
import matplotlib.pyplot as plt
|
|
import seaborn as sns
|
|
|
|
from sklearn.model_selection import train_test_split
|
|
from sklearn.metrics import roc_auc_score, roc_curve, confusion_matrix
|
|
from sklearn.calibration import calibration_curve
|
|
|
|
import statsmodels.api as sm
|
|
|
|
import warnings
|
|
warnings.filterwarnings("ignore")
|
|
|
|
RANDOM_STATE = 42
|
|
np.random.seed(RANDOM_STATE)
|
|
|
|
sns.set_style("whitegrid")
|
|
_guardar_figs("04")
|
|
|
|
|
|
CSV_PATH = "./dataframe_balanceado_con_edad_y_tumor_agrupados.csv"
|
|
|
|
df_raw = pd.read_csv(CSV_PATH, dtype=str)
|
|
|
|
# Traduce las columnas de nuestro pipeline a los nombres canónicos que usan las Fases
|
|
# 4-7 sin tocar su lógica: Age/Tumor_Size SIGUEN LLAMÁNDOSE así por compatibilidad, aunque
|
|
# ahora contienen las categorías de Age_group/Tumor_group en vez de valores continuos --
|
|
# para eso existen AGE_IS_NUMERIC/TUMORSIZE_IS_NUMERIC (en False más abajo), que el
|
|
# cuaderno original ya usaba para este caso ("SEER entrega la variable ya agrupada").
|
|
CANONICAL_MAP = {
|
|
"Age_group": "Edad",
|
|
"Tumor_group": "Tamano_tumor",
|
|
"Estadio_cat": "Estadio",
|
|
"Grado_histologico_cat": "Grado_histologico",
|
|
"Subtipo_molecular_cat": "Subtipo_molecular",
|
|
"Receptor_estrogeno_cat": "Receptor_estrogeno",
|
|
"Receptor_progesterona_cat": "Receptor_progesterona",
|
|
"Metastasis_cat": "Metastasis",
|
|
"Localizacion_mama_cat": "Localizacion_mama",
|
|
"Lateralidad_cat": "Lateralidad",
|
|
"Tipo_histologico_cat": "Tipo_histologico",
|
|
"Tratamiento_quirurgico_cat": "Tratamiento_quirurgico",
|
|
"Radioterapia_cat": "Radioterapia",
|
|
"Quimioterapia_cat": "Quimioterapia",
|
|
"Estado_civil_cat": "Estado_civil",
|
|
"Outcome_cat": "Outcome_cat",
|
|
# variables simuladas de la base sintética, si existen en el CSV
|
|
"Ganglios_positivos_cat": "Ganglios_positivos",
|
|
"Invasion_linfovascular_cat": "Invasion_linfovascular",
|
|
"Margenes_cat": "Margenes",
|
|
"Densidad_BIRADS_cat": "Densidad_BIRADS",
|
|
"Masa_espiculada_cat": "Masa_espiculada",
|
|
"Microcalcificaciones_cat": "Microcalcificaciones",
|
|
"Multifocalidad_cat": "Multifocalidad",
|
|
"BRCA_cat": "BRCA",
|
|
"HER2_IHQ_cat": "HER2_IHQ",
|
|
}
|
|
|
|
# Race es la excepción: recodificacion_covariables_SEER.ipynb nunca la recodifica (no
|
|
# está en su RECODERS) -- se usa tal cual viene de SEER, localizándola por palabra clave
|
|
# igual que hacía el cuaderno original con el CSV crudo.
|
|
def find_col(df, keywords, exclude=()):
|
|
for col in df.columns:
|
|
d = col.lower().replace("_", " ")
|
|
if any(k in d for k in keywords) and not any(e in d for e in exclude):
|
|
return col
|
|
return None
|
|
|
|
_race_col = find_col(df_raw, ["race"])
|
|
|
|
# La depuración automática puede haber conservado Tamano_tumor_cat en vez de Tumor_group
|
|
# (o al revés): se usa la que exista como "Tamano_tumor". Las covariables que la depuración
|
|
# eliminó (p. ej. EOD_Mets, ER_Status) simplemente se omiten abajo.
|
|
if "Tumor_group" not in df_raw.columns and "Tamano_tumor_cat" in df_raw.columns:
|
|
CANONICAL_MAP["Tamano_tumor_cat"] = "Tamano_tumor"
|
|
|
|
if _race_col is None:
|
|
pass
|
|
elif _race_col in CANONICAL_MAP:
|
|
_race_col = None
|
|
|
|
rename_map = {k: v for k, v in CANONICAL_MAP.items() if k in df_raw.columns}
|
|
|
|
# OJO: df_raw conserva TODAS las columnas crudas originales de SEER (las deja ahí todo
|
|
# el pipeline de balanceo/categorización), con nombres ya "limpios" puestos por el
|
|
# notebook constructor -- y alguna de ellas puede llamarse EXACTAMENTE igual que uno de
|
|
# nuestros nombres canónicos (p.ej. una columna cruda "Tamano_tumor" o "Race" preexistente,
|
|
# distinta de "Tumor_group"/Race_recode). Si se renombrara sobre el DataFrame completo
|
|
# (df_raw.rename(...)[...]), esa columna preexistente quedaría DUPLICADA junto con la
|
|
# recién renombrada -- un error que no truena aquí, sino mucho más adelante, dentro de
|
|
# pgmpy, con un traceback críptico ("DataFrame' object has no attribute 'dtype'"). Por
|
|
# eso se selecciona primero por nombre ORIGINAL (todos distintos, vienen de las llaves de
|
|
# CANONICAL_MAP) y solo DESPUÉS se renombra -- así nunca se arrastra una columna
|
|
# preexistente que por coincidencia ya tuviera el nombre destino.
|
|
df = df_raw[list(rename_map.keys())].rename(columns=rename_map).copy()
|
|
if _race_col:
|
|
df["Race"] = df_raw[_race_col]
|
|
|
|
_dup = df.columns[df.columns.duplicated()].tolist()
|
|
assert not _dup, (
|
|
f"Columnas duplicadas tras construir df: {_dup}. Esto rompería la red bayesiana más "
|
|
f"adelante con un error difícil de rastrear -- revisar CANONICAL_MAP / _race_col.")
|
|
|
|
# CS_Lymph_Nodes (variable del paper original) nunca se recodificó en este pipeline --
|
|
# se omite, igual que el cuaderno original haría ante cualquier variable faltante.
|
|
|
|
|
|
assert (df["Outcome_cat"] == "Desconocido").sum() == 0, (
|
|
"Se esperaba que la cohorte balanceada ya excluyera el desenlace desconocido.")
|
|
|
|
df["outcome"] = (df["Outcome_cat"] == "Sobrevive").astype(int)
|
|
|
|
|
|
|
|
AGE_IS_NUMERIC = False
|
|
TUMORSIZE_IS_NUMERIC = False
|
|
|
|
cat_cols = [c for c in ["Edad", "Tamano_tumor", "Estadio", "Grado_histologico", "Subtipo_molecular", "Receptor_estrogeno",
|
|
"Receptor_progesterona", "Metastasis", "Localizacion_mama", "Lateralidad",
|
|
"Tipo_histologico", "Tratamiento_quirurgico", "Radioterapia", "Quimioterapia",
|
|
"Estado_civil", "Race"] + ['Ganglios_positivos', 'Invasion_linfovascular', 'Margenes', 'Densidad_BIRADS', 'Masa_espiculada', 'Microcalcificaciones', 'Multifocalidad', 'BRCA', 'HER2_IHQ'] if c in df.columns]
|
|
num_cols = [] # nada continuo en este pipeline
|
|
|
|
df_enc = df.copy()
|
|
for c in cat_cols:
|
|
df_enc[c] = df_enc[c].fillna("Desconocido").astype(str)
|
|
|
|
|
|
feature_cols = cat_cols + num_cols
|
|
X = pd.get_dummies(df_enc[feature_cols], drop_first=True).astype(float)
|
|
y = df_enc["outcome"]
|
|
|
|
_constant_cols = [c for c in X.columns if X[c].nunique() <= 1]
|
|
if _constant_cols:
|
|
X = X.drop(columns=_constant_cols)
|
|
|
|
X_train, X_test, y_train, y_test = train_test_split(
|
|
X, y, test_size=0.3, random_state=RANDOM_STATE, stratify=y)
|
|
|
|
_constant_in_train = [c for c in X_train.columns if X_train[c].nunique() <= 1]
|
|
if _constant_in_train:
|
|
X_train = X_train.drop(columns=_constant_in_train)
|
|
X_test = X_test.drop(columns=_constant_in_train)
|
|
|
|
|
|
from scipy.stats import chi2_contingency
|
|
|
|
def univariate_prefilter(X, y, alpha=0.10, verbose=True):
|
|
kept = [] # lista de (columna, p_valor, estadistico_chi2)
|
|
for col in X.columns:
|
|
table = pd.crosstab(X[col], y)
|
|
if table.shape[0] < 2 or table.shape[1] < 2:
|
|
continue # columna sin variación -- no aporta nada, se descarta
|
|
try:
|
|
chi2_stat, p, _, _ = chi2_contingency(table)
|
|
except ValueError:
|
|
continue
|
|
if p < alpha:
|
|
kept.append((col, p, chi2_stat))
|
|
return kept
|
|
|
|
|
|
# MAX_CANDIDATES: tope DURO sobre cuántas columnas puede recibir el stepwise,
|
|
# sin importar cuántas pasen el filtro de alpha. Con datasets grandes (miles
|
|
# de filas), es común que decenas de variables salgan "significativas" aunque
|
|
# baje mucho alpha -- este tope evita que el stepwise se vuelva intratable
|
|
# de todos modos. Ajusta este número si quieres ser más/menos estricto.
|
|
MAX_CANDIDATES = 40
|
|
|
|
_prefilter_alpha = 0.10 # <-- edita aquí si quieres otro umbral
|
|
kept_with_stats = univariate_prefilter(X_train, y_train, alpha=_prefilter_alpha)
|
|
|
|
if len(kept_with_stats) > MAX_CANDIDATES:
|
|
# OJO: con datasets grandes, muchas variables fuertemente asociadas
|
|
# (p.ej. Stage, EOD_Mets) pueden tener un p-valor que en punto flotante
|
|
# es EXACTAMENTE 0.0 -- no solo "0.0000" redondeado en pantalla, sino el
|
|
# valor real. Si varias columnas empatan en 0.0, ordenar por p-valor ya
|
|
# no las distingue (el "orden" entre ellas sería arbitrario). Por eso
|
|
# ordenamos por el ESTADÍSTICO chi2 (más grande = asociación más fuerte),
|
|
# que sigue siendo comparable sin ese problema de precisión.
|
|
kept_with_stats.sort(key=lambda t: t[2], reverse=True) # chi2 descendente
|
|
kept_with_stats = kept_with_stats[:MAX_CANDIDATES]
|
|
|
|
prefiltered_cols = [c for c, _, _ in kept_with_stats]
|
|
|
|
|
|
def _safe_fit_logit(y, X_sub, maxiter=200):
|
|
try:
|
|
return sm.Logit(y, X_sub).fit(disp=0, method="bfgs", maxiter=maxiter)
|
|
except Exception:
|
|
try:
|
|
# Segundo intento con regularización L2 leve, más tolerante aún
|
|
return sm.Logit(y, X_sub).fit_regularized(disp=0, alpha=0.01, maxiter=maxiter)
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
def stepwise_selection(X, y, alpha_in=0.10, alpha_out=0.15, verbose=True):
|
|
included = []
|
|
excluded = list(X.columns)
|
|
|
|
while True:
|
|
changed = False
|
|
|
|
# --- Forward step ---
|
|
best_pval = np.inf
|
|
best_feature = None
|
|
for col in excluded:
|
|
model = _safe_fit_logit(y, sm.add_constant(X[included + [col]]))
|
|
if model is None:
|
|
continue
|
|
if col not in model.pvalues:
|
|
continue
|
|
pval = model.pvalues[col]
|
|
if pval < best_pval:
|
|
best_pval = pval
|
|
best_feature = col
|
|
if best_feature is not None and best_pval < alpha_in:
|
|
included.append(best_feature)
|
|
excluded.remove(best_feature)
|
|
changed = True
|
|
|
|
# --- Backward step ---
|
|
if included:
|
|
model = _safe_fit_logit(y, sm.add_constant(X[included]))
|
|
if model is not None:
|
|
pvals = model.pvalues.drop("const", errors="ignore")
|
|
if len(pvals) > 0:
|
|
worst_pval = pvals.max()
|
|
if worst_pval > alpha_out:
|
|
worst_feature = pvals.idxmax()
|
|
included.remove(worst_feature)
|
|
excluded.append(worst_feature)
|
|
changed = True
|
|
|
|
if not changed:
|
|
break
|
|
|
|
return included
|
|
|
|
|
|
# ------------------------------------------------------------------
|
|
# El stepwise es la parte más costosa de todo el notebook: en cada
|
|
# iteración ajusta un modelo por cada candidata restante. Con datasets
|
|
# reales de SEER (decenas de miles de filas), cada ajuste individual ya es
|
|
# lento de por sí, y eso se multiplica por cientos de ajustes a lo largo
|
|
# de todo el proceso.
|
|
#
|
|
# Para acotar el tiempo SIN perder precisión en el modelo final: la
|
|
# BÚSQUEDA de qué variables entran corre sobre una submuestra (estratificada
|
|
# por outcome) de hasta MAX_SEARCH_ROWS filas -- con ese tamaño de muestra
|
|
# ya sobra para decidir qué variables son relevantes. El modelo FINAL (celda
|
|
# siguiente) se vuelve a ajustar con las variables elegidas, pero sobre TODO
|
|
# tu X_train real, así que los coeficientes finales sí usan toda tu
|
|
# información.
|
|
# ------------------------------------------------------------------
|
|
MAX_SEARCH_ROWS = 8000
|
|
|
|
if X_train.shape[0] > MAX_SEARCH_ROWS:
|
|
_search_idx, _ = train_test_split(
|
|
X_train.index, train_size=MAX_SEARCH_ROWS, random_state=RANDOM_STATE,
|
|
stratify=y_train)
|
|
X_search = X_train.loc[_search_idx, prefiltered_cols]
|
|
y_search = y_train.loc[_search_idx]
|
|
else:
|
|
X_search, y_search = X_train[prefiltered_cols], y_train
|
|
|
|
selected_features = stepwise_selection(X_search, y_search, verbose=True)
|
|
|
|
|
|
final_lr_model = sm.Logit(y_train, sm.add_constant(X_train[selected_features])).fit(
|
|
disp=0, method="bfgs", maxiter=200
|
|
)
|
|
|
|
|
|
# Tabla de OR [95% CI], análoga a la Tabla 4 del paper
|
|
params = final_lr_model.params
|
|
conf = final_lr_model.conf_int()
|
|
conf["OR"] = params
|
|
conf.columns = ["2.5%", "97.5%", "OR"]
|
|
or_table = np.exp(conf)
|
|
or_table["p_value"] = final_lr_model.pvalues
|
|
or_table.round(3).to_csv("./or_lr_balanceada.csv")
|
|
|
|
|
|
try:
|
|
from pgmpy.estimators import HillClimbSearch, BDeu
|
|
from pgmpy.causal_discovery import ExpertKnowledge
|
|
try:
|
|
# pgmpy >= 1.0 renombró BayesianNetwork -> DiscreteBayesianNetwork
|
|
from pgmpy.models import DiscreteBayesianNetwork as BayesianNetwork
|
|
from pgmpy.parameter_estimator import DiscreteBayesianEstimator as BayesianEstimator
|
|
PGMPY_NEW_API = True
|
|
except ImportError:
|
|
from pgmpy.models import BayesianNetwork
|
|
from pgmpy.estimators import BayesianEstimator
|
|
PGMPY_NEW_API = False
|
|
from pgmpy.inference import VariableElimination
|
|
PGMPY_OK = True
|
|
except ImportError:
|
|
PGMPY_OK = False
|
|
|
|
# NOTA: pgmpy ha cambiado nombres de clases/parámetros entre versiones:
|
|
# - el nombre del score K2 aceptado por HillClimbSearch.estimate() puede ser
|
|
# "k2" (pgmpy >= 1.0) o "k2score" (versiones antiguas).
|
|
# - "BayesianNetwork" fue renombrada a "DiscreteBayesianNetwork", y el estimador de
|
|
# parámetros bayesiano ahora vive en pgmpy.parameter_estimator.DiscreteBayesianEstimator
|
|
# y se pasa como INSTANCIA a model.fit(estimator=...), en vez de kwargs sueltos.
|
|
# Si tu versión da error, revisa `pgmpy.estimators.StructureScore.get_scoring_method`,
|
|
# `pgmpy.models` y `pgmpy.parameter_estimator` para ver los nombres vigentes.
|
|
|
|
|
|
import numpy as np
|
|
import pandas as pd
|
|
from scipy.special import gammaln
|
|
|
|
|
|
MAX_UNIQUE_VALUES = 300
|
|
MAX_JOINT_STATES = 150
|
|
|
|
|
|
def _log_multinomial_coeff(counts, axis=-1):
|
|
counts = np.asarray(counts, dtype=np.float64)
|
|
N = counts.sum(axis=axis)
|
|
return gammaln(N + 1) - gammaln(counts + 1).sum(axis=axis)
|
|
|
|
|
|
def _log_dirichlet_multinomial_norm(gamma_total, J):
|
|
gamma_total = np.asarray(gamma_total, dtype=np.float64)
|
|
return gammaln(gamma_total + J) - gammaln(gamma_total + 1) - gammaln(J)
|
|
|
|
|
|
def _build_cumulative_counts(bucket_idx, category_idx, n_buckets, n_categories):
|
|
counts = np.zeros((n_buckets, n_categories), dtype=np.int64)
|
|
np.add.at(counts, (bucket_idx, category_idx), 1)
|
|
cum = np.concatenate([np.zeros((1, n_categories), dtype=np.int64),
|
|
np.cumsum(counts, axis=0)])
|
|
return cum
|
|
|
|
|
|
def discretize_single_variable(
|
|
x, parent_joint_idx, n_parent_states,
|
|
children_specs=None, L=None, verbose=False,
|
|
):
|
|
children_specs = children_specs or []
|
|
x = np.asarray(x, dtype=np.float64)
|
|
|
|
# --- Tope 1: demasiados valores únicos -> pre-agrupar en una rejilla más gruesa ---
|
|
n_unique_raw = len(np.unique(x))
|
|
if n_unique_raw > MAX_UNIQUE_VALUES:
|
|
ranks = pd.qcut(x, q=MAX_UNIQUE_VALUES, duplicates="drop", labels=False)
|
|
# Usamos el valor medio de cada bucket como "pseudo-valor continuo" --
|
|
# conserva el orden y permite que la DP siga trabajando en escala real.
|
|
bucket_means = pd.Series(x).groupby(ranks).transform("mean")
|
|
x = bucket_means.values
|
|
|
|
order = np.argsort(x, kind="mergesort")
|
|
x_sorted = x[order]
|
|
parent_sorted = parent_joint_idx[order]
|
|
children_sorted = [
|
|
{**c, "child_idx": c["child_idx"][order],
|
|
"spouse_joint_idx": (c["spouse_joint_idx"][order]
|
|
if c["spouse_joint_idx"] is not None else None)}
|
|
for c in children_specs
|
|
]
|
|
|
|
unique_vals, bucket_of_row = np.unique(x_sorted, return_inverse=True)
|
|
m = len(unique_vals)
|
|
|
|
if L is None:
|
|
cardinalities = [n_parent_states] + [c["n_child_states"] for c in children_specs]
|
|
L = max(cardinalities) if cardinalities else 2.0
|
|
L = float(max(L, 1.0))
|
|
|
|
cum_parent = _build_cumulative_counts(bucket_of_row, parent_sorted, m, n_parent_states)
|
|
|
|
cum_children = []
|
|
for c in children_sorted:
|
|
n_child = c["n_child_states"]
|
|
n_spouse = c.get("n_spouse_states", 1) or 1
|
|
if c["spouse_joint_idx"] is not None and n_spouse > 1:
|
|
combo_idx = c["child_idx"] * n_spouse + c["spouse_joint_idx"]
|
|
cum = _build_cumulative_counts(bucket_of_row, combo_idx, m, n_child * n_spouse)
|
|
cum_children.append((cum, n_child, n_spouse))
|
|
else:
|
|
cum = _build_cumulative_counts(bucket_of_row, c["child_idx"], m, n_child)
|
|
cum_children.append((cum, n_child, 1))
|
|
|
|
x_min, x_max = unique_vals[0], unique_vals[-1]
|
|
span = max(x_max - x_min, 1e-12)
|
|
|
|
def edge_prior_cost(u_val, v_val):
|
|
gap = max(v_val - u_val, 0.0)
|
|
z = -L * gap / span
|
|
if z > -1e-12:
|
|
return np.inf
|
|
return -np.log1p(-np.exp(z)) # costo = -ln(prior), prior = 1-exp(z)
|
|
|
|
# --- Programación dinámica, VECTORIZADA sobre u para cada v ---
|
|
S = np.zeros(m + 1)
|
|
parent_of = [None] * (m + 1)
|
|
|
|
for v in range(1, m + 1):
|
|
u_range = np.arange(0, v) # todos los u candidatos para este v, de una vez
|
|
|
|
# término "dentro del intervalo" (Ecuación 4, segundo producto), vectorizado
|
|
u_vals_for_within = np.where(u_range > 0, unique_vals[np.clip(u_range - 1, 0, m - 1)], x_min)
|
|
within = L * np.maximum(unique_vals[v - 1] - u_vals_for_within, 0.0) / span
|
|
|
|
# término de padres, vectorizado sobre u
|
|
pcounts = cum_parent[v][None, :] - cum_parent[u_range] # (v, JP)
|
|
gamma = pcounts.sum(axis=1)
|
|
parent_cost = (_log_dirichlet_multinomial_norm(gamma, n_parent_states)
|
|
+ _log_multinomial_coeff(pcounts, axis=1))
|
|
|
|
total_cost = within + parent_cost
|
|
|
|
# términos de hijos, vectorizados sobre u
|
|
for cum, n_child, n_spouse in cum_children:
|
|
counts_all = cum[v][None, :] - cum[u_range] # (v, n_child*n_spouse)
|
|
counts_all = counts_all.reshape(len(u_range), n_spouse, n_child)
|
|
g = counts_all.sum(axis=2) # (v, n_spouse)
|
|
child_cost = (_log_dirichlet_multinomial_norm(g, n_child)
|
|
+ _log_multinomial_coeff(counts_all, axis=2))
|
|
total_cost = total_cost + child_cost.sum(axis=1)
|
|
|
|
# costo de colocar un edge antes de cada u (0 si u==0, no hay edge previo)
|
|
edge_costs = np.zeros(len(u_range))
|
|
nonzero_u = u_range > 0
|
|
if nonzero_u.any():
|
|
edge_costs[nonzero_u] = [
|
|
edge_prior_cost(unique_vals[u - 1], unique_vals[u]) for u in u_range[nonzero_u]
|
|
]
|
|
|
|
candidate = np.where(u_range == 0, total_cost, S[u_range] + edge_costs + total_cost)
|
|
best_idx = int(np.argmin(candidate))
|
|
S[v] = candidate[best_idx]
|
|
parent_of[v] = int(u_range[best_idx])
|
|
|
|
edges = []
|
|
v = m
|
|
while v is not None and v > 0:
|
|
u = parent_of[v]
|
|
if u is not None and u > 0:
|
|
edges.append((unique_vals[u - 1] + unique_vals[u]) / 2.0)
|
|
v = u
|
|
|
|
edges.reverse()
|
|
|
|
|
|
return edges
|
|
|
|
|
|
def joint_index(df, cols):
|
|
if len(cols) == 0:
|
|
return np.zeros(len(df), dtype=np.int64), 1
|
|
|
|
idx = np.zeros(len(df), dtype=np.int64)
|
|
total_states = 1
|
|
for c in cols:
|
|
codes, _ = pd.factorize(df[c])
|
|
n_states_c = codes.max() + 1 if len(codes) > 0 else 1
|
|
idx = idx * n_states_c + codes
|
|
total_states *= n_states_c
|
|
return idx, total_states
|
|
|
|
|
|
|
|
|
|
MAX_JOINT_STATES = 3000 # tope de cardinalidad conjunta (ver ldvbn_core: JP o JCj*JSj)
|
|
|
|
|
|
def _cap_cardinality(df, cols, max_states, label=""):
|
|
cols = list(cols)
|
|
if not cols:
|
|
return cols, 1
|
|
|
|
cardinalities = {c: (pd.factorize(df[c])[0].max() + 1) for c in cols}
|
|
product = 1
|
|
for c in cols:
|
|
product *= cardinalities[c]
|
|
|
|
dropped = []
|
|
while product > max_states and len(cols) > 0:
|
|
worst = max(cols, key=lambda c: cardinalities[c])
|
|
cols.remove(worst)
|
|
dropped.append(worst)
|
|
product = 1
|
|
for c in cols:
|
|
product *= cardinalities[c]
|
|
|
|
|
|
return cols, product
|
|
|
|
|
|
def get_markov_blanket_specs(df, edges, target):
|
|
parents = [u for (u, v) in edges if v == target]
|
|
children = [v for (u, v) in edges if u == target]
|
|
|
|
parents, _ = _cap_cardinality(df, parents, MAX_JOINT_STATES, label=f"padres de {target}")
|
|
parent_idx, n_parent_states = joint_index(df, parents)
|
|
|
|
children_specs = []
|
|
for child in children:
|
|
spouses = [u for (u, v) in edges if v == child and u != target]
|
|
child_codes, _ = pd.factorize(df[child])
|
|
n_child_states = child_codes.max() + 1 if len(child_codes) > 0 else 1
|
|
|
|
# El tope aplica al producto TOTAL (cónyuges * categorías del hijo)
|
|
spouses, _ = _cap_cardinality(
|
|
df, spouses, max(MAX_JOINT_STATES // max(n_child_states, 1), 1),
|
|
label=f"cónyuges de {child} (hijo de {target})")
|
|
|
|
spouse_idx, n_spouse_states = joint_index(df, spouses)
|
|
children_specs.append({
|
|
"child_idx": child_codes,
|
|
"n_child_states": n_child_states,
|
|
"spouse_joint_idx": spouse_idx if spouses else None,
|
|
"n_spouse_states": n_spouse_states,
|
|
})
|
|
|
|
return parent_idx, n_parent_states, children_specs
|
|
|
|
|
|
def apply_discretization(x, edges):
|
|
if len(edges) == 0:
|
|
return np.zeros(len(x), dtype=int).astype(str)
|
|
edges_sorted = sorted(edges)
|
|
labels = np.digitize(x, edges_sorted)
|
|
return labels.astype(str)
|
|
|
|
|
|
def discretize_all_continuous(df, edges, continuous_vars, raw_values,
|
|
max_passes=3, verbose=True):
|
|
df = df.copy()
|
|
policies = {v: None for v in continuous_vars}
|
|
|
|
for cycle in range(max_passes):
|
|
changed = False
|
|
for var in continuous_vars:
|
|
parent_idx, n_parent_states, children_specs = get_markov_blanket_specs(
|
|
df, edges, var)
|
|
new_edges = discretize_single_variable(
|
|
x=raw_values[var],
|
|
parent_joint_idx=parent_idx,
|
|
n_parent_states=n_parent_states,
|
|
children_specs=children_specs,
|
|
verbose=False,
|
|
)
|
|
old_edges = policies[var]
|
|
if old_edges is None or len(new_edges) != len(old_edges) or \
|
|
not np.allclose(sorted(new_edges), sorted(old_edges), atol=1e-6):
|
|
changed = True
|
|
policies[var] = new_edges
|
|
df[var] = apply_discretization(raw_values[var], new_edges)
|
|
if not changed:
|
|
break
|
|
|
|
return df, policies
|
|
|
|
|
|
if PGMPY_OK:
|
|
df_bn = df_enc.copy()
|
|
|
|
# Variables continuas a discretizar con L_DVBN REAL (las que resultaron
|
|
# numéricas de verdad en la Fase 1 -- típicamente solo Tumor_Size, ya
|
|
# que Age suele venir agrupada de SEER). Si ninguna resulta continua,
|
|
# no hay nada que discretizar y la celda se reduce a aprender la
|
|
# estructura.
|
|
continuous_vars_for_bn = []
|
|
raw_values_for_bn = {}
|
|
if "Edad" in df_bn.columns and AGE_IS_NUMERIC:
|
|
continuous_vars_for_bn.append("Edad")
|
|
raw_values_for_bn["Edad"] = df_bn["Edad"].astype(float).values
|
|
if "Tamano_tumor" in df_bn.columns and TUMORSIZE_IS_NUMERIC:
|
|
continuous_vars_for_bn.append("Tamano_tumor")
|
|
raw_values_for_bn["Tamano_tumor"] = df_bn["Tamano_tumor"].astype(float).values
|
|
|
|
_other_bn_candidates = [c for c in (cat_cols + num_cols) if c not in continuous_vars_for_bn]
|
|
bn_cols = continuous_vars_for_bn + [c for c in _other_bn_candidates if c in df_bn.columns] + ["outcome"]
|
|
|
|
|
|
df_bn_small = df_bn[bn_cols].astype(str)
|
|
|
|
for v in continuous_vars_for_bn:
|
|
try:
|
|
prelim = pd.qcut(raw_values_for_bn[v], q=4, duplicates="drop", labels=False)
|
|
except ValueError:
|
|
prelim = pd.cut(raw_values_for_bn[v], bins=4, labels=False)
|
|
df_bn_small[v] = pd.Series(prelim, index=df_bn.index).astype(str)
|
|
|
|
bn_train, bn_test = train_test_split(
|
|
df_bn_small, test_size=0.3, random_state=RANDOM_STATE,
|
|
stratify=df_bn_small["outcome"])
|
|
|
|
raw_train = {v: pd.Series(raw_values_for_bn[v], index=df_bn.index).loc[bn_train.index].values
|
|
for v in continuous_vars_for_bn}
|
|
raw_test = {v: pd.Series(raw_values_for_bn[v], index=df_bn.index).loc[bn_test.index].values
|
|
for v in continuous_vars_for_bn}
|
|
|
|
# ------------------------------------------------------------------
|
|
# Hill-Climbing con MÚLTIPLES REINICIOS -- exactamente lo que recomienda
|
|
# el propio paper de L_DVBN para K2: "K2 is typically run multiple times
|
|
# with different topological orderings, and the network with the
|
|
# highest likelihood is retained." Aquí la diversidad entre corridas se
|
|
# logra con remuestreo bootstrap de los datos de entrenamiento (barajar
|
|
# el ORDEN de las columnas no introduce variabilidad: esta versión de
|
|
# pgmpy da el mismo resultado sin importar el orden). Cada
|
|
# estructura candidata se evalúa con su puntaje K2 sobre los datos
|
|
# COMPLETOS (no el bootstrap), y nos quedamos con la de mayor puntaje.
|
|
# ------------------------------------------------------------------
|
|
N_RESTARTS = 10
|
|
# BDEU_ESS: tamaño de muestra equivalente del puntaje BDeu. El puntaje K2
|
|
# "puro" (equivalente a BDEU_ESS=1) resultó ser una penalización de
|
|
# complejidad demasiado agresiva -- rechazaba variables con efecto REAL
|
|
# y sustancial sobre 'outcome' simplemente por agregar categorías,
|
|
# incluso cuando el tamaño de muestra (decenas de miles de filas) sobraba
|
|
# para estimarlas con confianza. Con BDEU_ESS=1000, validamos que sigue
|
|
# rechazando correctamente una variable de RUIDO puro con la misma
|
|
# cardinalidad, mientras acepta variables con señal real -- un balance
|
|
# más razonable que el K2 por defecto.
|
|
BDEU_ESS = 1000
|
|
|
|
# ------------------------------------------------------------------
|
|
# "FORBIDDEN SEARCH" (el método que menciona el paper para aprender la
|
|
# estructura): en bnlearn esto es una BLACKLIST de arcos prohibidos. La
|
|
# forma más útil de construirla es imponer un ORDEN TEMPORAL/CAUSAL por
|
|
# niveles ("tiers"): se prohíbe todo arco que apunte de un nivel hacia
|
|
# uno anterior. Aquí usamos el orden clínicamente sensato:
|
|
#
|
|
# 1. Demografía (preexiste al diagnóstico)
|
|
# 2. Características del tumor (se determinan al diagnosticar)
|
|
# 3. Tratamiento (se decide después de conocer el tumor)
|
|
# 4. Desenlace (ocurre al final)
|
|
#
|
|
# Sin esta restricción, la búsqueda produce arcos causalmente absurdos
|
|
# (p.ej. 'outcome' -> 'Estadio', o 'Estadio' -> 'Edad': el desenlace causando
|
|
# el diagnóstico, o el estadio causando la edad) y desperdicia su
|
|
# "presupuesto de complejidad" en ellos, dejando a 'outcome' con menos
|
|
# padres reales de los que podría tener.
|
|
# ------------------------------------------------------------------
|
|
TIER_DEMOGRAFIA = ["Edad", "Race", "Estado_civil", "BRCA", "Densidad_BIRADS"]
|
|
TIER_TUMOR = ["Estadio", "Grado_histologico", "Tipo_histologico", "Subtipo_molecular", "Receptor_estrogeno",
|
|
"Receptor_progesterona", "Tamano_tumor", "Localizacion_mama", "Lateralidad",
|
|
"Metastasis", "CS_Lymph_Nodes", "Ganglios_positivos", "Invasion_linfovascular",
|
|
"Masa_espiculada", "Microcalcificaciones", "Multifocalidad", "HER2_IHQ"]
|
|
TIER_TRATAMIENTO = ["Tratamiento_quirurgico", "Radioterapia", "Quimioterapia", "Margenes"]
|
|
TIER_OUTCOME = ["outcome"]
|
|
|
|
def build_temporal_order(available_cols):
|
|
tiers = []
|
|
for tier in [TIER_DEMOGRAFIA, TIER_TUMOR, TIER_TRATAMIENTO, TIER_OUTCOME]:
|
|
present = [c for c in tier if c in available_cols]
|
|
if present:
|
|
tiers.append(present)
|
|
# Cualquier columna no clasificada va al primer tier (sin restricción extra)
|
|
classified = {c for t in tiers for c in t}
|
|
unclassified = [c for c in available_cols if c not in classified]
|
|
if unclassified:
|
|
tiers.insert(0, unclassified)
|
|
return tiers
|
|
|
|
TEMPORAL_ORDER = build_temporal_order(list(bn_cols))
|
|
|
|
def hill_climb_with_restarts(data, n_restarts=N_RESTARTS, max_indegree=4, random_state=0):
|
|
best_score = -np.inf
|
|
best_edges = None
|
|
scorer = BDeu(data, equivalent_sample_size=BDEU_ESS)
|
|
expert = ExpertKnowledge(temporal_order=TEMPORAL_ORDER)
|
|
for i in range(n_restarts):
|
|
boot = data.sample(n=len(data), replace=True, random_state=random_state + i)
|
|
hc_i = HillClimbSearch(boot)
|
|
boot_scorer = BDeu(boot, equivalent_sample_size=BDEU_ESS)
|
|
structure_i = hc_i.estimate(scoring_method=boot_scorer, max_indegree=max_indegree,
|
|
expert_knowledge=expert, show_progress=False)
|
|
score_i = scorer.score(structure_i)
|
|
if score_i > best_score:
|
|
best_score = score_i
|
|
best_edges = list(structure_i.edges())
|
|
return best_edges, best_score
|
|
|
|
edges, best_score = hill_climb_with_restarts(bn_train, random_state=RANDOM_STATE)
|
|
|
|
policies = {}
|
|
if continuous_vars_for_bn:
|
|
N_ALTERNATIONS = 2
|
|
for round_i in range(N_ALTERNATIONS):
|
|
bn_train, policies = discretize_all_continuous(
|
|
bn_train, edges, continuous_vars_for_bn, raw_train,
|
|
max_passes=3, verbose=True)
|
|
|
|
new_edges, new_score = hill_climb_with_restarts(bn_train, random_state=RANDOM_STATE + round_i * 100)
|
|
|
|
if set(new_edges) == set(edges):
|
|
edges = new_edges
|
|
break
|
|
edges = new_edges
|
|
|
|
for v in continuous_vars_for_bn:
|
|
bn_test[v] = apply_discretization(raw_test[v], policies[v])
|
|
|
|
# ------------------------------------------------------------------
|
|
# Expansión dirigida: más padres candidatos ESPECÍFICAMENTE para 'outcome'.
|
|
#
|
|
# Motivo: al predecir con TODA la evidencia observada, la predicción de
|
|
# 'outcome' depende SOLO de sus propios padres (si 'outcome' no tiene
|
|
# hijos, su Markov blanket con evidencia completa se reduce exactamente
|
|
# a eso). El puntaje K2 global optimiza el ajuste conjunto de TODAS las
|
|
# variables -- Hill-Climbing (incluso con reinicios) puede no agregar
|
|
# más padres a 'outcome' si eso no mejora el ajuste GLOBAL, aunque sí
|
|
# mejoraría la predicción específica de 'outcome'. Aquí hacemos una
|
|
# búsqueda greedy local SOLO para 'outcome' (el mismo mecanismo del K2
|
|
# original de Cooper & Herskovits, 1992, pero aplicado de forma más
|
|
# agresiva y enfocada en el nodo que realmente nos interesa predecir).
|
|
# ------------------------------------------------------------------
|
|
# 'outcome' (el desenlace de supervivencia) no puede tener sentido causal
|
|
# como padre de variables de diagnóstico/tratamiento (esas ocurren ANTES
|
|
# del desenlace) -- si Hill-Climbing lo orientó así (puede pasar: el
|
|
# puntaje K2 es puramente estadístico, no conoce el orden temporal real),
|
|
# forzamos a 'outcome' a ser un nodo terminal quitando esos arcos.
|
|
outcome_children = [v for (u, v) in edges if u == "outcome"]
|
|
if outcome_children:
|
|
edges = [(u, v) for (u, v) in edges if u != "outcome"]
|
|
|
|
MAX_OUTCOME_PARENTS = 10
|
|
current_parents = [u for (u, v) in edges if v == "outcome"]
|
|
other_edges = [(u, v) for (u, v) in edges if v != "outcome"]
|
|
scorer_final = BDeu(bn_train, equivalent_sample_size=BDEU_ESS)
|
|
current_score = scorer_final.local_score("outcome", current_parents)
|
|
candidates = [c for c in bn_cols if c != "outcome" and c not in current_parents]
|
|
|
|
# Si un candidato es una variable CONTINUA que L_DVBN discretizó SIN
|
|
# conocer a 'outcome' (porque la estructura global no la conectó), pudo
|
|
# quedar con 0 cortes (una sola categoría constante) -- una columna
|
|
# constante nunca puede ganar aquí, aunque la variable SÍ tenga relación
|
|
# real con 'outcome'. Por eso, para cada candidato continuo, lo
|
|
# re-discretizamos aquí tratando a 'outcome' como su HIJO hipotético
|
|
# (con los padres actuales como cónyuges) antes de evaluar su score --
|
|
# exactamente la situación para la que está pensado el Algoritmo 1 del
|
|
# paper. OJO: los objetos de puntaje (BDeu/K2) cachean los datos al
|
|
# construirse y NO ven mutaciones posteriores del DataFrame -- por eso
|
|
# creamos un DataFrame y un scorer nuevos para cada evaluación de este
|
|
# tipo, en vez de mutar bn_train y reusar scorer_final.
|
|
def _trial_column_for(cand):
|
|
if cand not in continuous_vars_for_bn:
|
|
return bn_train[cand].values, None
|
|
outcome_codes, _ = pd.factorize(bn_train["outcome"])
|
|
n_outcome_states = outcome_codes.max() + 1
|
|
spouse_idx, n_spouse_states = joint_index(bn_train, current_parents)
|
|
trial_edges_cand = discretize_single_variable(
|
|
x=raw_train[cand],
|
|
parent_joint_idx=np.zeros(len(bn_train), dtype=int),
|
|
n_parent_states=1,
|
|
children_specs=[{
|
|
"child_idx": outcome_codes,
|
|
"n_child_states": n_outcome_states,
|
|
"spouse_joint_idx": spouse_idx if current_parents else None,
|
|
"n_spouse_states": n_spouse_states,
|
|
}],
|
|
)
|
|
return apply_discretization(raw_train[cand], trial_edges_cand), trial_edges_cand
|
|
|
|
improved = True
|
|
while improved and len(current_parents) < MAX_OUTCOME_PARENTS and candidates:
|
|
improved = False
|
|
best_gain = 0
|
|
best_cand = None
|
|
best_cand_col = None
|
|
best_cand_edges = None
|
|
for cand in candidates:
|
|
trial_col, trial_edges_cand = _trial_column_for(cand)
|
|
df_trial = bn_train[current_parents + ["outcome"]].copy()
|
|
df_trial[cand] = trial_col
|
|
scorer_trial = BDeu(df_trial, equivalent_sample_size=BDEU_ESS)
|
|
new_score = scorer_trial.local_score("outcome", current_parents + [cand])
|
|
gain = new_score - current_score
|
|
if gain > best_gain:
|
|
best_gain = gain
|
|
best_cand = cand
|
|
best_cand_col = trial_col
|
|
best_cand_edges = trial_edges_cand
|
|
if best_cand is not None:
|
|
current_parents.append(best_cand)
|
|
candidates.remove(best_cand)
|
|
current_score += best_gain
|
|
improved = True
|
|
bn_train[best_cand] = best_cand_col
|
|
if best_cand_edges is not None:
|
|
policies[best_cand] = best_cand_edges
|
|
bn_test[best_cand] = apply_discretization(raw_test[best_cand], best_cand_edges)
|
|
|
|
edges = other_edges + [(p, "outcome") for p in current_parents]
|
|
|
|
hbn_model = BayesianNetwork(edges)
|
|
if PGMPY_NEW_API:
|
|
hbn_model.fit(bn_train, estimator=BayesianEstimator(prior_type="BDeu"))
|
|
else:
|
|
hbn_model.fit(bn_train, estimator=BayesianEstimator, prior_type="BDeu")
|
|
|
|
|
|
if PGMPY_OK:
|
|
# Visualizar la red (equivalente a la Fig. 1 del paper)
|
|
import networkx as nx
|
|
|
|
plt.figure(figsize=(10, 8))
|
|
G = nx.DiGraph(hbn_model.edges())
|
|
pos = nx.spring_layout(G, seed=RANDOM_STATE, k=0.8)
|
|
nx.draw(G, pos, with_labels=True, node_color="lightblue",
|
|
node_size=2500, font_size=8, arrowsize=15)
|
|
plt.title("Estructura de la Red Bayesiana Híbrida (aproximación)")
|
|
_guardar_figs("04")
|
|
|
|
|
|
if PGMPY_OK:
|
|
learned_edges = list(hbn_model.edges())
|
|
pd.DataFrame(learned_edges, columns=["origen", "destino"]).to_csv("./hbn_arcos.csv", index=False)
|
|
|
|
|
|
|
|
# 2) El resto de los arcos, agrupados por variable de origen.
|
|
other = sorted((u, v) for (u, v) in learned_edges if v != "outcome")
|
|
current_source = None
|
|
for u, v in other:
|
|
if u != current_source:
|
|
current_source = u
|
|
|
|
# 3) Conteo de conexiones por variable, para ver cuáles son más centrales.
|
|
all_nodes = sorted(hbn_model.nodes())
|
|
conn = pd.DataFrame({
|
|
"variable": all_nodes,
|
|
"padres": [sum(1 for (u, v) in learned_edges if v == node) for node in all_nodes],
|
|
"hijos": [sum(1 for (u, v) in learned_edges if u == node) for node in all_nodes],
|
|
})
|
|
conn["total"] = conn["padres"] + conn["hijos"]
|
|
|
|
|
|
if PGMPY_OK:
|
|
# Fuerza de cada arco, equivalente a `arc.strength` de bnlearn para redes
|
|
# aprendidas por puntaje (la Tabla S1 del paper reporta esta medida): el
|
|
# cambio en el puntaje de la red al ELIMINAR el arco, manteniendo el resto
|
|
# de la estructura fija.
|
|
#
|
|
# delta MUY NEGATIVO -> quitar el arco empeora mucho la red: arco fuerte
|
|
# delta cercano a 0 -> el arco aporta poco
|
|
# delta POSITIVO -> quitarlo incluso mejoraría el puntaje: prescindible
|
|
strength_scorer = BDeu(bn_train, equivalent_sample_size=BDEU_ESS)
|
|
|
|
strength_rows = []
|
|
for (u, v) in hbn_model.edges():
|
|
parents_v = [p for (p, c) in hbn_model.edges() if c == v]
|
|
score_with = strength_scorer.local_score(v, parents_v)
|
|
score_without = strength_scorer.local_score(v, [p for p in parents_v if p != u])
|
|
strength_rows.append({
|
|
"desde": u,
|
|
"hacia": v,
|
|
"delta_al_quitar": score_without - score_with,
|
|
})
|
|
|
|
arc_strength = (pd.DataFrame(strength_rows)
|
|
.sort_values("delta_al_quitar")
|
|
.reset_index(drop=True))
|
|
arc_strength["delta_al_quitar"] = arc_strength["delta_al_quitar"].round(1)
|
|
|
|
|
|
|
|
|
|
|
|
# --- Predicciones LR ---
|
|
X_test_lr = sm.add_constant(X_test[selected_features], has_constant="add")
|
|
y_pred_lr = final_lr_model.predict(X_test_lr)
|
|
|
|
auc_lr = roc_auc_score(y_test, y_pred_lr)
|
|
fpr_lr, tpr_lr, _ = roc_curve(y_test, y_pred_lr)
|
|
|
|
|
|
if PGMPY_OK:
|
|
# --- Predicciones HBN ---
|
|
infer = VariableElimination(hbn_model)
|
|
evidence_cols = [c for c in bn_test.columns if c != "outcome"]
|
|
|
|
y_pred_hbn = []
|
|
for _, row in bn_test.iterrows():
|
|
evidence = row[evidence_cols].to_dict()
|
|
# eliminar evidencia sobre variables no presentes en el modelo (por robustez)
|
|
evidence = {k: v for k, v in evidence.items() if k in hbn_model.nodes()}
|
|
try:
|
|
q = infer.query(variables=["outcome"], evidence=evidence, show_progress=False)
|
|
prob_survival = q.values[list(q.state_names["outcome"]).index("1")]
|
|
except Exception:
|
|
prob_survival = np.nan
|
|
y_pred_hbn.append(prob_survival)
|
|
|
|
bn_test = bn_test.assign(pred=y_pred_hbn).dropna(subset=["pred"])
|
|
auc_hbn = roc_auc_score(bn_test["outcome"].astype(int), bn_test["pred"])
|
|
fpr_hbn, tpr_hbn, _ = roc_curve(bn_test["outcome"].astype(int), bn_test["pred"])
|
|
|
|
|
|
plt.figure(figsize=(7, 6))
|
|
plt.plot(fpr_lr, tpr_lr, label=f"LR (AUC={auc_lr:.3f})", color="black")
|
|
if PGMPY_OK:
|
|
plt.plot(fpr_hbn, tpr_hbn, label=f"HBN (AUC={auc_hbn:.3f})", color="crimson")
|
|
plt.plot([0, 1], [0, 1], linestyle="--", color="gray")
|
|
plt.xlabel("1 - Especificidad")
|
|
plt.ylabel("Sensibilidad")
|
|
plt.title("Curvas ROC -- comparacion LR vs. HBN")
|
|
plt.legend()
|
|
_guardar_figs("04")
|
|
|
|
|
|
prob_true_lr, prob_pred_lr = calibration_curve(y_test, y_pred_lr, n_bins=10)
|
|
|
|
plt.figure(figsize=(7, 6))
|
|
plt.plot(prob_pred_lr, prob_true_lr, marker="o", label="LR", color="black")
|
|
if PGMPY_OK:
|
|
prob_true_hbn, prob_pred_hbn = calibration_curve(
|
|
bn_test["outcome"].astype(int), bn_test["pred"], n_bins=10)
|
|
plt.plot(prob_pred_hbn, prob_true_hbn, marker="o", label="HBN", color="crimson")
|
|
plt.plot([0, 1], [0, 1], linestyle="--", color="gray", label="Calibracion perfecta")
|
|
plt.xlabel("Probabilidad predicha")
|
|
plt.ylabel("Probabilidad observada")
|
|
plt.title("Curvas de calibracion")
|
|
plt.legend()
|
|
_guardar_figs("04")
|
|
|
|
|
|
try:
|
|
from dcurves import dca as dca_func, plot_graphs
|
|
DCURVES_OK = True
|
|
except ImportError:
|
|
DCURVES_OK = False
|
|
|
|
if DCURVES_OK:
|
|
if PGMPY_OK:
|
|
dca_df = pd.DataFrame({
|
|
"outcome": bn_test["outcome"].astype(int).values,
|
|
"lr_pred": y_pred_lr.reindex(bn_test.index).values,
|
|
"hbn_pred": bn_test["pred"].values,
|
|
})
|
|
modelnames = ["lr_pred", "hbn_pred"]
|
|
else:
|
|
dca_df = pd.DataFrame({
|
|
"outcome": y_test.values,
|
|
"lr_pred": y_pred_lr.values,
|
|
})
|
|
modelnames = ["lr_pred"]
|
|
|
|
dca_result = dca_func(
|
|
data=dca_df,
|
|
outcome="outcome",
|
|
modelnames=modelnames,
|
|
)
|
|
# No fijamos color_names: dca_result incluye automaticamente las curvas de
|
|
# referencia "all" y "none" ademas de cada modelo, asi que dejamos que la
|
|
# funcion elija su propia paleta con el numero correcto de colores.
|
|
plot_graphs(plot_df=dca_result, graph_type="net_benefit", y_limits=[-0.05, 0.5])
|
|
_guardar_figs("04")
|
|
|
|
|
|
def find_optimal_threshold(y_true, y_prob):
|
|
fpr, tpr, thresholds = roc_curve(y_true, y_prob)
|
|
youden_j = tpr - fpr
|
|
best_idx = np.argmax(youden_j)
|
|
return thresholds[best_idx]
|
|
|
|
|
|
def differentiation_metrics(y_true, y_prob, threshold=0.5):
|
|
y_pred_class = (y_prob >= threshold).astype(int)
|
|
tn, fp, fn, tp = confusion_matrix(y_true, y_pred_class).ravel()
|
|
acc = (tp + tn) / (tp + tn + fp + fn)
|
|
tpr = tp / (tp + fn) # sensibilidad
|
|
tnr = tn / (tn + fp) # especificidad
|
|
ppv = tp / (tp + fp) if (tp + fp) > 0 else np.nan
|
|
npv = tn / (tn + fn) if (tn + fn) > 0 else np.nan
|
|
return {"ACC": acc, "TPR": tpr, "TNR": tnr, "PPV": ppv, "NPV": npv}
|
|
|
|
|
|
rows = []
|
|
|
|
# --- Umbral por defecto (0.5) -- lo que ya teniamos ---
|
|
rows.append({"Model": "LR", "Umbral": 0.50,
|
|
**differentiation_metrics(y_test.values, y_pred_lr.values, threshold=0.5)})
|
|
if PGMPY_OK:
|
|
rows.append({"Model": "HBN tabular", "Umbral": 0.50,
|
|
**differentiation_metrics(bn_test["outcome"].astype(int).values,
|
|
bn_test["pred"].values, threshold=0.5)})
|
|
|
|
# --- Umbral optimo (Youden) -- calculado POR SEPARADO para cada modelo ---
|
|
thr_lr = find_optimal_threshold(y_test.values, y_pred_lr.values)
|
|
rows.append({"Model": "LR", "Umbral": round(thr_lr, 3),
|
|
**differentiation_metrics(y_test.values, y_pred_lr.values, threshold=thr_lr)})
|
|
if PGMPY_OK:
|
|
thr_hbn = find_optimal_threshold(bn_test["outcome"].astype(int).values, bn_test["pred"].values)
|
|
rows.append({"Model": "HBN tabular", "Umbral": round(thr_hbn, 3),
|
|
**differentiation_metrics(bn_test["outcome"].astype(int).values,
|
|
bn_test["pred"].values, threshold=thr_hbn)})
|
|
|
|
metrics_table = pd.DataFrame(rows).set_index(["Model", "Umbral"]).round(2)
|
|
metrics_table.to_csv("./metricas_diferenciacion.csv")
|
|
pd.DataFrame([{"modelo": "LR", "AUC": auc_lr}] + ([{"modelo": "HBN", "AUC": auc_hbn}] if PGMPY_OK else [])).round(4).to_csv("./auc_validacion_interna.csv", index=False)
|
|
|
|
|
|
# ---- 6B.1 Parámetros y carga de la población natural ----
|
|
CSV_NATURAL = "./dataframe_poblacion_natural.csv"
|
|
RUN_LR_NATURAL = True # False: se salta toda la Fase 6B
|
|
MAX_SEARCH_ROWS_NAT = 30000 # filas para la BÚSQUEDA stepwise en la población natural (el ajuste final usa todo el train)
|
|
TEST_SIZE_NAT = 0.30
|
|
|
|
import os
|
|
from sklearn.metrics import average_precision_score, brier_score_loss
|
|
if RUN_LR_NATURAL and not os.path.exists(CSV_NATURAL):
|
|
RUN_LR_NATURAL = False
|
|
|
|
if RUN_LR_NATURAL:
|
|
dn_raw = pd.read_csv(CSV_NATURAL, dtype=str)
|
|
dn_raw = dn_raw[dn_raw["Outcome_cat"].isin(["Sobrevive", "Muerte"])].reset_index(drop=True)
|
|
en_bal = dn_raw["en_balanceado"].astype(int).values == 1
|
|
dn = dn_raw[list(rename_map.keys())].rename(columns=rename_map).copy()
|
|
if _race_col and _race_col in dn_raw.columns:
|
|
dn["Race"] = dn_raw[_race_col]
|
|
for c in cat_cols:
|
|
dn[c] = dn[c].fillna("Desconocido").astype(str)
|
|
y_nat = (dn["Outcome_cat"] == "Sobrevive").astype(int)
|
|
|
|
# Verifica que las filas balanceadas del archivo natural sean EXACTAMENTE las del archivo balanceado, en el mismo orden
|
|
idx_b = np.where(en_bal)[0]
|
|
assert len(idx_b) == len(df), f"El archivo natural trae {len(idx_b)} filas balanceadas y df tiene {len(df)}"
|
|
for c in ["Estadio", "Tratamiento_quirurgico", "Outcome_cat"]:
|
|
assert (dn.loc[idx_b, c].values == df[c].values).all(), f"Las filas balanceadas no coinciden en {c}: regenera el archivo natural con el balanceo actual"
|
|
pos_en_natural = pd.Series(idx_b, index=df.index) # fila de df -> fila de dn
|
|
train_bal_nat = set(pos_en_natural.loc[X_train.index]) # filas naturales que usó el modelo balanceado para entrenar
|
|
|
|
|
|
# ---- 6B.2 Codificación (referencia = categoría más frecuente) y partición natural ----
|
|
if RUN_LR_NATURAL:
|
|
Xn_full = pd.get_dummies(dn[cat_cols], drop_first=False).astype(float) # todas las categorías
|
|
ref_cols = {}
|
|
for c in cat_cols:
|
|
cols_c = [k for k in Xn_full.columns if k.startswith(c + "_") and k[len(c) + 1:] in set(dn[c])]
|
|
ref_cols[c] = Xn_full[cols_c].sum().idxmax() # la más frecuente
|
|
Xn = Xn_full.drop(columns=list(ref_cols.values()))
|
|
|
|
tr_n, te_n = train_test_split(np.arange(len(dn)), test_size=TEST_SIZE_NAT, random_state=RANDOM_STATE, stratify=y_nat)
|
|
Xn_train, Xn_test = Xn.iloc[tr_n], Xn.iloc[te_n]; yn_train, yn_test = y_nat.iloc[tr_n], y_nat.iloc[te_n]
|
|
cte = np.array([i for i in te_n if i not in train_bal_nat]) # conjunto de prueba COMÚN
|
|
|
|
cte_all = [c for c in Xn_train.columns if Xn_train[c].nunique() > 1]
|
|
Xn_train, Xn_test = Xn_train[cte_all], Xn_test[cte_all]
|
|
pre_n = univariate_prefilter(Xn_train, yn_train, alpha=_prefilter_alpha, verbose=True)
|
|
pre_n = sorted(pre_n, key=lambda t: -t[2])[:MAX_CANDIDATES]
|
|
pre_cols_n = [t[0] for t in pre_n]
|
|
|
|
|
|
# ---- 6B.3 Stepwise y ajuste final sobre la población natural ----
|
|
if RUN_LR_NATURAL:
|
|
if len(Xn_train) > MAX_SEARCH_ROWS_NAT:
|
|
_si, _ = train_test_split(Xn_train.index, train_size=MAX_SEARCH_ROWS_NAT, random_state=RANDOM_STATE, stratify=yn_train)
|
|
Xs, ys = Xn_train.loc[_si, pre_cols_n], yn_train.loc[_si]
|
|
else:
|
|
Xs, ys = Xn_train[pre_cols_n], yn_train
|
|
sel_nat = stepwise_selection(Xs, ys, verbose=False)
|
|
lr_nat = sm.Logit(yn_train, sm.add_constant(Xn_train[sel_nat])).fit(disp=0, method="bfgs", maxiter=300)
|
|
ci = np.exp(lr_nat.conf_int()); ci["OR_supervivencia"] = np.exp(lr_nat.params); ci.columns = ["2.5%", "97.5%", "OR_supervivencia"]
|
|
ci["p"] = lr_nat.pvalues
|
|
or_table_nat = ci.round(3)
|
|
or_table_nat.to_csv("./or_lr_poblacion_natural.csv")
|
|
|
|
|
|
# ---- 6B.4 Comparación en el MISMO conjunto de prueba natural ----
|
|
if RUN_LR_NATURAL:
|
|
def _logit(p): p = np.clip(p, 1e-9, 1 - 1e-9); return np.log(p / (1 - p))
|
|
def _sig(z): return 1 / (1 + np.exp(-z))
|
|
prev_nat = float(y_nat.mean()); prev_bal = float(y_train.mean())
|
|
shift = np.log(prev_nat / (1 - prev_nat)) - np.log(prev_bal / (1 - prev_bal)) # corrección de intercepto (outcome = supervivencia)
|
|
|
|
Xc = Xn.iloc[cte]; yc = y_nat.iloc[cte].values; stage_c = dn["Estadio"].iloc[cte].values
|
|
p_nat = lr_nat.predict(sm.add_constant(Xc[sel_nat], has_constant="add")).values
|
|
Xb_c = Xn_full.iloc[cte].reindex(columns=X_train.columns, fill_value=0.0) # mismas columnas que el modelo balanceado
|
|
p_bal_raw = final_lr_model.predict(sm.add_constant(Xb_c[selected_features], has_constant="add")).values
|
|
p_bal_cor = _sig(_logit(p_bal_raw) + shift)
|
|
|
|
def _fila(nombre, p):
|
|
m3 = np.isin(stage_c, ["I", "II", "III"])
|
|
auc3 = roc_auc_score(yc[m3], p[m3]) if len(set(yc[m3])) == 2 else np.nan
|
|
return {"modelo": nombre, "AUC": roc_auc_score(yc, p), "AUC estadios I-III": auc3,
|
|
"PR-AUC (muerte)": average_precision_score(1 - yc, 1 - p), "Brier": brier_score_loss(yc, p),
|
|
"prob. media predicha": p.mean(), "prob. media real": yc.mean()}
|
|
comp = pd.DataFrame([_fila("LR balanceada (probabilidades crudas)", p_bal_raw),
|
|
_fila("LR balanceada + corrección de intercepto", p_bal_cor),
|
|
_fila("LR población natural", p_nat)]).set_index("modelo").round(3)
|
|
comp.to_csv("./comparacion_lr_balanceada_vs_natural.csv")
|
|
filas = []
|
|
for s in sorted(set(stage_c)):
|
|
m = stage_c == s
|
|
if m.sum() >= 50 and len(set(yc[m])) == 2:
|
|
filas.append({"Estadio": s, "n": int(m.sum()), "muertes": int((1 - yc[m]).sum()),
|
|
"AUC LR balanceada": round(roc_auc_score(yc[m], p_bal_raw[m]), 3), "AUC LR natural": round(roc_auc_score(yc[m], p_nat[m]), 3)})
|
|
pd.DataFrame(filas).set_index("Estadio").to_csv("./auc_por_estadio_lr_natural.csv")
|
|
|
|
|
|
|
|
|
|
# ---- 6B.6 LR natural SIN tratamiento ----
|
|
if RUN_LR_NATURAL:
|
|
TRAT_VARS = ["Tratamiento_quirurgico", "Radioterapia", "Quimioterapia"]
|
|
cols_nt = [c for c in Xn_train.columns if not any(c.startswith(t + "_") for t in TRAT_VARS)]
|
|
pre_nt = univariate_prefilter(Xn_train[cols_nt], yn_train, alpha=_prefilter_alpha, verbose=False)
|
|
pre_cols_nt = [t[0] for t in sorted(pre_nt, key=lambda t: -t[2])[:MAX_CANDIDATES]]
|
|
Xs2, ys2 = (Xn_train.loc[_si, pre_cols_nt], yn_train.loc[_si]) if len(Xn_train) > MAX_SEARCH_ROWS_NAT else (Xn_train[pre_cols_nt], yn_train)
|
|
sel_nt = stepwise_selection(Xs2, ys2, verbose=False)
|
|
lr_nt = sm.Logit(yn_train, sm.add_constant(Xn_train[sel_nt])).fit(disp=0, method="bfgs", maxiter=300)
|
|
ci2 = np.exp(lr_nt.conf_int()); ci2["OR_supervivencia"] = np.exp(lr_nt.params); ci2.columns = ["2.5%", "97.5%", "OR_supervivencia"]; ci2["p"] = lr_nt.pvalues
|
|
ci2.round(3).to_csv("./or_lr_poblacion_natural_sin_tratamiento.csv")
|
|
|
|
p_nt = lr_nt.predict(sm.add_constant(Xc[sel_nt], has_constant="add")).values
|
|
comp2 = pd.concat([comp, pd.DataFrame([_fila("LR población natural SIN tratamiento", p_nt)]).set_index("modelo").round(3)])
|
|
comp2.to_csv("./comparacion_lr_balanceada_vs_natural.csv")
|
|
filas = []
|
|
for s in sorted(set(stage_c)):
|
|
m = stage_c == s
|
|
if m.sum() >= 50 and len(set(yc[m])) == 2:
|
|
filas.append({"Estadio": s, "n": int(m.sum()), "muertes": int((1 - yc[m]).sum()),
|
|
"AUC natural": round(roc_auc_score(yc[m], p_nat[m]), 3), "AUC natural SIN tratamiento": round(roc_auc_score(yc[m], p_nt[m]), 3)})
|
|
pd.DataFrame(filas).set_index("Estadio").to_csv("./auc_por_estadio_lr_natural_sin_tratamiento.csv")
|
|
|
|
|
|
# ---- 6B.7 Calibración por deciles de riesgo de MUERTE (población natural) ----
|
|
if RUN_LR_NATURAL:
|
|
def calib_deciles(p_sup, nombre):
|
|
riesgo = 1 - p_sup; muerte = 1 - yc
|
|
d = pd.DataFrame({"riesgo": riesgo, "muerte": muerte})
|
|
d["decil"] = pd.qcut(d["riesgo"].rank(method="first"), 10, labels=False) + 1
|
|
t = d.groupby("decil").agg(n=("muerte", "size"), muertes=("muerte", "sum"),
|
|
riesgo_predicho=("riesgo", "mean"), riesgo_observado=("muerte", "mean")).round(4)
|
|
t["modelo"] = nombre
|
|
return t
|
|
tab_cal = pd.concat([calib_deciles(p_nat, "natural"), calib_deciles(p_nt, "natural sin tratamiento")]).reset_index()
|
|
tab_cal.to_csv("./calibracion_deciles_lr_natural.csv", index=False)
|
|
|
|
|
|
|
|
BOOTSTRAP_IDX_PATH = "./bootstrap_indices.npy"
|
|
|
|
bootstrap_indices = np.load(BOOTSTRAP_IDX_PATH)
|
|
|
|
assert bootstrap_indices.shape[1] == len(df), (
|
|
f"bootstrap_indices tiene {bootstrap_indices.shape[1]} filas por réplica, pero "
|
|
f"df tiene {len(df)} -- revisa que bootstrapping_SEER.ipynb se haya corrido sobre "
|
|
f"el mismo CSV balanceado que este notebook.")
|
|
|
|
# --- Controles de costo (ajustar antes de una corrida grande) ---
|
|
N_BOOTSTRAP_RUN = 60 # <-- ~27 s/réplica con HBN en 5,452 filas (~27 min). Máx. 200
|
|
TIEMPO_MAX_S = 2700 # <-- tope de seguridad: el bucle se detiene solo y usa lo calculado
|
|
INCLUIR_HBN_EN_BOOTSTRAP = True # <-- False = solo LR (mucho más rápido)
|
|
N_RESTARTS_BOOT = 3 # reinicios de Hill-Climbing POR RÉPLICA
|
|
# (el ajuste principal de la Fase 5 usa 10)
|
|
|
|
|
|
def ejecutar_replica_pipeline(df_b, seed):
|
|
out = {"auc_lr": np.nan, "auc_hbn": np.nan,
|
|
"n_selected_lr": np.nan, "n_parents_hbn": np.nan, "coefs": None, "padres": None}
|
|
|
|
# --- outcome + codificacion (Fases 2-3, condensado) ---
|
|
df_b = df_b.copy()
|
|
df_b["outcome"] = (df_b["Outcome_cat"] == "Sobrevive").astype(int)
|
|
df_enc_b = df_b.copy()
|
|
for c in cat_cols:
|
|
df_enc_b[c] = df_enc_b[c].fillna("Desconocido").astype(str)
|
|
|
|
X_b = pd.get_dummies(df_enc_b[cat_cols + num_cols], drop_first=True).astype(float)
|
|
y_b = df_enc_b["outcome"]
|
|
_const = [c for c in X_b.columns if X_b[c].nunique() <= 1]
|
|
if _const:
|
|
X_b = X_b.drop(columns=_const)
|
|
if y_b.nunique() < 2:
|
|
return out
|
|
|
|
X_train_b, X_test_b, y_train_b, y_test_b = train_test_split(
|
|
X_b, y_b, test_size=0.3, random_state=seed, stratify=y_b)
|
|
_const_tr = [c for c in X_train_b.columns if X_train_b[c].nunique() <= 1]
|
|
if _const_tr:
|
|
X_train_b = X_train_b.drop(columns=_const_tr)
|
|
X_test_b = X_test_b.drop(columns=_const_tr)
|
|
|
|
# --- LR stepwise (Fase 4, condensado -- mismo alpha_in/alpha_out) ---
|
|
kept_b = univariate_prefilter(X_train_b, y_train_b, alpha=_prefilter_alpha, verbose=False)
|
|
kept_b.sort(key=lambda t: t[2], reverse=True)
|
|
prefiltered_b = [c for c, _, _ in kept_b[:MAX_CANDIDATES]]
|
|
if not prefiltered_b:
|
|
return out
|
|
|
|
if X_train_b.shape[0] > MAX_SEARCH_ROWS:
|
|
_idx_b, _ = train_test_split(X_train_b.index, train_size=MAX_SEARCH_ROWS,
|
|
random_state=seed, stratify=y_train_b)
|
|
X_search_b, y_search_b = X_train_b.loc[_idx_b, prefiltered_b], y_train_b.loc[_idx_b]
|
|
else:
|
|
X_search_b, y_search_b = X_train_b[prefiltered_b], y_train_b
|
|
|
|
selected_b = stepwise_selection(X_search_b, y_search_b, verbose=False)
|
|
out["n_selected_lr"] = len(selected_b)
|
|
if selected_b:
|
|
model_b = _safe_fit_logit(y_train_b, sm.add_constant(X_train_b[selected_b]))
|
|
if model_b is not None:
|
|
out["coefs"] = model_b.params.drop("const", errors="ignore").to_dict()
|
|
X_test_lr_b = sm.add_constant(X_test_b[selected_b], has_constant="add")
|
|
out["auc_lr"] = roc_auc_score(y_test_b, model_b.predict(X_test_lr_b))
|
|
|
|
# --- HBN (Fase 5, condensado) ---
|
|
if INCLUIR_HBN_EN_BOOTSTRAP and PGMPY_OK:
|
|
try:
|
|
df_bn_b = df_enc_b.copy()
|
|
bn_cols_b = [c for c in (cat_cols + num_cols) if c in df_bn_b.columns] + ["outcome"]
|
|
df_bn_small_b = df_bn_b[bn_cols_b].astype(str)
|
|
|
|
bn_train_b, bn_test_b = train_test_split(
|
|
df_bn_small_b, test_size=0.3, random_state=seed,
|
|
stratify=df_bn_small_b["outcome"])
|
|
|
|
edges_b, _ = hill_climb_with_restarts(
|
|
bn_train_b, n_restarts=N_RESTARTS_BOOT, random_state=seed)
|
|
|
|
# outcome como nodo terminal (igual que en la Fase 5)
|
|
edges_b = [(u, v) for (u, v) in edges_b if u != "outcome"]
|
|
current_parents_b = [u for (u, v) in edges_b if v == "outcome"]
|
|
other_edges_b = [(u, v) for (u, v) in edges_b if v != "outcome"]
|
|
scorer_b = BDeu(bn_train_b, equivalent_sample_size=BDEU_ESS)
|
|
current_score_b = scorer_b.local_score("outcome", current_parents_b)
|
|
candidates_b = [c for c in bn_cols_b if c != "outcome" and c not in current_parents_b]
|
|
|
|
improved = True
|
|
while improved and len(current_parents_b) < MAX_OUTCOME_PARENTS and candidates_b:
|
|
improved = False
|
|
best_gain, best_cand = 0, None
|
|
for cand in candidates_b:
|
|
df_trial = bn_train_b[current_parents_b + ["outcome"]].copy()
|
|
df_trial[cand] = bn_train_b[cand].values
|
|
scorer_trial = BDeu(df_trial, equivalent_sample_size=BDEU_ESS)
|
|
gain = (scorer_trial.local_score("outcome", current_parents_b + [cand])
|
|
- current_score_b)
|
|
if gain > best_gain:
|
|
best_gain, best_cand = gain, cand
|
|
if best_cand is not None:
|
|
current_parents_b.append(best_cand)
|
|
candidates_b.remove(best_cand)
|
|
current_score_b += best_gain
|
|
improved = True
|
|
|
|
edges_b = other_edges_b + [(p, "outcome") for p in current_parents_b]
|
|
out["n_parents_hbn"] = len(current_parents_b)
|
|
out["padres"] = list(current_parents_b)
|
|
|
|
hbn_b = BayesianNetwork(edges_b)
|
|
if PGMPY_NEW_API:
|
|
hbn_b.fit(bn_train_b, estimator=BayesianEstimator(prior_type="BDeu"))
|
|
else:
|
|
hbn_b.fit(bn_train_b, estimator=BayesianEstimator, prior_type="BDeu")
|
|
|
|
infer_b = VariableElimination(hbn_b)
|
|
evid_cols_b = [c for c in bn_test_b.columns if c != "outcome"]
|
|
preds_b = []
|
|
for _, row in bn_test_b.iterrows():
|
|
evidence = {k: v for k, v in row[evid_cols_b].to_dict().items()
|
|
if k in hbn_b.nodes()}
|
|
try:
|
|
q = infer_b.query(variables=["outcome"], evidence=evidence, show_progress=False)
|
|
preds_b.append(q.values[list(q.state_names["outcome"]).index("1")])
|
|
except Exception:
|
|
preds_b.append(np.nan)
|
|
bn_test_b = bn_test_b.assign(pred=preds_b).dropna(subset=["pred"])
|
|
out["auc_hbn"] = roc_auc_score(bn_test_b["outcome"].astype(int), bn_test_b["pred"])
|
|
except Exception as e:
|
|
pass
|
|
|
|
return out
|
|
|
|
|
|
import time
|
|
|
|
auc_lr_boot, auc_hbn_boot = [], []
|
|
n_sel_boot, n_par_boot = [], []
|
|
sel_boot_filas = []
|
|
_cats_largo = sorted(cat_cols, key=len, reverse=True)
|
|
def _var_de(t):
|
|
return next((c for c in _cats_largo if t.startswith(c + "_")), t)
|
|
|
|
t0 = time.time()
|
|
n_hechas = 0
|
|
for b in range(N_BOOTSTRAP_RUN):
|
|
if time.time() - t0 > TIEMPO_MAX_S:
|
|
break
|
|
idx = bootstrap_indices[b]
|
|
df_b = df.iloc[idx].reset_index(drop=True)
|
|
res = ejecutar_replica_pipeline(df_b, seed=RANDOM_STATE + b)
|
|
auc_lr_boot.append(res["auc_lr"])
|
|
auc_hbn_boot.append(res["auc_hbn"])
|
|
n_sel_boot.append(res["n_selected_lr"])
|
|
n_par_boot.append(res["n_parents_hbn"])
|
|
if res["coefs"] is not None:
|
|
sel_boot_filas.append({"replica": b, "modelo": "LR", "variable": "", "termino": "(replica)", "coef": np.nan})
|
|
sel_boot_filas += [{"replica": b, "modelo": "LR", "variable": _var_de(t), "termino": t, "coef": v} for t, v in res["coefs"].items()]
|
|
if res["padres"] is not None:
|
|
sel_boot_filas.append({"replica": b, "modelo": "HBN", "variable": "", "termino": "(replica)", "coef": np.nan})
|
|
sel_boot_filas += [{"replica": b, "modelo": "HBN", "variable": p_, "termino": p_, "coef": np.nan} for p_ in res["padres"]]
|
|
n_hechas += 1
|
|
|
|
|
|
pd.DataFrame(sel_boot_filas).to_csv("./seleccion_bootstrap.csv", index=False)
|
|
|
|
|
|
def ic_95(arr):
|
|
arr = np.array([a for a in arr if not np.isnan(a)])
|
|
if len(arr) == 0:
|
|
return (np.nan, np.nan, 0)
|
|
lo, hi = np.percentile(arr, [2.5, 97.5])
|
|
return (lo, hi, len(arr))
|
|
|
|
resumen_boot = []
|
|
for nombre, arr in [("LR (stepwise)", auc_lr_boot),
|
|
("HBN (CPT tabular)", auc_hbn_boot)]:
|
|
lo, hi, n_validas = ic_95(arr)
|
|
resumen_boot.append({
|
|
"modelo": nombre,
|
|
"AUC medio": np.nanmean(arr) if n_validas else np.nan,
|
|
"IC 95% lo": lo, "IC 95% hi": hi, "replicas validas": n_validas,
|
|
})
|
|
|
|
tabla_bootstrap = pd.DataFrame(resumen_boot).round(3)
|
|
tabla_bootstrap.to_csv("./auc_bootstrap.csv", index=False)
|
|
|
|
|
|
# Diferencia pareada LR - HBN (misma réplica)
|
|
_d = np.array(auc_lr_boot) - np.array(auc_hbn_boot)
|
|
_d = _d[~np.isnan(_d)]
|
|
if len(_d):
|
|
pd.DataFrame([{"dif_AUC_LR_menos_HBN": _d.mean(), "IC95_inf": np.percentile(_d, 2.5), "IC95_sup": np.percentile(_d, 97.5), "pct_replicas_LR_gana": (_d > 0).mean() * 100}]).round(4).to_csv("./auc_bootstrap_diferencia.csv", index=False)
|
|
|
|
|
|
import time
|
|
|
|
PROP_CSV = "./propuestas_categorizacion.csv"
|
|
N_SPLITS_PROP = 5 # particiones 70/30 distintas por propuesta (mismas semillas para todas -> comparación pareada)
|
|
PROPUESTAS_A_CORRER = None # None = todas las del CSV; o una lista, p. ej. ["P1_actual", "P6_clinico_fijo"]
|
|
INCLUIR_HBN_PROP = True # False = solo LR (mucho más rápido)
|
|
TIEMPO_MAX_PROP_S = 3600 # tope de seguridad: se detiene solo y usa lo calculado
|
|
|
|
prop = pd.read_csv(PROP_CSV, dtype=str)
|
|
assert len(prop) == len(df), (f"propuestas_categorizacion.csv tiene {len(prop)} filas y df {len(df)}: "
|
|
"deben salir del MISMO balanceo (mismo orden de filas)")
|
|
|
|
ids = sorted({c.split("__", 1)[1] for c in prop.columns if "__" in c})
|
|
if PROPUESTAS_A_CORRER is not None:
|
|
ids = [i for i in ids if i in PROPUESTAS_A_CORRER]
|
|
|
|
_flag_prev = INCLUIR_HBN_EN_BOOTSTRAP
|
|
INCLUIR_HBN_EN_BOOTSTRAP = INCLUIR_HBN_PROP
|
|
|
|
resultados_prop = []
|
|
t0 = time.time()
|
|
parar = False
|
|
for pid in ids:
|
|
df_p = df.copy()
|
|
k_edad = k_tumor = None
|
|
if f"Age_group__{pid}" in prop.columns:
|
|
df_p["Edad"] = prop[f"Age_group__{pid}"].values
|
|
k_edad = df_p["Edad"].nunique()
|
|
if f"Tumor_group__{pid}" in prop.columns and "Tamano_tumor" in df_p.columns:
|
|
df_p["Tamano_tumor"] = prop[f"Tumor_group__{pid}"].values
|
|
k_tumor = df_p["Tamano_tumor"].nunique(dropna=False)
|
|
for s in range(N_SPLITS_PROP):
|
|
if time.time() - t0 > TIEMPO_MAX_PROP_S:
|
|
parar = True
|
|
break
|
|
res = ejecutar_replica_pipeline(df_p, seed=RANDOM_STATE + s)
|
|
resultados_prop.append({"propuesta": pid, "split": s, "K_edad": k_edad, "K_tumor": k_tumor, **res})
|
|
if parar:
|
|
break
|
|
|
|
INCLUIR_HBN_EN_BOOTSTRAP = _flag_prev
|
|
res_prop = pd.DataFrame(resultados_prop)
|
|
res_prop.to_csv("./resultados_propuestas_categorizacion.csv", index=False)
|
|
|
|
resumen_prop = (res_prop.groupby("propuesta")
|
|
.agg(K_edad=("K_edad", "first"), K_tumor=("K_tumor", "first"),
|
|
AUC_LR=("auc_lr", "mean"), sd_LR=("auc_lr", "std"),
|
|
AUC_HBN=("auc_hbn", "mean"), sd_HBN=("auc_hbn", "std"),
|
|
vars_LR=("n_selected_lr", "mean"), padres_HBN=("n_parents_hbn", "mean"),
|
|
n_splits=("split", "count")).round(3))
|
|
resumen_prop.sort_values("AUC_LR", ascending=False).to_csv("./resumen_propuestas_categorizacion.csv")
|
|
|
|
# Diferencia pareada contra la propuesta base (mismas particiones)
|
|
base = "P1_actual" if "P1_actual" in res_prop["propuesta"].values else res_prop["propuesta"].iloc[0]
|
|
b = res_prop[res_prop["propuesta"] == base].set_index("split")
|
|
filas = []
|
|
for pid in res_prop["propuesta"].unique():
|
|
if pid == base:
|
|
continue
|
|
x = res_prop[res_prop["propuesta"] == pid].set_index("split")
|
|
j = b.join(x, lsuffix="_b", rsuffix="_x", how="inner")
|
|
filas.append({"propuesta": pid, f"ΔAUC_LR vs {base}": (j["auc_lr_x"] - j["auc_lr_b"]).mean(),
|
|
f"ΔAUC_HBN vs {base}": (j["auc_hbn_x"] - j["auc_hbn_b"]).mean(),
|
|
"splits_comparados": len(j)})
|
|
pd.DataFrame(filas).round(4).to_csv("./delta_auc_propuestas_vs_base.csv", index=False)
|