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.
470 lines
23 KiB
Python
470 lines
23 KiB
Python
"""The heavy routines of the depuration stage, apart from its Hamilton nodes (`depuration.py`): Theil's U, GVIF, the
|
|
calibration of the thresholds (chance floor, natural gap, sensitivity sweeps, clustering) and the A/B/C elimination.
|
|
|
|
Plain functions with no I/O and no module state, so they run alone and on a Dask worker. Ported from
|
|
`01_depuracion.py`; the report keys keep the script's Spanish names because downstream files read them.
|
|
"""
|
|
|
|
import itertools
|
|
from dataclasses import dataclass, field
|
|
|
|
import numpy as np
|
|
import pandas as pd
|
|
from scipy.cluster.hierarchy import cophenet, fcluster, linkage
|
|
from scipy.spatial.distance import squareform
|
|
from sklearn.metrics import silhouette_score
|
|
|
|
from models.cama.seer_survival.settings import DepurationSettings
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Thresholds:
|
|
"""The thresholds in use by the elimination (the configured ones, or the calibration's when `thresholds_auto`)."""
|
|
|
|
dup_u: float
|
|
u_redund: float
|
|
gvif_drop: float
|
|
cluster_method: str
|
|
cluster_cut: float
|
|
pair_r_min: float
|
|
auto: bool
|
|
|
|
|
|
@dataclass
|
|
class Calibration:
|
|
"""What the calibration found: its tables and report, and the suggestions the thresholds may adopt."""
|
|
|
|
pairs_u: pd.DataFrame
|
|
cluster_cut_table: pd.DataFrame # empty when the clustering could not be calibrated
|
|
report: dict
|
|
summary: list[dict]
|
|
u_suggestion: dict
|
|
dup_u_suggested: float
|
|
gvif_drop_suggested: float
|
|
cluster_method_suggested: str
|
|
config_eliminations: dict
|
|
warnings: list[str] = field(default_factory=list)
|
|
|
|
|
|
# ---------------------------------------------------------------- Theil's U and GVIF
|
|
|
|
def theil_u_matrix(d: pd.DataFrame, columns: list[str]) -> pd.DataFrame:
|
|
"""U(row | column): the share of the row variable's entropy that the column variable explains."""
|
|
U = pd.DataFrame(np.nan, index=columns, columns=columns)
|
|
H = {}
|
|
for c in columns:
|
|
p = d[c].value_counts(normalize=True).values
|
|
H[c] = float(-(p * np.log(p)).sum())
|
|
for a, b in itertools.combinations(columns, 2):
|
|
pxy = pd.crosstab(d[a], d[b]).values.astype(float)
|
|
pxy /= pxy.sum()
|
|
nz = pxy[pxy > 0]
|
|
hxy = float(-(nz * np.log(nz)).sum())
|
|
mi = H[a] + H[b] - hxy
|
|
U.loc[a, b] = mi / H[a] if H[a] > 0 else np.nan
|
|
U.loc[b, a] = mi / H[b] if H[b] > 0 else np.nan
|
|
return U
|
|
|
|
|
|
def design(d: pd.DataFrame, columns: list[str]):
|
|
"""Indicator blocks, one per variable, dropping each one's most frequent category and constant columns."""
|
|
blocks = {}
|
|
for c in columns:
|
|
ind = pd.get_dummies(d[c], prefix=c, prefix_sep="=").astype(float)
|
|
ind = ind.drop(columns=ind.sum().idxmax())
|
|
ind = ind.loc[:, ind.std() > 0]
|
|
if ind.shape[1] > 0:
|
|
blocks[c] = ind
|
|
X = pd.concat(blocks.values(), axis=1)
|
|
return X, blocks
|
|
|
|
|
|
def gvif_table(d: pd.DataFrame, columns: list[str]):
|
|
"""(table, []) with each variable's GVIF and `GVIF^(1/2df)`; or (None, candidates) when the design is singular,
|
|
the candidates being the variables that are an exact combination of the others, fewest categories first."""
|
|
X, blocks = design(d, columns)
|
|
R = np.corrcoef(X.values, rowvar=False)
|
|
pos = {n: i for i, n in enumerate(X.columns)}
|
|
s, ld = np.linalg.slogdet(R)
|
|
if not (s > 0 and np.isfinite(ld) and ld > -30):
|
|
cand = []
|
|
for c, b in blocks.items():
|
|
others = [x for x in X.columns if x not in b.columns]
|
|
A = np.column_stack([X[others].values, np.ones(len(X))])
|
|
for x in b.columns:
|
|
y = X[x].values
|
|
coef, *_ = np.linalg.lstsq(A, y, rcond=None)
|
|
r2 = 1 - ((y - A @ coef) ** 2).sum() / ((y - y.mean()) ** 2).sum()
|
|
if r2 >= 0.9999:
|
|
cand.append((b.shape[1], c))
|
|
break
|
|
return None, sorted(cand)
|
|
rows = []
|
|
for c, b in blocks.items():
|
|
idx = [pos[n] for n in b.columns]
|
|
rest = [i for i in range(len(pos)) if i not in set(idx)]
|
|
s1, l1 = np.linalg.slogdet(R[np.ix_(idx, idx)])
|
|
s2, l2 = np.linalg.slogdet(R[np.ix_(rest, rest)]) if rest else (1, 0.0)
|
|
gv = float(np.exp(l1 + l2 - ld))
|
|
rows.append({"variable": c, "gl": len(idx), "GVIF": gv, "GVIF_ajustado": gv ** (1 / (2 * len(idx)))})
|
|
return pd.DataFrame(rows).sort_values("GVIF_ajustado", ascending=False).reset_index(drop=True), []
|
|
|
|
|
|
def _entropy(p: np.ndarray) -> float:
|
|
p = p[p > 0]
|
|
return float(-(p * np.log(p)).sum())
|
|
|
|
|
|
def info_pair(cx: np.ndarray, cy: np.ndarray, kx: int, ky: int) -> dict:
|
|
"""Entropies, mutual information and the accuracy of predicting each variable from the other, from factor codes."""
|
|
j = np.bincount(cx * ky + cy, minlength=kx * ky).reshape(kx, ky).astype(float)
|
|
n = j.sum()
|
|
px = j.sum(1) / n
|
|
py = j.sum(0) / n
|
|
hxy = _entropy((j / n).ravel())
|
|
hx, hy = _entropy(px), _entropy(py)
|
|
return dict(hx=hx, hy=hy, mi=hx + hy - hxy, acc_x_dado_y=j.max(0).sum() / n, acc_y_dado_x=j.max(1).sum() / n,
|
|
base_x=px.max(), base_y=py.max())
|
|
|
|
|
|
def loser(a: str, b: str, protected, prefer, key) -> tuple[str, str] | None:
|
|
"""(dropped, kept) of two redundant variables: a protected one is kept, then a preferred one, then the one with
|
|
more unknowns, more categories, later position (`key`). None when both are protected."""
|
|
if a in protected and b in protected:
|
|
return None
|
|
if a in protected:
|
|
return b, a
|
|
if b in protected:
|
|
return a, b
|
|
if a in prefer and b not in prefer:
|
|
return b, a
|
|
if b in prefer and a not in prefer:
|
|
return a, b
|
|
return (a, b) if key(a) > key(b) else (b, a)
|
|
|
|
|
|
# ---------------------------------------------------------------- calibration
|
|
|
|
def suggest_u(pairs_u: pd.DataFrame, chance_ceiling: float, s: DepurationSettings,
|
|
gap_from: float | None = None, gap_min: float | None = None) -> dict:
|
|
"""The U_REDUND suggestion: the natural gap among the pairs' U, floored by chance, else the conventional value."""
|
|
gap_from = s.u_gap_from if gap_from is None else gap_from
|
|
gap_min = s.u_gap_min if gap_min is None else gap_min
|
|
v = np.sort(pairs_u["U(X|Y)"].dropna().round(4).unique())[::-1]
|
|
out = {"metodo": "convencional", "brecha": None, "borde_sup": None, "borde_inf": None, "confianza": "revisar"}
|
|
best = None
|
|
for i in range(len(v) - 1):
|
|
if v[i] >= gap_from and (best is None or v[i] - v[i + 1] > best[0]):
|
|
best = (v[i] - v[i + 1], v[i], v[i + 1])
|
|
if best is not None and best[0] >= gap_min:
|
|
mid = float(np.clip((best[1] + best[2]) / 2, *s.u_plausible))
|
|
out.update(metodo="brecha natural", U=mid, brecha=round(float(best[0]), 3), borde_sup=round(float(best[1]), 3),
|
|
borde_inf=round(float(best[2]), 3), confianza="alta")
|
|
else:
|
|
out["U"] = s.u_conventional
|
|
out["motivo"] = (("no hay pares con U >= %.2f" % gap_from) if best is None
|
|
else ("la mayor brecha (%.3f) < %.2f" % (best[0], gap_min)))
|
|
floor = s.k_azar * chance_ceiling
|
|
if out["U"] < floor:
|
|
out["U"] = float(min(floor, 0.99))
|
|
out["metodo"] += " + piso por azar"
|
|
out["confianza"] = "revisar"
|
|
out["U"] = round(float(out["U"]), 2)
|
|
return out
|
|
|
|
|
|
class RedundancyScreen:
|
|
"""Steps A, B and C on one frame at any thresholds, caching U matrices and GVIF tables by the active columns.
|
|
The calibration replays the elimination many times, so it uses the fast factor-code U."""
|
|
|
|
def __init__(self, frame: pd.DataFrame, columns: list[str], codes: dict, kcat: dict, s: DepurationSettings):
|
|
self.frame, self.columns, self.codes, self.kcat, self.s = frame, columns, codes, kcat, s
|
|
pct_unknown = {c: float((frame[c] == s.unknown_label).mean()) for c in columns}
|
|
ncat = {c: int(frame[c].nunique()) for c in columns}
|
|
order = {c: i for i, c in enumerate(columns)}
|
|
self._key = lambda c: (pct_unknown[c], ncat[c], order[c])
|
|
self._u, self._g = {}, {}
|
|
|
|
def u_matrix(self, cols_t: tuple) -> pd.DataFrame:
|
|
if cols_t not in self._u:
|
|
M = pd.DataFrame(np.nan, index=list(cols_t), columns=list(cols_t))
|
|
for a, b in itertools.combinations(cols_t, 2):
|
|
ip = info_pair(self.codes[a], self.codes[b], self.kcat[a], self.kcat[b])
|
|
M.loc[a, b] = ip["mi"] / ip["hx"] if ip["hx"] > 0 else np.nan
|
|
M.loc[b, a] = ip["mi"] / ip["hy"] if ip["hy"] > 0 else np.nan
|
|
self._u[cols_t] = M
|
|
return self._u[cols_t]
|
|
|
|
def gvif(self, cols_t: tuple):
|
|
if cols_t not in self._g:
|
|
self._g[cols_t] = gvif_table(self.frame, list(cols_t))
|
|
return self._g[cols_t]
|
|
|
|
def run(self, dup_u: float, u_redund: float, gvif_drop: float) -> tuple[dict, list[str]]:
|
|
"""({dropped variable: step}, active variables)."""
|
|
s = self.s
|
|
active, out = list(self.columns), {}
|
|
U = self.u_matrix(tuple(active)) # A
|
|
for a, b in itertools.combinations(list(active), 2):
|
|
if a not in active or b not in active:
|
|
continue
|
|
if U.loc[a, b] >= dup_u and U.loc[b, a] >= dup_u:
|
|
r = loser(a, b, s.protected, s.prefer, self._key)
|
|
if r:
|
|
active.remove(r[0])
|
|
out[r[0]] = "A"
|
|
U = self.u_matrix(tuple(active)) # B
|
|
cand = []
|
|
for x in active:
|
|
for y in active:
|
|
if x != y and U.loc[x, y] >= u_redund and U.loc[y, x] < u_redund:
|
|
cand.append((U.loc[x, y], x, y))
|
|
for u, x, y in sorted(cand, reverse=True):
|
|
if x in active and y in active and x not in s.protected and x not in s.prefer:
|
|
active.remove(x)
|
|
out[x] = "B"
|
|
for _ in range(s.max_iter_gvif): # C
|
|
if len(active) < 3:
|
|
break
|
|
table, exact = self.gvif(tuple(active))
|
|
if table is None:
|
|
ex = [c for _, c in exact if c not in s.protected]
|
|
if not ex:
|
|
break
|
|
active.remove(ex[0])
|
|
out[ex[0]] = "C"
|
|
continue
|
|
cd = table[(table["GVIF_ajustado"] >= gvif_drop) & (~table["variable"].isin(s.protected))]
|
|
if cd.empty:
|
|
break
|
|
v = cd.iloc[0]["variable"]
|
|
active.remove(v)
|
|
out[v] = "C"
|
|
return out, active
|
|
|
|
|
|
def _labels(d: dict) -> str:
|
|
return ", ".join(f"{k} [{p}]" for k, p in sorted(d.items())) or "(nada)"
|
|
|
|
|
|
def _category_matrix(d, columns, min_n, max_cat, warnings):
|
|
X = pd.get_dummies(d[columns], prefix_sep="=", dtype=np.float32)
|
|
total = X.sum()
|
|
X = X.loc[:, (total >= min_n) & (total <= len(X) - min_n)]
|
|
if X.shape[1] > max_cat:
|
|
X = X[X.sum().sort_values(ascending=False).index[:max_cat]]
|
|
warnings.append(f"demasiadas categorías para el clustering: se usan las {max_cat} más frecuentes.")
|
|
return X
|
|
|
|
|
|
def calibrate(frame: pd.DataFrame, columns: list[str], s: DepurationSettings, generated_at: str) -> Calibration:
|
|
"""Suggests the thresholds from the data (chance floor and natural gap of U, GVIF margin, clustering linkage and
|
|
cut) and reports how stable the elimination is to them. It never changes the frame."""
|
|
rng = np.random.default_rng(s.seed)
|
|
warnings: list[str] = []
|
|
report = {"fecha": generated_at, "advertencias": warnings, "parametros": {
|
|
"NULL_PERM": s.null_perm, "K_AZAR": s.k_azar, "U_CONVENCIONAL": s.u_conventional, "U_GAP_DESDE": s.u_gap_from,
|
|
"U_GAP_MIN_BRECHA": s.u_gap_min, "U_RANGO_PLAUSIBLE": list(s.u_plausible), "VIF_CORTE": s.vif_cut,
|
|
"R_GRANDE": s.r_large, "MIN_N_CAT": s.min_n_cat, "SEMILLA": s.seed}}
|
|
if len(columns) < 2:
|
|
raise ValueError("La calibración necesita al menos 2 variables categóricas.")
|
|
df_cal = frame if len(frame) <= s.n_max_cal else frame.sample(s.n_max_cal, random_state=s.seed)
|
|
codes = {c: pd.factorize(df_cal[c])[0] for c in columns}
|
|
kcat = {c: int(df_cal[c].nunique()) for c in columns}
|
|
n_cal = len(df_cal)
|
|
median_cells = float(np.median([n_cal / (kcat[a] * kcat[b]) for a, b in itertools.combinations(columns, 2)]))
|
|
if n_cal < 1000:
|
|
warnings.append(f"n pequeño ({n_cal}): U está sesgado hacia arriba; el piso por azar lo compensa, pero interpreta con cautela.")
|
|
if median_cells < 5:
|
|
warnings.append(f"tablas de contingencia dispersas (mediana {median_cells:.1f} pacientes/celda < 5): U se infla; confía más en el piso por azar que en el valor absoluto.")
|
|
if len(columns) < 4:
|
|
warnings.append("pocas variables (< 4): el GVIF y la brecha natural son poco informativos.")
|
|
if max(kcat.values()) > 30:
|
|
warnings.append(f"variable con {max(kcat.values())} categorías: considera agruparlas antes de depurar.")
|
|
report["datos"] = {"n": int(len(frame)), "n_calibracion": int(n_cal), "n_variables": len(columns),
|
|
"categorias_por_variable": kcat, "pacientes_por_celda_mediana": median_cells}
|
|
|
|
# 1. U of Theil: pairs, accuracy and chance floor
|
|
rows, ceiling = [], []
|
|
for a, b in itertools.combinations(columns, 2):
|
|
ip = info_pair(codes[a], codes[b], kcat[a], kcat[b])
|
|
mi_null = np.array([info_pair(codes[a], rng.permutation(codes[b]), kcat[a], kcat[b])["mi"]
|
|
for _ in range(s.null_perm)])
|
|
for x, y, hx, acc, base in [(a, b, ip["hx"], ip["acc_x_dado_y"], ip["base_x"]),
|
|
(b, a, ip["hy"], ip["acc_y_dado_x"], ip["base_y"])]:
|
|
u = ip["mi"] / hx if hx > 0 else np.nan
|
|
u_null = mi_null.max() / hx if hx > 0 else np.nan
|
|
rows.append({"X": x, "dado_Y": y, "U(X|Y)": u, "U_azar_max": u_null,
|
|
"exactitud_X_desde_Y": acc, "exactitud_base_X": base})
|
|
ceiling.append(u_null)
|
|
pairs_u = pd.DataFrame(rows).sort_values("U(X|Y)", ascending=False).reset_index(drop=True)
|
|
pairs_u["brecha_al_siguiente"] = pairs_u["U(X|Y)"] - pairs_u["U(X|Y)"].shift(-1)
|
|
chance_ceiling = float(np.nanmax(ceiling))
|
|
u_sug = suggest_u(pairs_u, chance_ceiling, s)
|
|
|
|
# 2. Sensitivity: which variables go when each threshold moves
|
|
screen = RedundancyScreen(df_cal, columns, codes, kcat, s)
|
|
check = theil_u_matrix(df_cal, columns)
|
|
fast = screen.u_matrix(tuple(columns))
|
|
assert np.allclose(check.values.astype(float), fast.loc[columns, columns].values.astype(float),
|
|
equal_nan=True, atol=1e-9), "U rápida != theil_u_matrix"
|
|
base_out, base_act = screen.run(s.dup_u, s.u_redund, s.gvif_drop)
|
|
|
|
dup_sug = round(min(max(0.90, u_sug["U"] + 0.05), 0.99), 2)
|
|
out_sug, _ = screen.run(dup_sug, u_sug["U"], s.gvif_drop)
|
|
same = set(out_sug) == set(base_out)
|
|
u_sug["misma_decision_que_config"] = bool(same)
|
|
if not same and u_sug["confianza"] == "alta":
|
|
u_sug["confianza"] = "revisar"
|
|
if not same:
|
|
warnings.append("los umbrales sugeridos producen un conjunto distinto de variables eliminadas: revisa los barridos A-C antes de aplicarlos.")
|
|
|
|
# D) the gap rule's parameters are conventions: does changing them change the suggestion or what is dropped?
|
|
gap_rows = []
|
|
for gd in s.gap_from_grid:
|
|
for gm in s.gap_min_grid:
|
|
sg = suggest_u(pairs_u, chance_ceiling, s, gd, gm)
|
|
dup_s = round(min(max(0.90, sg["U"] + 0.05), 0.99), 2)
|
|
o, _ = screen.run(dup_s, sg["U"], s.gvif_drop)
|
|
gap_rows.append({"U_GAP_DESDE": gd, "U_GAP_MIN_BRECHA": gm, "U_REDUND sugerido": sg["U"],
|
|
"método": sg["metodo"], "misma decisión": set(o) == set(base_out),
|
|
"elimina [regla]": _labels(o)})
|
|
sens_gap = pd.DataFrame(gap_rows)
|
|
different = sens_gap[~sens_gap["misma decisión"]]
|
|
if len(different):
|
|
warnings.append(f"la decisión depende de U_GAP_DESDE / U_GAP_MIN_BRECHA en {len(different)} de {len(sens_gap)} combinaciones: son convenciones; revisa el barrido D antes de fijar el umbral.")
|
|
report["sensibilidad_regla_brecha"] = {
|
|
"grilla_U_GAP_DESDE": list(s.gap_from_grid), "grilla_U_GAP_MIN_BRECHA": list(s.gap_min_grid),
|
|
"proporcion_misma_decision": float(sens_gap["misma decisión"].mean()),
|
|
"U_sugerido_min": float(sens_gap["U_REDUND sugerido"].min()),
|
|
"U_sugerido_max": float(sens_gap["U_REDUND sugerido"].max())}
|
|
|
|
# 3. GVIF: margin to the threshold
|
|
gvif_drop_sug = round(float(np.sqrt(s.vif_cut)), 2)
|
|
tab_k, _ = screen.gvif(tuple(base_act))
|
|
margin = None
|
|
if tab_k is not None and len(tab_k):
|
|
tab_k = tab_k.copy()
|
|
tab_k["margen_al_umbral"] = s.gvif_drop - tab_k["GVIF_ajustado"]
|
|
margin = float(tab_k["margen_al_umbral"].min())
|
|
if margin < 0.15:
|
|
warnings.append("alguna variable conservada está muy cerca del umbral de GVIF: la decisión es sensible al corte.")
|
|
|
|
# 4. Clustering: linkage (cophenetic) and cut (Cohen)
|
|
min_n_eff = s.min_n_cat
|
|
X = _category_matrix(df_cal, columns, min_n_eff, s.max_cat_cluster, warnings)
|
|
if X.shape[1] < 6:
|
|
min_n_eff = max(5, int(0.005 * n_cal))
|
|
X = _category_matrix(df_cal, columns, min_n_eff, s.max_cat_cluster, warnings)
|
|
warnings.append(f"muy pocas categorías con >= {s.min_n_cat} pacientes: se baja el mínimo a {min_n_eff} para el clustering.")
|
|
cluster_ok = X.shape[1] >= 4
|
|
method_sug, coph, cut_table = s.cluster_method, {}, pd.DataFrame()
|
|
if not cluster_ok:
|
|
warnings.append("no hay suficientes categorías para calibrar el clustering; se mantienen los valores por convención.")
|
|
else:
|
|
names = list(X.columns)
|
|
var = np.array([c.split("=", 1)[0] for c in names])
|
|
V = X.values.astype(np.float32)
|
|
V -= V.mean(0)
|
|
cov = V.T @ V
|
|
sd = np.sqrt(np.diag(cov))
|
|
R = (cov / np.outer(sd, sd)).astype(float)
|
|
D = 1 - R if s.cluster_dist == "signed" else 1 - np.abs(R)
|
|
D = np.clip((D + D.T) / 2, 0, None)
|
|
np.fill_diagonal(D, 0)
|
|
cond = squareform(D, checks=False)
|
|
for m in ["single", "complete", "average", "weighted"]:
|
|
coph[m] = float(cophenet(linkage(cond, method=m), cond)[0])
|
|
method_sug = max(coph, key=coph.get)
|
|
Zc = linkage(cond, method=method_sug)
|
|
rows = []
|
|
for t in np.round(np.arange(0.30, 1.01, 0.05), 2):
|
|
lab = fcluster(Zc, t=float(t), criterion="distance")
|
|
ng = len(set(lab))
|
|
multi = sum(1 for g in set(lab) if len(set(var[lab == g])) >= 2)
|
|
sil = float(silhouette_score(D, lab, metric="precomputed")) if 2 <= ng <= len(lab) - 1 else np.nan
|
|
rows.append({"corte (dist.)": t, "r medio exigido": round(1 - t, 2), "n_grupos": ng,
|
|
"grupos_multivariable": multi, "silueta": round(sil, 3) if sil == sil else np.nan})
|
|
cut_table = pd.DataFrame(rows)
|
|
|
|
summary = [
|
|
{"parámetro": "U_REDUND", "configurado": s.u_redund, "sugerido": u_sug["U"], "criterio": u_sug["metodo"],
|
|
"confianza": u_sug["confianza"]},
|
|
{"parámetro": "DUP_U", "configurado": s.dup_u, "sugerido": dup_sug, "criterio": "max(0.90, U_REDUND+0.05)",
|
|
"confianza": u_sug["confianza"]},
|
|
{"parámetro": "GVIF_DROP", "configurado": s.gvif_drop, "sugerido": gvif_drop_sug,
|
|
"criterio": f"sqrt(VIF {s.vif_cut}) (R2={1 - 1 / s.vif_cut:.2f})",
|
|
"confianza": "alta" if (margin is None or margin >= 0.15) else "revisar"},
|
|
{"parámetro": "CLUSTER_METODO", "configurado": s.cluster_method, "sugerido": method_sug,
|
|
"criterio": "máx. correlación cofenética", "confianza": "alta" if cluster_ok else "revisar"},
|
|
{"parámetro": "CLUSTER_CORTE", "configurado": round(1 - s.r_large, 2), "sugerido": round(1 - s.r_large, 2),
|
|
"criterio": f"Cohen: r medio >= {s.r_large}", "confianza": "alta"},
|
|
{"parámetro": "PAR_R_MIN", "configurado": s.r_large, "sugerido": s.r_large, "criterio": "Cohen: efecto grande",
|
|
"confianza": "alta"}]
|
|
report.update({"piso_azar_U": chance_ceiling, "sugerencia_U": u_sug, "resumen": summary,
|
|
"eliminadas_con_config": base_out, "correlacion_cofenetica": coph})
|
|
return Calibration(pairs_u, cut_table, report, summary, u_sug, dup_sug, gvif_drop_sug, method_sug, base_out,
|
|
warnings)
|
|
|
|
|
|
def thresholds_in_use(c: Calibration, s: DepurationSettings) -> Thresholds:
|
|
"""The configured thresholds, or the calibration's suggestions when `thresholds_auto`."""
|
|
cut, r_min = round(1 - s.r_large, 2), s.r_large
|
|
if s.thresholds_auto:
|
|
return Thresholds(c.dup_u_suggested, c.u_suggestion["U"], c.gvif_drop_suggested, c.cluster_method_suggested,
|
|
cut, r_min, True)
|
|
return Thresholds(s.dup_u, s.u_redund, s.gvif_drop, s.cluster_method, cut, r_min, False)
|
|
|
|
|
|
# ---------------------------------------------------------------- elimination (steps A, B, C on the full frame)
|
|
|
|
def eliminate(frame: pd.DataFrame, columns: list[str], t: Thresholds, s: DepurationSettings) -> pd.DataFrame:
|
|
"""The dropped variables, one row each: `variable`, `paso`, `motivo`, `a_favor_de`. A removes duplicates (U both
|
|
ways >= dup_u), B derived variables (U one way only >= u_redund), C the nested ones by GVIF."""
|
|
active = list(columns)
|
|
dropped: list[dict] = []
|
|
pct_unknown = {c: float((frame[c] == s.unknown_label).mean()) for c in columns}
|
|
ncat = {c: int(frame[c].nunique()) for c in columns}
|
|
order = {c: i for i, c in enumerate(columns)}
|
|
key = lambda c: (pct_unknown[c], ncat[c], order[c]) # noqa: E731
|
|
|
|
def drop(var, step, reason, favor):
|
|
active.remove(var)
|
|
dropped.append({"variable": var, "paso": step, "motivo": reason, "a_favor_de": favor})
|
|
|
|
U = theil_u_matrix(frame, active) # A
|
|
for a, b in itertools.combinations(list(active), 2):
|
|
if a not in active or b not in active:
|
|
continue
|
|
if U.loc[a, b] >= t.dup_u and U.loc[b, a] >= t.dup_u:
|
|
r = loser(a, b, s.protected, s.prefer, key)
|
|
if r:
|
|
drop(r[0], "A duplicada", f"U({a}|{b})={U.loc[a, b]:.2f}, U({b}|{a})={U.loc[b, a]:.2f}", r[1])
|
|
|
|
U = theil_u_matrix(frame, active) # B
|
|
cand = []
|
|
for x in active:
|
|
for y in active:
|
|
if x != y and U.loc[x, y] >= t.u_redund and U.loc[y, x] < t.u_redund:
|
|
cand.append((U.loc[x, y], x, y))
|
|
for u, x, y in sorted(cand, reverse=True):
|
|
if x in active and y in active and x not in s.protected and x not in s.prefer:
|
|
drop(x, "B derivada", f"U({x}|{y})={u:.2f} vs U({y}|{x})={U.loc[y, x]:.2f}", y)
|
|
|
|
for _ in range(s.max_iter_gvif): # C
|
|
if len(active) < 3:
|
|
break
|
|
table, exact = gvif_table(frame, active)
|
|
if table is None:
|
|
exact = [c for _, c in exact if c not in s.protected]
|
|
if not exact:
|
|
break
|
|
drop(exact[0], "C anidada exacta", "combinación exacta de otras variables", "(el resto)")
|
|
continue
|
|
cd = table[(table["GVIF_ajustado"] >= t.gvif_drop) & (~table["variable"].isin(s.protected))]
|
|
if cd.empty:
|
|
break
|
|
v = cd.iloc[0]
|
|
drop(v["variable"], "C GVIF", f"GVIF ajustado={v['GVIF_ajustado']:.2f} >= {t.gvif_drop}", "(el resto)")
|
|
return pd.DataFrame(dropped, columns=["variable", "paso", "motivo", "a_favor_de"])
|