47 lines
1.9 KiB
Python
47 lines
1.9 KiB
Python
"""The opt-in development evaluation (models.cacu.development): Firth and its FLIC and FLAC
|
|
corrections, and the nested selection that never looks outside its training partition."""
|
|
|
|
import numpy as np
|
|
import pandas as pd
|
|
import pytest
|
|
|
|
from models.cacu.development import METHODS, Firth, candidates, evaluate
|
|
|
|
|
|
def data(n=60, seed=0):
|
|
rng = np.random.default_rng(seed)
|
|
X = pd.DataFrame({"a": rng.integers(0, 2, n), "b": rng.integers(0, 2, n)}, dtype=float)
|
|
X.loc[:5, "a"] = np.nan
|
|
X["not_a"], X["sparse"], X["counts"] = 1 - X["a"], np.nan, rng.integers(0, 5, n)
|
|
y = (rng.random(n) < 0.15 + 0.5 * X["b"]).astype(int).to_numpy()
|
|
return X, y
|
|
|
|
|
|
def test_flic_matches_the_outcome_rate_and_flac_stays_near_firth():
|
|
X, y = data()
|
|
fitted = {m: Firth(m).fit(X[["b"]], y).predict_proba(X[["b"]])[:, 1] for m in METHODS}
|
|
assert fitted["flic"].sum() == pytest.approx(y.sum())
|
|
assert np.abs(fitted["flac"] - fitted["firth"]).max() < 0.05
|
|
with pytest.raises(ValueError, match="collinear"):
|
|
Firth().fit(np.column_stack([X["b"], X["b"]]), y)
|
|
|
|
|
|
def test_candidates_are_known_binary_and_distinguishable():
|
|
X, _ = data()
|
|
assert candidates(X, 0.7, 5) == ["b", "a"] # not_a is a's complement; the rest aren't 0/1
|
|
assert candidates(X, 0.95, 5) == ["b"]
|
|
|
|
|
|
def test_nested_selection_reports_every_method_validation_and_attempt():
|
|
X, y = data()
|
|
found = evaluate(X, y)
|
|
assert found["development_only"] and found["max_subsets"] == 16
|
|
for plan in ("cv", "loocv"):
|
|
for method in METHODS:
|
|
result = found["validation"][plan][method]
|
|
assert result["unscored"] == 0 and set(result["metrics"]) >= {"auc", "brier"}
|
|
assert all(set(chosen) <= {"a", "b"} for chosen in result["selected"])
|
|
assert {a["method"] for a in found["attempts"]} == set(METHODS)
|
|
with pytest.raises(ValueError, match="exceeds"):
|
|
evaluate(X, y, max_fits=10)
|