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.
96 lines
4.1 KiB
Python
96 lines
4.1 KiB
Python
"""Logistic regression with stepwise selection, apart from the modeling nodes (`modeling.py`): a univariate chi-square
|
|
pre-filter, the stepwise search on a stratified subsample and the safe fit. Plain functions with no I/O. Ported from
|
|
`04_modelado.py` (phases 3-4)."""
|
|
|
|
import numpy as np
|
|
import pandas as pd
|
|
import statsmodels.api as sm
|
|
from scipy.stats import chi2_contingency
|
|
from sklearn.model_selection import train_test_split
|
|
|
|
|
|
def univariate_prefilter(X: pd.DataFrame, y: pd.Series, alpha: float = 0.10) -> list[tuple]:
|
|
"""(column, p, chi2) of the columns whose chi-square against the outcome has p < alpha."""
|
|
kept = []
|
|
for col in X.columns:
|
|
table = pd.crosstab(X[col], y)
|
|
if table.shape[0] < 2 or table.shape[1] < 2:
|
|
continue # no variation: nothing to add
|
|
try:
|
|
chi2_stat, p, _, _ = chi2_contingency(table)
|
|
except ValueError:
|
|
continue
|
|
if p < alpha:
|
|
kept.append((col, p, chi2_stat))
|
|
return kept
|
|
|
|
|
|
def prefiltered_columns(X: pd.DataFrame, y: pd.Series, alpha: float, max_candidates: int,
|
|
always_sort: bool = True) -> list[str]:
|
|
"""The pre-filter's columns, at most `max_candidates` and strongest first (by chi-square: with big samples many
|
|
p-values are exactly 0.0 and can't order them). The main fit only sorts when it must cut; the others always do."""
|
|
kept = univariate_prefilter(X, y, alpha=alpha)
|
|
if always_sort or len(kept) > max_candidates:
|
|
kept = sorted(kept, key=lambda t: t[2], reverse=True)
|
|
return [c for c, _, _ in kept[:max_candidates]]
|
|
|
|
|
|
def safe_fit_logit(y, X_sub, maxiter: int = 200):
|
|
"""A BFGS logit; a lightly L2-regularized one if that fails; None if both do."""
|
|
try:
|
|
return sm.Logit(y, X_sub).fit(disp=0, method="bfgs", maxiter=maxiter)
|
|
except Exception:
|
|
try:
|
|
return sm.Logit(y, X_sub).fit_regularized(disp=0, alpha=0.01, maxiter=maxiter)
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
def stepwise_selection(X: pd.DataFrame, y: pd.Series, alpha_in: float = 0.10, alpha_out: float = 0.15) -> list[str]:
|
|
"""Forward step (the candidate with the lowest p below `alpha_in`), then a backward step (the worst above `alpha_out`),
|
|
until nothing changes."""
|
|
included, excluded = [], list(X.columns)
|
|
while True:
|
|
changed = False
|
|
best_pval, best_feature = np.inf, None
|
|
for col in excluded:
|
|
model = safe_fit_logit(y, sm.add_constant(X[included + [col]]))
|
|
if model is None or col not in model.pvalues:
|
|
continue
|
|
pval = model.pvalues[col]
|
|
if pval < best_pval:
|
|
best_pval, best_feature = pval, col
|
|
if best_feature is not None and best_pval < alpha_in:
|
|
included.append(best_feature)
|
|
excluded.remove(best_feature)
|
|
changed = True
|
|
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 and pvals.max() > alpha_out:
|
|
worst = pvals.idxmax()
|
|
included.remove(worst)
|
|
excluded.append(worst)
|
|
changed = True
|
|
if not changed:
|
|
break
|
|
return included
|
|
|
|
|
|
def search_sample(X_train: pd.DataFrame, y_train: pd.Series, columns: list[str], max_rows: int, random_state: int):
|
|
"""The stepwise searches on a subsample stratified by outcome (more than enough to decide which variables matter);
|
|
the final model is refitted on the whole train."""
|
|
if X_train.shape[0] > max_rows:
|
|
idx, _ = train_test_split(X_train.index, train_size=max_rows, random_state=random_state, stratify=y_train)
|
|
return X_train.loc[idx, columns], y_train.loc[idx]
|
|
return X_train[columns], y_train
|
|
|
|
|
|
def encode(df: pd.DataFrame, columns: list[str]) -> pd.DataFrame:
|
|
"""Dummies without the first category; the unknowns are one more category."""
|
|
enc = df.copy()
|
|
for c in columns:
|
|
enc[c] = enc[c].fillna("Desconocido").astype(str)
|
|
return enc
|