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.
110 lines
4.6 KiB
Python
110 lines
4.6 KiB
Python
"""The heavy routines of the balancing stage, apart from its Hamilton nodes (`balancing.py`): the outcome definition,
|
|
multiple correspondence analysis (MCA) and the informed undersampling of the majority class around the minority one.
|
|
Plain functions with no I/O. Ported from `02_balanceo_categorizacion.py`."""
|
|
|
|
import re
|
|
from dataclasses import dataclass
|
|
|
|
import numpy as np
|
|
import pandas as pd
|
|
from scipy.spatial import cKDTree
|
|
|
|
from models.cama.seer_survival.columns import find_col
|
|
from models.cama.seer_survival.settings import BalancingSettings
|
|
|
|
|
|
@dataclass(frozen=True, eq=False)
|
|
class Mca:
|
|
F: np.ndarray # row coordinates, one row per patient
|
|
G: np.ndarray # category coordinates
|
|
eigenvalues: np.ndarray
|
|
inertia_explained: np.ndarray
|
|
contributions: pd.DataFrame
|
|
|
|
|
|
def age_midpoint(v) -> float:
|
|
"""The middle of an age level: "40-44" -> 42, "85+" -> 90, "05" -> 5; NaN when it has no number."""
|
|
if not isinstance(v, str):
|
|
return np.nan
|
|
s = v.strip()
|
|
m = re.match(r"^(\d+)\s*-\s*(\d+)", s)
|
|
if m:
|
|
return (int(m.group(1)) + int(m.group(2))) / 2
|
|
m = re.match(r"^(\d+)\s*\+", s)
|
|
if m:
|
|
return int(m.group(1)) + 5
|
|
m = re.match(r"^(\d+)", s)
|
|
return float(m.group(1)) if m else np.nan
|
|
|
|
|
|
def outcome_values(df: pd.DataFrame, labels: dict, s: BalancingSettings) -> np.ndarray:
|
|
"""1.0 survives the horizon, 0.0 dies before it, NaN unknown. With `censura_excluida`, a patient alive with less
|
|
follow-up than the horizon is unknown, and so is every patient of a diagnosis year with too much censoring."""
|
|
if "outcome" in df.columns:
|
|
return df["outcome"].astype(float).values
|
|
surv_col = find_col(labels, ["survival months"], exclude=["flag"])
|
|
assert surv_col is not None, "No se encontró la columna de meses de supervivencia."
|
|
vital_col = find_col(labels, ["vital status"])
|
|
year_col = find_col(labels, ["year of diagnosis", "year of dx"])
|
|
surv = pd.to_numeric(df[surv_col], errors="coerce")
|
|
ge = surv >= s.horizon_months
|
|
dead = df[vital_col].astype(str).str.lower().str.contains("dead") if vital_col is not None and vital_col in df.columns else None
|
|
original = np.where(surv.notna(), ge.astype(float), np.nan)
|
|
if not (s.outcome_mode == "censura_excluida" and dead is not None):
|
|
return original
|
|
values = np.where(surv.isna(), np.nan, np.where(ge, 1.0, np.where(dead, 0.0, np.nan)))
|
|
if s.exclude_censored_years and year_col is not None and year_col in df.columns:
|
|
censored = surv.notna() & (~ge) & (~dead)
|
|
pct = censored.groupby(df[year_col]).mean() * 100
|
|
years = sorted(pct[pct > s.censoring_max_pct].index.tolist())
|
|
if years:
|
|
values = np.where(df[year_col].isin(years), np.nan, values)
|
|
return values
|
|
|
|
|
|
def fit_mca(df_cat: pd.DataFrame, n_components: int = 10) -> Mca:
|
|
"""MCA of a frame of categorical columns, by the SVD of the standardized residuals of its indicator matrix."""
|
|
Z = pd.get_dummies(df_cat, prefix_sep="__").astype(float)
|
|
n, J = Z.shape
|
|
Q = df_cat.shape[1]
|
|
|
|
P = Z.values / (n * Q)
|
|
r = P.sum(axis=1)
|
|
c = P.sum(axis=0)
|
|
|
|
Dr_inv_sqrt = 1.0 / np.sqrt(r)
|
|
Dc_inv_sqrt = 1.0 / np.sqrt(c)
|
|
S = Dr_inv_sqrt[:, None] * (P - np.outer(r, c)) * Dc_inv_sqrt[None, :]
|
|
|
|
U, sigma, Vt = np.linalg.svd(S, full_matrices=False)
|
|
V = Vt.T
|
|
K = min(n_components, len(sigma))
|
|
U, sigma, V = U[:, :K], sigma[:K], V[:, :K]
|
|
|
|
F = Dr_inv_sqrt[:, None] * U * sigma[None, :]
|
|
G = Dc_inv_sqrt[:, None] * V * sigma[None, :]
|
|
|
|
eigenvalues = sigma ** 2
|
|
inertia_total = ((P - np.outer(r, c)) ** 2 / np.outer(r, c)).sum()
|
|
contrib = (c[:, None] * G ** 2) / eigenvalues[None, :]
|
|
return Mca(F, G, eigenvalues, eigenvalues / inertia_total,
|
|
pd.DataFrame(contrib, index=Z.columns, columns=[f"Dim{k + 1}" for k in range(K)]))
|
|
|
|
|
|
def select_informed_undersample(F: np.ndarray, outcome: np.ndarray, minority_label: int, majority_label: int,
|
|
target_ratio: float = 1.0, dims: int | None = None) -> tuple[np.ndarray, np.ndarray]:
|
|
"""(keep mask, distance to the nearest minority patient): every minority patient and the `target_ratio` x minority
|
|
majority patients closest to the minority in MCA space."""
|
|
if dims is not None:
|
|
F = F[:, :dims]
|
|
mask_min = outcome == minority_label
|
|
dist, _ = cKDTree(F[mask_min]).query(F, k=1)
|
|
mask_maj = outcome == majority_label
|
|
n_keep_maj = int(round(mask_min.sum() * target_ratio))
|
|
|
|
maj_idx = np.where(mask_maj)[0]
|
|
order = np.argsort(dist[maj_idx])
|
|
keep_mask = mask_min.copy()
|
|
keep_mask[maj_idx[order[:n_keep_maj]]] = True
|
|
return keep_mask, dist
|