Evaluar regresiones de desarrollo con selección anidada
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
"""Firth, FLIC and FLAC from edgar/camodels, commit 2392d54fd4a3942b56dae803906586bc65600728."""
|
||||
|
||||
import warnings
|
||||
|
||||
import numpy as np
|
||||
from scipy.optimize import brentq
|
||||
from scipy.special import expit
|
||||
from sklearn.base import BaseEstimator, ClassifierMixin
|
||||
from sklearn.exceptions import ConvergenceWarning
|
||||
|
||||
SOLVER = dict(max_iter=200, gtol=1e-6, xtol=1e-6)
|
||||
|
||||
|
||||
class ConvergenceError(RuntimeError):
|
||||
"""Raised when the remaining Newton step fails the convergence check."""
|
||||
|
||||
|
||||
def solve_logistic(X, y, sample_weight=None, penalty_weight=0.5):
|
||||
"""Fit logistic regression and return the fitted solver and leverages.
|
||||
|
||||
Check the remaining Newton step directly because numerical precision can
|
||||
affect the solver's convergence flag.
|
||||
"""
|
||||
y = np.asarray(y)
|
||||
if y.ndim != 1 or not (np.isin(y, [0, 1]).all() and (y == 0).any() and (y == 1).any()):
|
||||
raise ValueError("The outcome must contain only 0 and 1, with both classes present.")
|
||||
y = y.astype(int, copy=False)
|
||||
|
||||
from firthmodels import FirthLogisticRegression
|
||||
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore", ConvergenceWarning)
|
||||
model = FirthLogisticRegression(penalty_weight=penalty_weight, **SOLVER).fit(
|
||||
X, y, sample_weight=sample_weight
|
||||
)
|
||||
design = np.column_stack([np.ones(len(y)), X])
|
||||
weights = np.ones(len(y)) if sample_weight is None else sample_weight
|
||||
p = expit(model.intercept_ + X @ model.coef_)
|
||||
w = weights * p * (1 - p)
|
||||
info = design.T @ (w[:, None] * design)
|
||||
h = w * np.einsum("ij,ji->i", design, np.linalg.solve(info, design.T))
|
||||
score = design.T @ (weights * (y - p) + penalty_weight * h * (1 - 2 * p))
|
||||
step = np.abs(np.linalg.solve(info, score)).max()
|
||||
if not np.isfinite(step) or step >= 1e-4:
|
||||
raise ConvergenceError(f"The fit did not converge (remaining Newton step {step:.2g}).")
|
||||
return model, h
|
||||
|
||||
|
||||
class FirthFamily(ClassifierMixin, BaseEstimator):
|
||||
"""Estimate binary outcome probabilities using Firth, FLIC, or FLAC."""
|
||||
|
||||
def __init__(self, method="firth"):
|
||||
self.method = method
|
||||
|
||||
def fit(self, X, y):
|
||||
"""Fit the selected method to a binary outcome."""
|
||||
if self.method not in ("firth", "flic", "flac"):
|
||||
raise ValueError(f"Unknown method {self.method!r}. Expected 'firth', 'flic', or 'flac'.")
|
||||
X = np.asarray(X, float)
|
||||
firth, h = solve_logistic(X, y)
|
||||
y = np.asarray(y, int)
|
||||
self.classes_ = np.array([0, 1])
|
||||
self.coef_, self.intercept_ = firth.coef_.copy(), float(firth.intercept_)
|
||||
|
||||
if self.method == "flic":
|
||||
eta = X @ self.coef_
|
||||
self.intercept_ = brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50, xtol=1e-12)
|
||||
|
||||
elif self.method == "flac":
|
||||
# Pseudo-observations use both outcomes, each with half the leverage.
|
||||
g = np.repeat([0, 1, 1], len(y))
|
||||
self.X_aug_ = np.column_stack([np.tile(X, (3, 1)), g])
|
||||
self.y_aug_ = np.concatenate([y, y, 1 - y])
|
||||
self.w_aug_ = np.concatenate([np.ones(len(y)), h / 2, h / 2])
|
||||
ml, _ = solve_logistic(self.X_aug_, self.y_aug_, self.w_aug_, penalty_weight=0)
|
||||
# Predict on original observations, where the indicator is zero.
|
||||
self.coef_, self.intercept_ = ml.coef_[:-1].copy(), float(ml.intercept_)
|
||||
return self
|
||||
|
||||
def predict_proba(self, X):
|
||||
"""Return probabilities for classes 0 and 1 in that order."""
|
||||
p = expit(self.intercept_ + np.asarray(X, float) @ self.coef_)
|
||||
return np.column_stack([1 - p, p])
|
||||
@@ -0,0 +1,142 @@
|
||||
"""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, 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}
|
||||
+43
-1
@@ -90,6 +90,47 @@ def score():
|
||||
score_models()
|
||||
|
||||
|
||||
class CacuDevelopmentEvaluation(dg.Config):
|
||||
as_of: str
|
||||
max_fits: int = 100000
|
||||
|
||||
|
||||
@dg.op
|
||||
def evaluate_cacu_development(context: dg.OpExecutionContext, config: CacuDevelopmentEvaluation) -> str:
|
||||
"""Opt-in research evaluation only: no registered model, promotion or patient scores."""
|
||||
import mlflow
|
||||
import pandas as pd
|
||||
|
||||
from core import cacu
|
||||
from models.cacu import encoders, features
|
||||
from models.cacu.development_selection import evaluate
|
||||
from persistance import gold, registry
|
||||
|
||||
as_of = date.fromisoformat(config.as_of)
|
||||
cohort = "cacu_cohort_surveillance"
|
||||
events = gold.evidence_timelines("cacu_events", cohort, as_of)
|
||||
if events.empty:
|
||||
raise EmptyCohort(f"no eligible patients in {cohort}")
|
||||
encoded = encoders.encode(events, gold.cervical_forms(cohort))
|
||||
outcome = features.windowed_outcome(features.prepared(events), cacu.CIN2_PLUS, 1.0,
|
||||
pd.Timestamp(as_of))
|
||||
rows = encoded.merge(outcome, on="person_id", validate="one_to_one")
|
||||
rows = rows[rows["known"]].reset_index(drop=True)
|
||||
X = rows.drop(columns=["person_id", "index_date", "known", "y"])
|
||||
report = evaluate(X, rows["y"].to_numpy(), max_fits=config.max_fits)
|
||||
report.update(cohort=cohort, as_of=as_of.isoformat(), outcome="CIN2+ at one year")
|
||||
mlflow.set_experiment(registry.EXPERIMENT)
|
||||
with mlflow.start_run(run_name="cacu.cin2_firth_development") as run:
|
||||
mlflow.log_dict(report, "reports/development_evaluation.json")
|
||||
context.log.info("Development evaluation logged as %s", run.info.run_id)
|
||||
return run.info.run_id
|
||||
|
||||
|
||||
@dg.job
|
||||
def cacu_development_evaluation():
|
||||
evaluate_cacu_development()
|
||||
|
||||
|
||||
class Analysis(dg.Config):
|
||||
domain: str
|
||||
|
||||
@@ -144,4 +185,5 @@ nightly = (
|
||||
else []
|
||||
)
|
||||
|
||||
defs = dg.Definitions(jobs=[ingest, train, score, analyze, rebuild, backup], schedules=nightly)
|
||||
defs = dg.Definitions(jobs=[ingest, train, score, analyze, rebuild, backup,
|
||||
cacu_development_evaluation], schedules=nightly)
|
||||
|
||||
@@ -24,6 +24,7 @@ dependencies = [
|
||||
"edfio>=0.4.18",
|
||||
"statsmodels>=0.15.0",
|
||||
"pgmpy>=1.1.2",
|
||||
"firthmodels>=0.8.2",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from models.cacu.development_firth import FirthFamily
|
||||
from models.cacu.development_selection import METHODS, _candidates, _matrix, evaluate
|
||||
|
||||
|
||||
@pytest.mark.parametrize('method', METHODS)
|
||||
def test_methods_fit_simulated_data(method):
|
||||
X = np.array([[0], [0], [0], [1], [1], [1], [2], [2], [2], [3], [3], [3]], float)
|
||||
y = np.array([0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0])
|
||||
prediction = FirthFamily(method).fit(X, y).predict_proba(X)[:, 1]
|
||||
assert np.isfinite(prediction).all() and ((prediction > 0) & (prediction < 1)).all()
|
||||
|
||||
|
||||
def test_candidates_and_imputation_use_only_training_rows():
|
||||
train = pd.DataFrame({'a': [0., 1., np.nan, 1.], 'copy': [0., 1., np.nan, 1.],
|
||||
'absent': [np.nan] * 4})
|
||||
assert _candidates(train, 0.7, 5) == ['a']
|
||||
a, b = _matrix(train, pd.DataFrame({'a': [np.nan]}), ['a'])
|
||||
assert b[0, 0] == np.nanmedian(a[:, 0]) == 1
|
||||
|
||||
|
||||
def test_nested_cv_and_loocv_record_every_attempt():
|
||||
X = pd.DataFrame({'a': [0, 0, 1, 1, 0, 1, 0, 1],
|
||||
'b': [0, 1, 0, 1, 1, 0, 0, 1]})
|
||||
y = np.array([0, 1, 0, 1, 0, 1, 1, 0])
|
||||
report = evaluate(X, y, candidate_limit=2, subset_limit=2, outer_folds=2, inner_folds=2)
|
||||
assert report['development_only'] and report['max_subsets'] == 4
|
||||
assert set(report['validation']) == {'cv', 'loocv'}
|
||||
assert {a['method'] for a in report['attempts']} == set(METHODS)
|
||||
assert all('variables' in a and 'error' in a for a in report['attempts'])
|
||||
assert all(len(report['validation']['loocv'][m]['selected']) == len(X) for m in METHODS)
|
||||
|
||||
|
||||
def test_budget_rejects_large_loocv_before_fitting():
|
||||
X = pd.DataFrame({'a': [0, 1] * 10})
|
||||
with pytest.raises(ValueError, match='exceeds configured limit'):
|
||||
evaluate(X, [0, 1] * 10, candidate_limit=2, subset_limit=2, max_fits=1)
|
||||
|
||||
|
||||
def test_development_job_is_not_a_production_score():
|
||||
from core.models import DEVELOPMENT
|
||||
from models.definitions import defs
|
||||
|
||||
assert 'cacu.cin2_firth_development' in DEVELOPMENT
|
||||
job = defs.get_job_def('cacu_development_evaluation')
|
||||
assert job.name == 'cacu_development_evaluation'
|
||||
|
||||
|
||||
def test_development_job_writes_evaluation_to_isolated_mlflow(tmp_path, monkeypatch):
|
||||
import dagster as dg
|
||||
import mlflow
|
||||
from mlflow.tracking._tracking_service import utils as tracking_utils
|
||||
|
||||
from models.cacu import development_selection, encoders, features
|
||||
from models.definitions import CacuDevelopmentEvaluation, evaluate_cacu_development
|
||||
from persistance import gold
|
||||
|
||||
monkeypatch.setenv('MLFLOW_TRACKING_URI', (tmp_path / 'mlruns').as_uri())
|
||||
monkeypatch.setenv('MLFLOW_ALLOW_FILE_STORE', 'true')
|
||||
monkeypatch.setattr(tracking_utils, '_tracking_uri', tracking_utils._tracking_uri)
|
||||
mlflow.set_tracking_uri((tmp_path / 'mlruns').as_uri())
|
||||
patients = [str(i) for i in range(8)]
|
||||
events = pd.DataFrame({'person_id': patients, 'date': ['2025-01-01'] * 8,
|
||||
'index_date': ['2025-01-01'] * 8})
|
||||
encoded = pd.DataFrame({'person_id': patients, 'index_date': ['2025-01-01'] * 8,
|
||||
'factor': [0, 0, 1, 1, 0, 1, 0, 1]})
|
||||
outcomes = pd.DataFrame({'person_id': patients, 'known': [True] * 8,
|
||||
'y': [0, 1, 0, 1, 0, 1, 1, 0]})
|
||||
monkeypatch.setattr(gold, 'evidence_timelines', lambda *a: events)
|
||||
monkeypatch.setattr(gold, 'cervical_forms', lambda *a: pd.DataFrame())
|
||||
monkeypatch.setattr(encoders, 'encode', lambda *a: encoded)
|
||||
monkeypatch.setattr(features, 'windowed_outcome', lambda *a: outcomes)
|
||||
real = development_selection.evaluate
|
||||
monkeypatch.setattr(development_selection, 'evaluate',
|
||||
lambda X, y, **kw: real(X, y, candidate_limit=1, subset_limit=1,
|
||||
outer_folds=2, inner_folds=2, **kw))
|
||||
with dg.build_op_context() as context:
|
||||
run_id = evaluate_cacu_development(context, CacuDevelopmentEvaluation(as_of='2026-01-01'))
|
||||
artifacts = mlflow.MlflowClient().list_artifacts(run_id, 'reports')
|
||||
assert [a.path for a in artifacts] == ['reports/development_evaluation.json']
|
||||
Reference in New Issue
Block a user