42161eb612
Stages 01-06 (depuration, MCA balancing and categorization, bootstrap indices, stepwise LR and hybrid Bayesian network, survival curves, risk factors), settings in model.toml, run.py writing each stage's files and pipeline.py as the runner that replaces ejecutar_pipeline.py. New extras seer-survival and seer-survival-dca; experiments/ excluded from the wheel.
155 lines
8.2 KiB
Python
155 lines
8.2 KiB
Python
"""The logistic regression on the NATURAL population (every patient with a known outcome, before the undersampling),
|
|
compared with the balanced model on the same common test set; apart from the modeling nodes (`modeling.py`). Plain
|
|
functions with no I/O. Ported from `04_modelado.py` (phase 6B).
|
|
|
|
The balanced model is compared both with its raw probabilities and with an intercept correction for the prevalence shift;
|
|
the natural model is fitted with and without the treatment variables. The common test set is the natural test patients
|
|
that the balanced model did not train on.
|
|
"""
|
|
|
|
from dataclasses import dataclass
|
|
|
|
import numpy as np
|
|
import pandas as pd
|
|
import statsmodels.api as sm
|
|
from sklearn.metrics import average_precision_score, brier_score_loss, roc_auc_score
|
|
from sklearn.model_selection import train_test_split
|
|
|
|
from models.cama.seer_survival import lr_selection
|
|
from models.cama.seer_survival.settings import ModelingSettings
|
|
|
|
|
|
@dataclass(frozen=True, eq=False)
|
|
class NaturalResults:
|
|
odds_ratios: pd.DataFrame # LR on the natural population
|
|
odds_ratios_no_treatment: pd.DataFrame
|
|
comparison: pd.DataFrame # balanced raw / corrected / natural / natural without treatment
|
|
auc_by_stage: pd.DataFrame # balanced vs natural
|
|
auc_by_stage_no_treatment: pd.DataFrame
|
|
calibration_deciles: pd.DataFrame
|
|
|
|
|
|
def _odds_table(model) -> pd.DataFrame:
|
|
ci = np.exp(model.conf_int())
|
|
ci["OR_supervivencia"] = np.exp(model.params)
|
|
ci.columns = ["2.5%", "97.5%", "OR_supervivencia"]
|
|
ci["p"] = model.pvalues
|
|
return ci.round(3)
|
|
|
|
|
|
def _logit(p):
|
|
p = np.clip(p, 1e-9, 1 - 1e-9)
|
|
return np.log(p / (1 - p))
|
|
|
|
|
|
def _sigmoid(z):
|
|
return 1 / (1 + np.exp(-z))
|
|
|
|
|
|
def _stage_aucs(stage, y, preds: dict[str, np.ndarray], min_n: int = 50) -> pd.DataFrame:
|
|
"""Per stage with at least `min_n` patients and both outcomes: n, deaths and the AUC of each prediction."""
|
|
rows = []
|
|
for s in sorted(set(stage)):
|
|
m = stage == s
|
|
if m.sum() >= min_n and len(set(y[m])) == 2:
|
|
rows.append({"Estadio": s, "n": int(m.sum()), "muertes": int((1 - y[m]).sum()),
|
|
**{name: round(roc_auc_score(y[m], p[m]), 3) for name, p in preds.items()}})
|
|
return pd.DataFrame(rows).set_index("Estadio")
|
|
|
|
|
|
def _deciles(p_survival, y, name: str) -> pd.DataFrame:
|
|
risk, death = 1 - p_survival, 1 - y
|
|
d = pd.DataFrame({"riesgo": risk, "muerte": death})
|
|
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"] = name
|
|
return t
|
|
|
|
|
|
def fit_natural(natural_raw: pd.DataFrame, df: pd.DataFrame, rename_map: dict, race_column: str | None,
|
|
cat_cols: list[str], X_train: pd.DataFrame, y_train: pd.Series, final_lr_model, selected: list[str],
|
|
s: ModelingSettings) -> NaturalResults:
|
|
dn_raw = natural_raw[natural_raw["Outcome_cat"].isin(["Sobrevive", "Muerte"])].reset_index(drop=True)
|
|
in_balanced = dn_raw["en_balanceado"].astype(int).values == 1
|
|
dn = dn_raw[list(rename_map.keys())].rename(columns=rename_map).copy()
|
|
if race_column and race_column in dn_raw.columns:
|
|
dn["Race"] = dn_raw[race_column]
|
|
for c in cat_cols:
|
|
dn[c] = dn[c].fillna("Desconocido").astype(str)
|
|
y_nat = (dn["Outcome_cat"] == "Sobrevive").astype(int)
|
|
|
|
# the balanced rows of the natural file must be EXACTLY the balanced file's, in the same order
|
|
idx_b = np.where(in_balanced)[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"
|
|
position = pd.Series(idx_b, index=df.index) # row of df -> row of dn
|
|
train_balanced = set(position.loc[X_train.index]) # natural rows the balanced model trained on
|
|
|
|
# encoding (reference = the most frequent category) and the natural split
|
|
Xn_full = pd.get_dummies(dn[cat_cols], drop_first=False).astype(float)
|
|
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()
|
|
Xn = Xn_full.drop(columns=list(ref_cols.values()))
|
|
|
|
tr_n, te_n = train_test_split(np.arange(len(dn)), test_size=s.natural_test_size, random_state=s.random_state,
|
|
stratify=y_nat)
|
|
Xn_train, yn_train = Xn.iloc[tr_n], y_nat.iloc[tr_n]
|
|
common = np.array([i for i in te_n if i not in train_balanced]) # the COMMON test set
|
|
|
|
varying = [c for c in Xn_train.columns if Xn_train[c].nunique() > 1]
|
|
Xn_train = Xn_train[varying]
|
|
pre_cols = lr_selection.prefiltered_columns(Xn_train, yn_train, s.prefilter_alpha, s.max_candidates)
|
|
|
|
# stepwise and final fit on the natural population
|
|
search_idx = None
|
|
if len(Xn_train) > s.natural_search_rows:
|
|
search_idx, _ = train_test_split(Xn_train.index, train_size=s.natural_search_rows,
|
|
random_state=s.random_state, stratify=yn_train)
|
|
Xs, ys = Xn_train.loc[search_idx, pre_cols], yn_train.loc[search_idx]
|
|
else:
|
|
Xs, ys = Xn_train[pre_cols], yn_train
|
|
sel_nat = lr_selection.stepwise_selection(Xs, ys, s.alpha_in, s.alpha_out)
|
|
lr_nat = sm.Logit(yn_train, sm.add_constant(Xn_train[sel_nat])).fit(disp=0, method="bfgs", maxiter=s.natural_maxiter)
|
|
|
|
# comparison on the common natural test set, with an intercept correction of the balanced model
|
|
prev_nat, prev_bal = float(y_nat.mean()), float(y_train.mean())
|
|
shift = np.log(prev_nat / (1 - prev_nat)) - np.log(prev_bal / (1 - prev_bal))
|
|
Xc, yc, stage_c = Xn.iloc[common], y_nat.iloc[common].values, dn["Estadio"].iloc[common].values
|
|
p_nat = lr_nat.predict(sm.add_constant(Xc[sel_nat], has_constant="add")).values
|
|
Xb_c = Xn_full.iloc[common].reindex(columns=X_train.columns, fill_value=0.0)
|
|
p_bal_raw = final_lr_model.predict(sm.add_constant(Xb_c[selected], has_constant="add")).values
|
|
p_bal_cor = _sigmoid(_logit(p_bal_raw) + shift)
|
|
|
|
def row(name, 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": name, "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([row("LR balanceada (probabilidades crudas)", p_bal_raw),
|
|
row("LR balanceada + corrección de intercepto", p_bal_cor),
|
|
row("LR población natural", p_nat)]).set_index("modelo").round(3)
|
|
auc_stage = _stage_aucs(stage_c, yc, {"AUC LR balanceada": p_bal_raw, "AUC LR natural": p_nat})
|
|
|
|
# the natural LR WITHOUT treatment
|
|
cols_nt = [c for c in Xn_train.columns if not any(c.startswith(t + "_") for t in s.treatment_vars)]
|
|
pre_cols_nt = lr_selection.prefiltered_columns(Xn_train[cols_nt], yn_train, s.prefilter_alpha, s.max_candidates)
|
|
if len(Xn_train) > s.natural_search_rows:
|
|
Xs2, ys2 = Xn_train.loc[search_idx, pre_cols_nt], yn_train.loc[search_idx]
|
|
else:
|
|
Xs2, ys2 = Xn_train[pre_cols_nt], yn_train
|
|
sel_nt = lr_selection.stepwise_selection(Xs2, ys2, s.alpha_in, s.alpha_out)
|
|
lr_nt = sm.Logit(yn_train, sm.add_constant(Xn_train[sel_nt])).fit(disp=0, method="bfgs", maxiter=s.natural_maxiter)
|
|
p_nt = lr_nt.predict(sm.add_constant(Xc[sel_nt], has_constant="add")).values
|
|
comp2 = pd.concat([comp, pd.DataFrame([row("LR población natural SIN tratamiento", p_nt)]).set_index("modelo").round(3)])
|
|
auc_stage_nt = _stage_aucs(stage_c, yc, {"AUC natural": p_nat, "AUC natural SIN tratamiento": p_nt})
|
|
|
|
deciles = pd.concat([_deciles(p_nat, yc, "natural"), _deciles(p_nt, yc, "natural sin tratamiento")]).reset_index()
|
|
return NaturalResults(_odds_table(lr_nat), _odds_table(lr_nt), comp2, auc_stage, auc_stage_nt, deciles)
|