Files
models/models/cacu/development_selection.py
T
2026-12-04 09:12:15 -06:00

194 lines
7.7 KiB
Python

"""Nested, exhaustive evaluation of a bounded set of CaCu binary encoders.
Development only. Selection, coverage screening, rank checks and imputation use training
partitions only. Methods follow edgar/camodels commit 2392d54fd4a3942b56dae803906586bc65600728.
"""
import itertools
import math
import time
import numpy as np
import pandas as pd
from scipy.special import expit as expit
from scipy.special import logit
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss, log_loss, roc_auc_score
from sklearn.model_selection import LeaveOneOut, StratifiedKFold
from models.cacu.development_firth import FirthFamily
METHODS = ("firth", "flic", "flac")
def _candidates(X, coverage, limit):
eligible = []
for name in sorted(X.columns):
col = pd.to_numeric(X[name], errors="coerce")
known = col.dropna()
if len(known) / len(X) >= coverage and set(known.unique()) == {0, 1}:
eligible.append((name, col.notna().mean()))
# Perfectly identical or complementary observed columns are not distinguishable.
chosen = []
for name, _ in sorted(eligible, key=lambda item: (-item[1], item[0])):
a = X[name]
if any(
((a == X[other]) | (a.isna() & X[other].isna())).all()
or ((a == 1 - X[other]) | (a.isna() & X[other].isna())).all()
for other in chosen
):
continue
chosen.append(name)
if len(chosen) == limit:
break
return chosen
def _matrix(train, test, columns):
tr = train[list(columns)].to_numpy(dtype=float)
te = test[list(columns)].to_numpy(dtype=float)
if tr.shape[1] and np.isnan(tr).all(axis=0).any():
raise ValueError("predictor absent in training partition")
median = np.nanmedian(tr, axis=0) if tr.shape[1] else np.array([])
tr, te = np.where(np.isnan(tr), median, tr), np.where(np.isnan(te), median, te)
if np.linalg.matrix_rank(np.column_stack([np.ones(len(tr)), tr])) < len(columns) + 1:
raise ValueError("collinear predictors in training partition")
return tr, te
def _predict(train, y, test, columns, method):
tr, te = _matrix(train, test, columns)
if not columns:
return np.repeat(np.mean(y), len(test))
return FirthFamily(method).fit(tr, y).predict_proba(te)[:, 1]
def _metrics(y, probability):
y, p = np.asarray(y), np.asarray(probability)
valid = np.isfinite(p)
if valid.sum() != len(y) or len(np.unique(y)) != 2:
return {
"auc": None,
"brier": None,
"calibration_intercept": None,
"calibration_slope": None,
"log_loss": None,
}
logits = logit(np.clip(p, 1e-12, 1 - 1e-12)).reshape(-1, 1)
calibration = LogisticRegression(C=1e6).fit(logits, y)
return {
"auc": float(roc_auc_score(y, p)),
"brier": float(brier_score_loss(y, p)),
"calibration_intercept": float(calibration.intercept_[0]),
"calibration_slope": float(calibration.coef_[0, 0]),
"log_loss": float(log_loss(y, p, labels=[0, 1])),
}
def evaluate(
X: pd.DataFrame,
y,
*,
coverage=0.7,
candidate_limit=5,
subset_limit=2,
outer_folds=3,
inner_folds=2,
seed=17,
max_fits=100000,
):
"""Evaluate Firth/FLIC/FLAC with nested stratified CV and nested leave-one-out.
A fixed upper bound (default five candidates, pairs at most) permits at most 16 subsets
including the intercept. Each method selects a subset by inner out-of-fold log loss for
every outer split; all attempted subsets and failures are recorded.
"""
X = X.reset_index(drop=True).apply(pd.to_numeric, errors="coerce")
y = np.asarray(y)
if len(X) != len(y) or not np.isin(y, [0, 1]).all():
raise ValueError("one known binary outcome is required per row")
if min(np.bincount(y.astype(int), minlength=2)) < max(outer_folds, inner_folds + 1):
raise ValueError("insufficient members of each outcome for nested CV and LOOCV")
if not 1 <= candidate_limit <= 8 or not 1 <= subset_limit <= candidate_limit:
raise ValueError("candidate and subset limits exceed the supported bounds")
max_subsets = sum(
math.comb(candidate_limit, k) for k in range(min(candidate_limit, subset_limit) + 1)
)
estimated_fits = (outer_folds + len(X)) * len(METHODS) * (max_subsets * inner_folds + 1)
if estimated_fits > max_fits:
raise ValueError(f"estimated {estimated_fits} fits exceeds configured limit {max_fits}")
attempted, outputs = [], {}
started = time.monotonic()
plans = {
"cv": StratifiedKFold(outer_folds, shuffle=True, random_state=seed).split(X, y),
"loocv": LeaveOneOut().split(X, y),
}
for plan, splits in plans.items():
predictions = {m: np.full(len(X), np.nan) for m in METHODS}
selected = {m: [] for m in METHODS}
for fold, (train_idx, test_idx) in enumerate(splits):
train, test, ytrain = X.iloc[train_idx], X.iloc[test_idx], y[train_idx].astype(int)
candidates = _candidates(train, coverage, candidate_limit)
subsets = [()] + [
c
for size in range(1, min(len(candidates), subset_limit) + 1)
for c in itertools.combinations(candidates, size)
]
inner = list(
StratifiedKFold(inner_folds, shuffle=True, random_state=seed).split(train, ytrain)
)
for method in METHODS:
ranking = []
for columns in subsets:
probs = np.full(len(train), np.nan)
error = None
try:
for a, b in inner:
probs[b] = _predict(
train.iloc[a], ytrain[a], train.iloc[b], columns, method
)
loss = float(log_loss(ytrain, probs, labels=[0, 1]))
ranking.append((loss, len(columns), columns))
except (ValueError, np.linalg.LinAlgError, RuntimeError) as exc:
loss, error = None, type(exc).__name__
attempted.append(
{
"validation": plan,
"fold": fold,
"method": method,
"variables": list(columns),
"inner_log_loss": loss,
"error": error,
}
)
_, _, best = min(ranking)
selected[method].append(list(best))
try:
predictions[method][test_idx] = _predict(train, ytrain, test, best, method)
except (ValueError, np.linalg.LinAlgError, RuntimeError):
pass
outputs[plan] = {
m: {
"metrics": _metrics(y, predictions[m]),
"selected": selected[m],
"unscored": int(np.isnan(predictions[m]).sum()),
"stability": {
name: sum(name in cols for cols in selected[m]) for name in X.columns
},
}
for m in METHODS
}
return {
"development_only": True,
"candidate_limit": candidate_limit,
"subset_limit": subset_limit,
"coverage_minimum": coverage,
"max_subsets": max_subsets,
"maximum_fits": estimated_fits,
"estimated_seconds_at_50ms_per_fit": estimated_fits * 0.05,
"elapsed_seconds": time.monotonic() - started,
"source": "edgar/camodels@2392d54fd4a3942b56dae803906586bc65600728",
"attempts": attempted,
"validation": outputs,
}