Limpiar los avisos de estilo
This commit is contained in:
@@ -1,32 +1,43 @@
|
|||||||
"""The prevalence part of Klausch's BayesPIM as a conjugate Gibbs sampler, for cross-sectional screening data.
|
"""The prevalence part of Klausch's BayesPIM as a conjugate Gibbs sampler, for cross-sectional\
|
||||||
|
screening data.
|
||||||
|
|
||||||
Klausch, Lissenberg-Witte and Coupé (2026), Stat Med 45(8-9):e70433, doi:10.1002/sim.70433. Their R package needs
|
Klausch, Lissenberg-Witte and Coupé (2026), Stat Med 45(8-9):e70433, doi:10.1002/sim.70433.\
|
||||||
follow-up times to initialise the incidence part, so it cannot fit a sample with one test per woman (2026 sample of
|
Their R package needs
|
||||||
|
follow-up times to initialise the incidence part, so it cannot fit a sample with one test per\
|
||||||
|
woman (2026 sample of
|
||||||
Modelo-cacu, issue 0120). With no follow-up only the prevalence part is informed, and it is this:
|
Modelo-cacu, issue 0120). With no follow-up only the prevalence part is informed, and it is this:
|
||||||
|
|
||||||
z_i ~ N(x_i beta, 1), g_i = 1[z_i > 0] true state at the test (probit, Albert and Chib 1993)
|
z_i ~ N(x_i beta, 1), g_i = 1[z_i > 0] true state at the test (probit, Albert\
|
||||||
|
and Chib 1993)
|
||||||
y_i | g_i, r_i = 1 ~ Bernoulli(kappa g_i) the test: specificity 1, sensitivity kappa
|
y_i | g_i, r_i = 1 ~ Bernoulli(kappa g_i) the test: specificity 1, sensitivity kappa
|
||||||
r_i = 0 no test (or no result): g_i is only augmented
|
r_i = 0 no test (or no result): g_i is only augmented
|
||||||
|
|
||||||
Every full conditional is a standard distribution, so each step is an exact draw:
|
Every full conditional is a standard distribution, so each step is an exact draw:
|
||||||
g (Bernoulli, z integrated out), z (truncated normal), beta (normal), kappa (beta).
|
g (Bernoulli, z integrated out), z (truncated normal), beta (normal), kappa (beta).
|
||||||
|
|
||||||
The extension proposed in chapter 19 (selection of who gets the test, the arc g -> r) adds a second probit,
|
The extension proposed in chapter 19 (selection of who gets the test, the arc g -> r) adds a\
|
||||||
|
second probit,
|
||||||
|
|
||||||
w_i ~ N(u_i gamma + gamma_g arc_i g_i, 1), r_i = 1[w_i > 0]
|
w_i ~ N(u_i gamma + gamma_g arc_i g_i, 1), r_i = 1[w_i > 0]
|
||||||
|
|
||||||
with arc_i = 1 where the hospital protocol does not refer the woman's cell (referral there is clinical suspicion or
|
with arc_i = 1 where the hospital protocol does not refer the woman's cell (referral there is\
|
||||||
persistence). It keeps conjugacy: w is another truncated normal, (gamma, gamma_g) another normal regression with the
|
clinical suspicion or
|
||||||
augmented g as a column, and g gains the factor P(r_i | g = 1) / P(r_i | g = 0). With one test per woman gamma_g is
|
persistence). It keeps conjugacy: w is another truncated normal, (gamma, gamma_g) another\
|
||||||
|
normal regression with the
|
||||||
|
augmented g as a column, and g gains the factor P(r_i | g = 1) / P(r_i | g = 0). With one test\
|
||||||
|
per woman gamma_g is
|
||||||
weakly identified and needs an informative prior.
|
weakly identified and needs an informative prior.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from scipy.stats import norm, truncnorm
|
from scipy.stats import norm, truncnorm
|
||||||
|
|
||||||
|
|
||||||
def normal_posterior(X: np.ndarray, z: np.ndarray, b0: np.ndarray, B0inv: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
def normal_posterior(
|
||||||
|
X: np.ndarray, z: np.ndarray, b0: np.ndarray, B0inv: np.ndarray
|
||||||
|
) -> tuple[np.ndarray, np.ndarray]:
|
||||||
"""beta | z for a regression with unit-variance errors and prior N(b0, B0): N(m, V) with
|
"""beta | z for a regression with unit-variance errors and prior N(b0, B0): N(m, V) with
|
||||||
V = (X'X + B0^-1)^-1 and m = V (X'z + B0^-1 b0). Returns m and the Cholesky factor of V."""
|
V = (X'X + B0^-1)^-1 and m = V (X'z + B0^-1 b0). Returns m and the Cholesky factor of V."""
|
||||||
V = np.linalg.inv(X.T @ X + B0inv)
|
V = np.linalg.inv(X.T @ X + B0inv)
|
||||||
@@ -42,44 +53,69 @@ def draw_latent(mean: np.ndarray, positive: np.ndarray, rng: np.random.Generator
|
|||||||
|
|
||||||
|
|
||||||
def prob_g(p: np.ndarray, r: np.ndarray, y: np.ndarray, kappa: float, odds_r=1.0) -> np.ndarray:
|
def prob_g(p: np.ndarray, r: np.ndarray, y: np.ndarray, kappa: float, odds_r=1.0) -> np.ndarray:
|
||||||
"""P(g_i = 1 | beta, kappa, data) with z_i integrated out: prior odds p / (1 - p) times the likelihood ratio of
|
"""P(g_i = 1 | beta, kappa, data) with z_i integrated out: prior odds p / (1 - p) times\
|
||||||
|
the likelihood ratio of
|
||||||
what was observed of woman i, P(data | g = 1) / P(data | g = 0):
|
what was observed of woman i, P(data | g = 1) / P(data | g = 0):
|
||||||
|
|
||||||
* tested positive: infinite (specificity 1: only a diseased woman tests positive), so g = 1;
|
* tested positive: infinite (specificity 1: only a diseased woman tests positive), so g = 1;
|
||||||
* tested negative: (1 - kappa) / 1 (a diseased woman is missed with probability 1 - kappa);
|
* tested negative: (1 - kappa) / 1 (a diseased woman is missed with probability 1 - kappa);
|
||||||
* untested: 1 (nothing observed).
|
* untested: 1 (nothing observed).
|
||||||
|
|
||||||
`odds_r` is the extra ratio P(r_i | g = 1) / P(r_i | g = 0) of the referral arc; 1 without it."""
|
`odds_r` is the extra ratio P(r_i | g = 1) / P(r_i | g = 0) of the referral arc; 1 without\
|
||||||
|
it."""
|
||||||
lr = np.where(r == 1, np.where(y == 1, np.inf, 1.0 - kappa), 1.0) * odds_r
|
lr = np.where(r == 1, np.where(y == 1, np.inf, 1.0 - kappa), 1.0) * odds_r
|
||||||
odds = p / (1.0 - p) * lr
|
odds = p / (1.0 - p) * lr
|
||||||
with np.errstate(invalid="ignore"): # inf / inf in the branch that np.where drops
|
with np.errstate(invalid="ignore"): # inf / inf in the branch that np.where drops
|
||||||
return np.where(np.isinf(odds), 1.0, odds / (1.0 + odds))
|
return np.where(np.isinf(odds), 1.0, odds / (1.0 + odds))
|
||||||
|
|
||||||
|
|
||||||
def draw_kappa(g: np.ndarray, r: np.ndarray, y: np.ndarray, a: float, b: float, rng: np.random.Generator) -> float:
|
def draw_kappa(
|
||||||
"""kappa | g, y ~ Beta(a + detected, b + missed), counting only tested women whose (augmented) g is 1."""
|
g: np.ndarray, r: np.ndarray, y: np.ndarray, a: float, b: float, rng: np.random.Generator
|
||||||
|
) -> float:
|
||||||
|
"""kappa | g, y ~ Beta(a + detected, b + missed), counting only tested women whose\
|
||||||
|
(augmented) g is 1."""
|
||||||
diseased = (r == 1) & (g == 1)
|
diseased = (r == 1) & (g == 1)
|
||||||
detected = int((y[diseased] == 1).sum())
|
detected = int((y[diseased] == 1).sum())
|
||||||
return rng.beta(a + detected, b + int(diseased.sum()) - detected)
|
return rng.beta(a + detected, b + int(diseased.sum()) - detected)
|
||||||
|
|
||||||
|
|
||||||
def referral_odds(eta_r: np.ndarray, gamma_g: float, arc: np.ndarray, r: np.ndarray) -> np.ndarray:
|
def referral_odds(eta_r: np.ndarray, gamma_g: float, arc: np.ndarray, r: np.ndarray) -> np.ndarray:
|
||||||
"""The arc g -> r: P(r_i | g_i = 1) / P(r_i | g_i = 0) when r_i = 1[w_i > 0], w_i ~ N(eta_r_i + gamma_g arc_i g_i, 1).
|
"""The arc g -> r: P(r_i | g_i = 1) / P(r_i | g_i = 0) when r_i = 1[w_i > 0], w_i ~\
|
||||||
For a tested woman it is Phi(eta + gamma_g) / Phi(eta); for an untested one, the same with the survival
|
N(eta_r_i + gamma_g arc_i g_i, 1).
|
||||||
function. Where arc_i = 0 (the protocol refers her cell) both are equal and the ratio is 1. Logs for stability."""
|
For a tested woman it is Phi(eta + gamma_g) / Phi(eta); for an untested one, the same with\
|
||||||
|
the survival
|
||||||
|
function. Where arc_i = 0 (the protocol refers her cell) both are equal and the ratio is\
|
||||||
|
1. Logs for stability."""
|
||||||
shifted = eta_r + gamma_g * arc
|
shifted = eta_r + gamma_g * arc
|
||||||
log1 = np.where(r == 1, norm.logcdf(shifted), norm.logsf(shifted))
|
log1 = np.where(r == 1, norm.logcdf(shifted), norm.logsf(shifted))
|
||||||
log0 = np.where(r == 1, norm.logcdf(eta_r), norm.logsf(eta_r))
|
log0 = np.where(r == 1, norm.logcdf(eta_r), norm.logsf(eta_r))
|
||||||
return np.exp(log1 - log0)
|
return np.exp(log1 - log0)
|
||||||
|
|
||||||
|
|
||||||
def gibbs(X: np.ndarray, r, y, b0, B0, kappa_ab=(1.0, 1.0), U=None, arc=None, d0=None, D0=None,
|
def gibbs(
|
||||||
iterations: int = 4000, warmup: int = 2000, seed: int = 0) -> dict:
|
X: np.ndarray,
|
||||||
"""One chain. X carries the intercept column; r = 1 if the test was done with a result, y its result (ignored
|
r,
|
||||||
where r = 0). Prior beta ~ N(b0, B0), kappa ~ Beta(kappa_ab). Returns the kept draws of beta and kappa.
|
y,
|
||||||
|
b0,
|
||||||
|
B0,
|
||||||
|
kappa_ab=(1.0, 1.0),
|
||||||
|
U=None,
|
||||||
|
arc=None,
|
||||||
|
d0=None,
|
||||||
|
D0=None,
|
||||||
|
iterations: int = 4000,
|
||||||
|
warmup: int = 2000,
|
||||||
|
seed: int = 0,
|
||||||
|
) -> dict:
|
||||||
|
"""One chain. X carries the intercept column; r = 1 if the test was done with a result, y\
|
||||||
|
its result (ignored
|
||||||
|
where r = 0). Prior beta ~ N(b0, B0), kappa ~ Beta(kappa_ab). Returns the kept draws of\
|
||||||
|
beta and kappa.
|
||||||
|
|
||||||
With `U` (the referral design, with its intercept), the arc g -> r is added: w_i ~ N(U_i gamma + gamma_g arc_i g_i,
|
With `U` (the referral design, with its intercept), the arc g -> r is added: w_i ~ N(U_i\
|
||||||
1), r_i = 1[w_i > 0], with `arc` = 1 where the protocol does not refer the woman's cell (the arc acts) and
|
gamma + gamma_g arc_i g_i,
|
||||||
|
1), r_i = 1[w_i > 0], with `arc` = 1 where the protocol does not refer the woman's cell\
|
||||||
|
(the arc acts) and
|
||||||
delta = (gamma, gamma_g) ~ N(d0, D0), gamma_g last. Its draws are returned as "delta"."""
|
delta = (gamma, gamma_g) ~ N(d0, D0), gamma_g last. Its draws are returned as "delta"."""
|
||||||
rng = np.random.default_rng(seed)
|
rng = np.random.default_rng(seed)
|
||||||
r, y = np.asarray(r, int), np.asarray(y, float)
|
r, y = np.asarray(r, int), np.asarray(y, float)
|
||||||
@@ -113,8 +149,10 @@ def gibbs(X: np.ndarray, r, y, b0, B0, kappa_ab=(1.0, 1.0), U=None, arc=None, d0
|
|||||||
|
|
||||||
|
|
||||||
def split_rhat(draws: np.ndarray) -> float:
|
def split_rhat(draws: np.ndarray) -> float:
|
||||||
"""Split R-hat of one scalar (Gelman et al., BDA3, section 11.4): `draws` has shape (chains, iterations). Each
|
"""Split R-hat of one scalar (Gelman et al., BDA3, section 11.4): `draws` has shape\
|
||||||
chain is cut in half, and the spread between the halves' means is compared with the spread within them."""
|
(chains, iterations). Each
|
||||||
|
chain is cut in half, and the spread between the halves' means is compared with the spread\
|
||||||
|
within them."""
|
||||||
half = draws.shape[1] // 2
|
half = draws.shape[1] // 2
|
||||||
parts = np.concatenate([draws[:, :half], draws[:, half : 2 * half]])
|
parts = np.concatenate([draws[:, :half], draws[:, half : 2 * half]])
|
||||||
within = parts.var(axis=1, ddof=1).mean()
|
within = parts.var(axis=1, ddof=1).mean()
|
||||||
@@ -123,25 +161,33 @@ def split_rhat(draws: np.ndarray) -> float:
|
|||||||
|
|
||||||
|
|
||||||
def patterns(X, r, y, U=None, arc=None) -> dict:
|
def patterns(X, r, y, U=None, arc=None) -> dict:
|
||||||
"""Women with the same covariates and the same observation share their likelihood term: the distinct rows and
|
"""Women with the same covariates and the same observation share their likelihood term:\
|
||||||
|
the distinct rows and
|
||||||
how many women each one stands for (y = -1 marks an untested row)."""
|
how many women each one stands for (y = -1 marks an untested row)."""
|
||||||
cols = [X, r[:, None], np.nan_to_num(y, nan=-1.0)[:, None]]
|
cols = [X, r[:, None], np.nan_to_num(y, nan=-1.0)[:, None]]
|
||||||
if U is not None:
|
if U is not None:
|
||||||
cols += [U, np.asarray(arc, float)[:, None]]
|
cols += [U, np.asarray(arc, float)[:, None]]
|
||||||
rows, counts = np.unique(np.column_stack(cols), axis=0, return_counts=True)
|
rows, counts = np.unique(np.column_stack(cols), axis=0, return_counts=True)
|
||||||
p = X.shape[1]
|
p = X.shape[1]
|
||||||
out = {"X": rows[:, :p], "r": rows[:, p].astype(int), "y": rows[:, p + 1], "n": counts.astype(float)}
|
out = {
|
||||||
|
"X": rows[:, :p],
|
||||||
|
"r": rows[:, p].astype(int),
|
||||||
|
"y": rows[:, p + 1],
|
||||||
|
"n": counts.astype(float),
|
||||||
|
}
|
||||||
if U is not None:
|
if U is not None:
|
||||||
out["U"], out["arc"] = rows[:, p + 2 : -1], rows[:, -1]
|
out["U"], out["arc"] = rows[:, p + 2 : -1], rows[:, -1]
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
def pymc_model(X, r, y, b0, B0, kappa_ab=(1.0, 1.0), U=None, arc=None, d0=None, D0=None):
|
def pymc_model(X, r, y, b0, B0, kappa_ab=(1.0, 1.0), U=None, arc=None, d0=None, D0=None):
|
||||||
"""The same model with g summed out of the likelihood, so that NUTS samples only continuous parameters:
|
"""The same model with g summed out of the likelihood, so that NUTS samples only\
|
||||||
|
continuous parameters:
|
||||||
|
|
||||||
P(data_i) = P(g=1) P(r_i | g=1) P(y_i | g=1) + P(g=0) P(r_i | g=0) P(y_i | g=0)
|
P(data_i) = P(g=1) P(r_i | g=1) P(y_i | g=1) + P(g=0) P(r_i | g=0) P(y_i | g=0)
|
||||||
|
|
||||||
with P(y=1 | g=0) = 0 (specificity 1), so a tested positive keeps only the first term. Without `U` the test is
|
with P(y=1 | g=0) = 0 (specificity 1), so a tested positive keeps only the first term.\
|
||||||
|
Without `U` the test is
|
||||||
taken as done at random given x, and P(r | g) drops out, as in the Gibbs."""
|
taken as done at random given x, and P(r | g) drops out, as in the Gibbs."""
|
||||||
import pymc as pm
|
import pymc as pm
|
||||||
import pytensor.tensor as pt
|
import pytensor.tensor as pt
|
||||||
@@ -149,7 +195,11 @@ def pymc_model(X, r, y, b0, B0, kappa_ab=(1.0, 1.0), U=None, arc=None, d0=None,
|
|||||||
d = patterns(np.asarray(X, float), np.asarray(r, int), np.asarray(y, float), U, arc)
|
d = patterns(np.asarray(X, float), np.asarray(r, int), np.asarray(y, float), U, arc)
|
||||||
positive = (d["r"] == 1) & (d["y"] == 1)
|
positive = (d["r"] == 1) & (d["y"] == 1)
|
||||||
negative = (d["r"] == 1) & (d["y"] == 0)
|
negative = (d["r"] == 1) & (d["y"] == 0)
|
||||||
log_phi = lambda v: pm.logcdf(pm.Normal.dist(0.0, 1.0), v) # log Phi(v), stable in the tails
|
|
||||||
|
def log_phi(v):
|
||||||
|
# log Phi(v), stable in the tails
|
||||||
|
return pm.logcdf(pm.Normal.dist(0.0, 1.0), v)
|
||||||
|
|
||||||
with pm.Model() as model:
|
with pm.Model() as model:
|
||||||
beta = pm.MvNormal("beta", mu=np.asarray(b0, float), cov=np.asarray(B0, float))
|
beta = pm.MvNormal("beta", mu=np.asarray(b0, float), cov=np.asarray(B0, float))
|
||||||
kappa = pm.Beta("kappa", *kappa_ab)
|
kappa = pm.Beta("kappa", *kappa_ab)
|
||||||
@@ -169,22 +219,49 @@ def pymc_model(X, r, y, b0, B0, kappa_ab=(1.0, 1.0), U=None, arc=None, d0=None,
|
|||||||
return model
|
return model
|
||||||
|
|
||||||
|
|
||||||
def nuts(X, r, y, b0, B0, kappa_ab=(1.0, 1.0), U=None, arc=None, d0=None, D0=None, draws: int = 1000,
|
def nuts(
|
||||||
tune: int = 1000, chains: int = 4, seed: int = 0, cores: int | None = None) -> dict:
|
X,
|
||||||
"""NUTS on `pymc_model`. Returns the draws with the chains stacked (as in `gibbs`), the max split R-hat over the
|
r,
|
||||||
|
y,
|
||||||
|
b0,
|
||||||
|
B0,
|
||||||
|
kappa_ab=(1.0, 1.0),
|
||||||
|
U=None,
|
||||||
|
arc=None,
|
||||||
|
d0=None,
|
||||||
|
D0=None,
|
||||||
|
draws: int = 1000,
|
||||||
|
tune: int = 1000,
|
||||||
|
chains: int = 4,
|
||||||
|
seed: int = 0,
|
||||||
|
cores: int | None = None,
|
||||||
|
) -> dict:
|
||||||
|
"""NUTS on `pymc_model`. Returns the draws with the chains stacked (as in `gibbs`), the\
|
||||||
|
max split R-hat over the
|
||||||
parameters and the number of divergent transitions. `cores` defaults to one per chain."""
|
parameters and the number of divergent transitions. `cores` defaults to one per chain."""
|
||||||
import pymc as pm
|
import pymc as pm
|
||||||
|
|
||||||
with pymc_model(X, r, y, b0, B0, kappa_ab, U, arc, d0, D0):
|
with pymc_model(X, r, y, b0, B0, kappa_ab, U, arc, d0, D0):
|
||||||
idata = pm.sample(draws=draws, tune=tune, chains=chains, cores=cores or chains, random_seed=seed, progressbar=False,
|
idata = pm.sample(
|
||||||
compute_convergence_checks=False)
|
draws=draws,
|
||||||
|
tune=tune,
|
||||||
|
chains=chains,
|
||||||
|
cores=cores or chains,
|
||||||
|
random_seed=seed,
|
||||||
|
progressbar=False,
|
||||||
|
compute_convergence_checks=False,
|
||||||
|
)
|
||||||
post = idata.posterior
|
post = idata.posterior
|
||||||
out, rhats = {}, []
|
out, rhats = {}, []
|
||||||
for name in ("beta", "kappa", "delta"):
|
for name in ("beta", "kappa", "delta"):
|
||||||
if name in post:
|
if name in post:
|
||||||
v = post[name].values.reshape(chains, draws, -1) # (chains, draws, parameters)
|
v = post[name].values.reshape(chains, draws, -1) # (chains, draws, parameters)
|
||||||
rhats += [split_rhat(v[:, :, j]) for j in range(v.shape[2])]
|
rhats += [split_rhat(v[:, :, j]) for j in range(v.shape[2])]
|
||||||
out[name] = v.reshape(chains * draws, -1).squeeze() if name == "kappa" else v.reshape(chains * draws, -1)
|
out[name] = (
|
||||||
|
v.reshape(chains * draws, -1).squeeze()
|
||||||
|
if name == "kappa"
|
||||||
|
else v.reshape(chains * draws, -1)
|
||||||
|
)
|
||||||
out["rhat"] = max(rhats)
|
out["rhat"] = max(rhats)
|
||||||
out["divergences"] = int(idata.sample_stats["diverging"].values.sum())
|
out["divergences"] = int(idata.sample_stats["diverging"].values.sum())
|
||||||
return out
|
return out
|
||||||
|
|||||||
@@ -55,7 +55,9 @@ class FirthFamily(ClassifierMixin, BaseEstimator):
|
|||||||
def fit(self, X, y):
|
def fit(self, X, y):
|
||||||
"""Fit the selected method to a binary outcome."""
|
"""Fit the selected method to a binary outcome."""
|
||||||
if self.method not in ("firth", "flic", "flac"):
|
if self.method not in ("firth", "flic", "flac"):
|
||||||
raise ValueError(f"Unknown method {self.method!r}. Expected 'firth', 'flic', or 'flac'.")
|
raise ValueError(
|
||||||
|
f"Unknown method {self.method!r}. Expected 'firth', 'flic', or 'flac'."
|
||||||
|
)
|
||||||
X = np.asarray(X, float)
|
X = np.asarray(X, float)
|
||||||
firth, h = solve_logistic(X, y)
|
firth, h = solve_logistic(X, y)
|
||||||
y = np.asarray(y, int)
|
y = np.asarray(y, int)
|
||||||
|
|||||||
@@ -10,20 +10,21 @@ import time
|
|||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from scipy.special import expit, logit
|
from scipy.special import expit as expit
|
||||||
|
from scipy.special import logit
|
||||||
from sklearn.linear_model import LogisticRegression
|
from sklearn.linear_model import LogisticRegression
|
||||||
from sklearn.metrics import brier_score_loss, log_loss, roc_auc_score
|
from sklearn.metrics import brier_score_loss, log_loss, roc_auc_score
|
||||||
from sklearn.model_selection import LeaveOneOut, StratifiedKFold
|
from sklearn.model_selection import LeaveOneOut, StratifiedKFold
|
||||||
|
|
||||||
from models.cacu.development_firth import FirthFamily
|
from models.cacu.development_firth import FirthFamily
|
||||||
|
|
||||||
METHODS = ('firth', 'flic', 'flac')
|
METHODS = ("firth", "flic", "flac")
|
||||||
|
|
||||||
|
|
||||||
def _candidates(X, coverage, limit):
|
def _candidates(X, coverage, limit):
|
||||||
eligible = []
|
eligible = []
|
||||||
for name in sorted(X.columns):
|
for name in sorted(X.columns):
|
||||||
col = pd.to_numeric(X[name], errors='coerce')
|
col = pd.to_numeric(X[name], errors="coerce")
|
||||||
known = col.dropna()
|
known = col.dropna()
|
||||||
if len(known) / len(X) >= coverage and set(known.unique()) == {0, 1}:
|
if len(known) / len(X) >= coverage and set(known.unique()) == {0, 1}:
|
||||||
eligible.append((name, col.notna().mean()))
|
eligible.append((name, col.notna().mean()))
|
||||||
@@ -31,9 +32,11 @@ def _candidates(X, coverage, limit):
|
|||||||
chosen = []
|
chosen = []
|
||||||
for name, _ in sorted(eligible, key=lambda item: (-item[1], item[0])):
|
for name, _ in sorted(eligible, key=lambda item: (-item[1], item[0])):
|
||||||
a = X[name]
|
a = X[name]
|
||||||
if any(((a == X[other]) | (a.isna() & X[other].isna())).all() or
|
if any(
|
||||||
((a == 1 - X[other]) | (a.isna() & X[other].isna())).all()
|
((a == X[other]) | (a.isna() & X[other].isna())).all()
|
||||||
for other in chosen):
|
or ((a == 1 - X[other]) | (a.isna() & X[other].isna())).all()
|
||||||
|
for other in chosen
|
||||||
|
):
|
||||||
continue
|
continue
|
||||||
chosen.append(name)
|
chosen.append(name)
|
||||||
if len(chosen) == limit:
|
if len(chosen) == limit:
|
||||||
@@ -45,11 +48,11 @@ def _matrix(train, test, columns):
|
|||||||
tr = train[list(columns)].to_numpy(dtype=float)
|
tr = train[list(columns)].to_numpy(dtype=float)
|
||||||
te = test[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():
|
if tr.shape[1] and np.isnan(tr).all(axis=0).any():
|
||||||
raise ValueError('predictor absent in training partition')
|
raise ValueError("predictor absent in training partition")
|
||||||
median = np.nanmedian(tr, axis=0) if tr.shape[1] else np.array([])
|
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)
|
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:
|
if np.linalg.matrix_rank(np.column_stack([np.ones(len(tr)), tr])) < len(columns) + 1:
|
||||||
raise ValueError('collinear predictors in training partition')
|
raise ValueError("collinear predictors in training partition")
|
||||||
return tr, te
|
return tr, te
|
||||||
|
|
||||||
|
|
||||||
@@ -64,50 +67,76 @@ def _metrics(y, probability):
|
|||||||
y, p = np.asarray(y), np.asarray(probability)
|
y, p = np.asarray(y), np.asarray(probability)
|
||||||
valid = np.isfinite(p)
|
valid = np.isfinite(p)
|
||||||
if valid.sum() != len(y) or len(np.unique(y)) != 2:
|
if valid.sum() != len(y) or len(np.unique(y)) != 2:
|
||||||
return {'auc': None, 'brier': None, 'calibration_intercept': None,
|
return {
|
||||||
'calibration_slope': None, 'log_loss': None}
|
"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)
|
logits = logit(np.clip(p, 1e-12, 1 - 1e-12)).reshape(-1, 1)
|
||||||
calibration = LogisticRegression(C=1e6).fit(logits, y)
|
calibration = LogisticRegression(C=1e6).fit(logits, y)
|
||||||
return {'auc': float(roc_auc_score(y, p)), 'brier': float(brier_score_loss(y, p)),
|
return {
|
||||||
'calibration_intercept': float(calibration.intercept_[0]),
|
"auc": float(roc_auc_score(y, p)),
|
||||||
'calibration_slope': float(calibration.coef_[0, 0]),
|
"brier": float(brier_score_loss(y, p)),
|
||||||
'log_loss': float(log_loss(y, p, labels=[0, 1]))}
|
"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,
|
def evaluate(
|
||||||
outer_folds=3, inner_folds=2, seed=17, max_fits=100000):
|
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.
|
"""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
|
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
|
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.
|
every outer split; all attempted subsets and failures are recorded.
|
||||||
"""
|
"""
|
||||||
X = X.reset_index(drop=True).apply(pd.to_numeric, errors='coerce')
|
X = X.reset_index(drop=True).apply(pd.to_numeric, errors="coerce")
|
||||||
y = np.asarray(y)
|
y = np.asarray(y)
|
||||||
if len(X) != len(y) or not np.isin(y, [0, 1]).all():
|
if len(X) != len(y) or not np.isin(y, [0, 1]).all():
|
||||||
raise ValueError('one known binary outcome is required per row')
|
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):
|
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')
|
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:
|
if not 1 <= candidate_limit <= 8 or not 1 <= subset_limit <= candidate_limit:
|
||||||
raise ValueError('candidate and subset limits exceed the supported bounds')
|
raise ValueError("candidate and subset limits exceed the supported bounds")
|
||||||
max_subsets = sum(math.comb(candidate_limit, k)
|
max_subsets = sum(
|
||||||
for k in range(min(candidate_limit, subset_limit) + 1))
|
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)
|
estimated_fits = (outer_folds + len(X)) * len(METHODS) * (max_subsets * inner_folds + 1)
|
||||||
if estimated_fits > max_fits:
|
if estimated_fits > max_fits:
|
||||||
raise ValueError(f'estimated {estimated_fits} fits exceeds configured limit {max_fits}')
|
raise ValueError(f"estimated {estimated_fits} fits exceeds configured limit {max_fits}")
|
||||||
attempted, outputs = [], {}
|
attempted, outputs = [], {}
|
||||||
started = time.monotonic()
|
started = time.monotonic()
|
||||||
plans = {'cv': StratifiedKFold(outer_folds, shuffle=True, random_state=seed).split(X, y),
|
plans = {
|
||||||
'loocv': LeaveOneOut().split(X, y)}
|
"cv": StratifiedKFold(outer_folds, shuffle=True, random_state=seed).split(X, y),
|
||||||
|
"loocv": LeaveOneOut().split(X, y),
|
||||||
|
}
|
||||||
for plan, splits in plans.items():
|
for plan, splits in plans.items():
|
||||||
predictions = {m: np.full(len(X), np.nan) for m in METHODS}
|
predictions = {m: np.full(len(X), np.nan) for m in METHODS}
|
||||||
selected = {m: [] for m in METHODS}
|
selected = {m: [] for m in METHODS}
|
||||||
for fold, (train_idx, test_idx) in enumerate(splits):
|
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)
|
train, test, ytrain = X.iloc[train_idx], X.iloc[test_idx], y[train_idx].astype(int)
|
||||||
candidates = _candidates(train, coverage, candidate_limit)
|
candidates = _candidates(train, coverage, candidate_limit)
|
||||||
subsets = [()] + [c for size in range(1, min(len(candidates), subset_limit) + 1)
|
subsets = [()] + [
|
||||||
for c in itertools.combinations(candidates, size)]
|
c
|
||||||
inner = list(StratifiedKFold(inner_folds, shuffle=True, random_state=seed).split(train, ytrain))
|
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:
|
for method in METHODS:
|
||||||
ranking = []
|
ranking = []
|
||||||
for columns in subsets:
|
for columns in subsets:
|
||||||
@@ -115,28 +144,50 @@ def evaluate(X: pd.DataFrame, y, *, coverage=0.7, candidate_limit=5, subset_limi
|
|||||||
error = None
|
error = None
|
||||||
try:
|
try:
|
||||||
for a, b in inner:
|
for a, b in inner:
|
||||||
probs[b] = _predict(train.iloc[a], ytrain[a], train.iloc[b], columns, method)
|
probs[b] = _predict(
|
||||||
|
train.iloc[a], ytrain[a], train.iloc[b], columns, method
|
||||||
|
)
|
||||||
loss = float(log_loss(ytrain, probs, labels=[0, 1]))
|
loss = float(log_loss(ytrain, probs, labels=[0, 1]))
|
||||||
ranking.append((loss, len(columns), columns))
|
ranking.append((loss, len(columns), columns))
|
||||||
except (ValueError, np.linalg.LinAlgError, RuntimeError) as exc:
|
except (ValueError, np.linalg.LinAlgError, RuntimeError) as exc:
|
||||||
loss, error = None, type(exc).__name__
|
loss, error = None, type(exc).__name__
|
||||||
attempted.append({'validation': plan, 'fold': fold, 'method': method,
|
attempted.append(
|
||||||
'variables': list(columns), 'inner_log_loss': loss, 'error': error})
|
{
|
||||||
|
"validation": plan,
|
||||||
|
"fold": fold,
|
||||||
|
"method": method,
|
||||||
|
"variables": list(columns),
|
||||||
|
"inner_log_loss": loss,
|
||||||
|
"error": error,
|
||||||
|
}
|
||||||
|
)
|
||||||
_, _, best = min(ranking)
|
_, _, best = min(ranking)
|
||||||
selected[method].append(list(best))
|
selected[method].append(list(best))
|
||||||
try:
|
try:
|
||||||
predictions[method][test_idx] = _predict(train, ytrain, test, best, method)
|
predictions[method][test_idx] = _predict(train, ytrain, test, best, method)
|
||||||
except (ValueError, np.linalg.LinAlgError, RuntimeError):
|
except (ValueError, np.linalg.LinAlgError, RuntimeError):
|
||||||
pass
|
pass
|
||||||
outputs[plan] = {m: {'metrics': _metrics(y, predictions[m]), 'selected': selected[m],
|
outputs[plan] = {
|
||||||
'unscored': int(np.isnan(predictions[m]).sum()),
|
m: {
|
||||||
'stability': {name: sum(name in cols for cols in selected[m])
|
"metrics": _metrics(y, predictions[m]),
|
||||||
for name in X.columns}}
|
"selected": selected[m],
|
||||||
for m in METHODS}
|
"unscored": int(np.isnan(predictions[m]).sum()),
|
||||||
return {'development_only': True, 'candidate_limit': candidate_limit,
|
"stability": {
|
||||||
'subset_limit': subset_limit, 'coverage_minimum': coverage,
|
name: sum(name in cols for cols in selected[m]) for name in X.columns
|
||||||
'max_subsets': max_subsets, 'maximum_fits': estimated_fits,
|
},
|
||||||
'estimated_seconds_at_50ms_per_fit': estimated_fits * 0.05,
|
}
|
||||||
'elapsed_seconds': time.monotonic() - started,
|
for m in METHODS
|
||||||
'source': 'edgar/camodels@2392d54fd4a3942b56dae803906586bc65600728',
|
}
|
||||||
'attempts': attempted, 'validation': outputs}
|
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,
|
||||||
|
}
|
||||||
|
|||||||
@@ -118,11 +118,15 @@ def last_screening_cytology(events: pd.DataFrame) -> pd.Series:
|
|||||||
key = ["person_id", "source_table", "source_id"]
|
key = ["person_id", "source_table", "source_id"]
|
||||||
samples = events.loc[(events["type"] == "cytology") & ~events["person_id"].isin(referred),
|
samples = events.loc[(events["type"] == "cytology") & ~events["person_id"].isin(referred),
|
||||||
[*key, "date"]] # fmt: skip
|
[*key, "date"]] # fmt: skip
|
||||||
hysterectomy = events.loc[
|
hysterectomy = (
|
||||||
|
events.loc[
|
||||||
(events["source_table"] == "cervical_cytology")
|
(events["source_table"] == "cervical_cytology")
|
||||||
& (events["type"] == "gynecologic_condition")
|
& (events["type"] == "gynecologic_condition")
|
||||||
& (events["value_code"] == "hysterectomy")
|
& (events["value_code"] == "hysterectomy")
|
||||||
].groupby("person_id")["date"].min()
|
]
|
||||||
|
.groupby("person_id")["date"]
|
||||||
|
.min()
|
||||||
|
)
|
||||||
recorded = samples["person_id"].map(hysterectomy)
|
recorded = samples["person_id"].map(hysterectomy)
|
||||||
samples = samples[recorded.isna() | (samples["date"] < recorded)]
|
samples = samples[recorded.isna() | (samples["date"] < recorded)]
|
||||||
results = events[events["type"].isin(RESULTS) & events["value_code"].notna()]
|
results = events[events["type"].isin(RESULTS) & events["value_code"].notna()]
|
||||||
|
|||||||
+18
-8
@@ -271,8 +271,9 @@ class Mixture(BaseEstimator):
|
|||||||
point, variance = self.fits_[key].risk_with_variance(
|
point, variance = self.fits_[key].risk_with_variance(
|
||||||
unique[:, :n_x], unique[:, n_x:], self.horizons_years
|
unique[:, :n_x], unique[:, n_x:], self.horizons_years
|
||||||
)
|
)
|
||||||
relative = np.where(np.isfinite(variance),
|
relative = np.where(
|
||||||
np.sqrt(variance) / np.maximum(point, 1e-300), np.nan)
|
np.isfinite(variance), np.sqrt(variance) / np.maximum(point, 1e-300), np.nan
|
||||||
|
)
|
||||||
band = np.column_stack([point, np.clip(point * np.exp(-z * relative), 0, 1),
|
band = np.column_stack([point, np.clip(point * np.exp(-z * relative), 0, 1),
|
||||||
np.clip(point * np.exp(z * relative), 0, 1)]) # fmt: skip
|
np.clip(point * np.exp(z * relative), 0, 1)]) # fmt: skip
|
||||||
out[index[placed]] = band[inverse.ravel()]
|
out[index[placed]] = band[inverse.ravel()]
|
||||||
@@ -286,8 +287,11 @@ class Mixture(BaseEstimator):
|
|||||||
f = self.fits_.get(key)
|
f = self.fits_.get(key)
|
||||||
predictions = self.predict(X.iloc[index])
|
predictions = self.predict(X.iloc[index])
|
||||||
missing = np.isnan(predictions[:, h:]).any(axis=1)
|
missing = np.isnan(predictions[:, h:]).any(axis=1)
|
||||||
entry = {"stratum": [str(v) for v in key], "rows": len(index),
|
entry = {
|
||||||
"rows_without_interval": int(missing.sum())}
|
"stratum": [str(v) for v in key],
|
||||||
|
"rows": len(index),
|
||||||
|
"rows_without_interval": int(missing.sum()),
|
||||||
|
}
|
||||||
if f is None:
|
if f is None:
|
||||||
entry.update(status="unseen_stratum", frozen_parameters=[], negative_variances=[])
|
entry.update(status="unseen_stratum", frozen_parameters=[], negative_variances=[])
|
||||||
else:
|
else:
|
||||||
@@ -297,12 +301,18 @@ class Mixture(BaseEstimator):
|
|||||||
free = np.isfinite(diagonal)
|
free = np.isfinite(diagonal)
|
||||||
block = f.covariance[np.ix_(free, free)]
|
block = f.covariance[np.ix_(free, free)]
|
||||||
try:
|
try:
|
||||||
positive = bool(block.size and np.isfinite(block).all()
|
positive = bool(
|
||||||
|
block.size
|
||||||
|
and np.isfinite(block).all()
|
||||||
and np.allclose(block, block.T)
|
and np.allclose(block, block.T)
|
||||||
and (np.linalg.eigvalsh(block) > 0).all())
|
and (np.linalg.eigvalsh(block) > 0).all()
|
||||||
|
)
|
||||||
except np.linalg.LinAlgError:
|
except np.linalg.LinAlgError:
|
||||||
positive = False
|
positive = False
|
||||||
entry.update(status="positive_definite" if positive else "not_estimable",
|
entry.update(
|
||||||
frozen_parameters=frozen, negative_variances=negative)
|
status="positive_definite" if positive else "not_estimable",
|
||||||
|
frozen_parameters=frozen,
|
||||||
|
negative_variances=negative,
|
||||||
|
)
|
||||||
result.append(entry)
|
result.append(entry)
|
||||||
return {"strata": result, "horizons_years": list(self.horizons_years)}
|
return {"strata": result, "horizons_years": list(self.horizons_years)}
|
||||||
|
|||||||
+22
-11
@@ -36,13 +36,21 @@ COHORT_SCENARIOS = {
|
|||||||
AWAITING = {"unreported_biopsy", "no_index_result"}
|
AWAITING = {"unreported_biopsy", "no_index_result"}
|
||||||
# Clinical categories, not execution order: a candidate may belong to several stages.
|
# Clinical categories, not execution order: a candidate may belong to several stages.
|
||||||
REASON_STAGE = {
|
REASON_STAGE = {
|
||||||
"hysterectomy": "eligibility", "under_18": "eligibility",
|
"hysterectomy": "eligibility",
|
||||||
"no_birth_date": "eligibility", "died_by_index": "eligibility",
|
"under_18": "eligibility",
|
||||||
"prior_outcome": "history", "outcome_by_index": "history",
|
"no_birth_date": "eligibility",
|
||||||
"cancer_history": "history", "prior_treatment": "history",
|
"died_by_index": "eligibility",
|
||||||
"outcome_before_index": "history", "no_pretreatment_biopsy": "history",
|
"prior_outcome": "history",
|
||||||
"no_referral": "index", "referral_not_graded": "index", "no_cotest": "index",
|
"outcome_by_index": "history",
|
||||||
"no_index_result": "index", "unreported_biopsy": "index",
|
"cancer_history": "history",
|
||||||
|
"prior_treatment": "history",
|
||||||
|
"outcome_before_index": "history",
|
||||||
|
"no_pretreatment_biopsy": "history",
|
||||||
|
"no_referral": "index",
|
||||||
|
"referral_not_graded": "index",
|
||||||
|
"no_cotest": "index",
|
||||||
|
"no_index_result": "index",
|
||||||
|
"unreported_biopsy": "index",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -75,8 +83,10 @@ def attrition(cohort: str, rows: pd.DataFrame, people: int, as_of: date) -> dict
|
|||||||
str(stage): len(group[key].drop_duplicates())
|
str(stage): len(group[key].drop_duplicates())
|
||||||
for stage, group in stages.groupby("stage", sort=True)
|
for stage, group in stages.groupby("stage", sort=True)
|
||||||
},
|
},
|
||||||
"stage_by_reason": {str(reason): REASON_STAGE.get(str(reason), "unknown")
|
"stage_by_reason": {
|
||||||
for reason in sorted(excluded["criterion"].unique())},
|
str(reason): REASON_STAGE.get(str(reason), "unknown")
|
||||||
|
for reason in sorted(excluded["criterion"].unique())
|
||||||
|
},
|
||||||
"stage_counts_overlap": True,
|
"stage_counts_overlap": True,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -129,8 +139,9 @@ def _label(feature: str, value) -> str:
|
|||||||
|
|
||||||
|
|
||||||
def _band(curve, variance) -> tuple[list, list]:
|
def _band(curve, variance) -> tuple[list, list]:
|
||||||
relative = np.where(np.isfinite(variance),
|
relative = np.where(
|
||||||
np.sqrt(variance) / np.maximum(curve, 1e-300), np.nan)
|
np.isfinite(variance), np.sqrt(variance) / np.maximum(curve, 1e-300), np.nan
|
||||||
|
)
|
||||||
return (np.clip(curve * np.exp(-Z * relative), 0, 1).tolist(),
|
return (np.clip(curve * np.exp(-Z * relative), 0, 1).tolist(),
|
||||||
np.clip(curve * np.exp(Z * relative), 0, 1).tolist()) # fmt: skip
|
np.clip(curve * np.exp(Z * relative), 0, 1).tolist()) # fmt: skip
|
||||||
|
|
||||||
|
|||||||
@@ -49,9 +49,13 @@ def _rows(members: pd.DataFrame, risks: np.ndarray, horizons, predictors=()) ->
|
|||||||
frame["ci_low"], frame["ci_high"] = risks[:, h : 2 * h].ravel(), risks[:, 2 * h :].ravel()
|
frame["ci_low"], frame["ci_high"] = risks[:, h : 2 * h].ravel(), risks[:, 2 * h :].ravel()
|
||||||
else:
|
else:
|
||||||
frame["ci_low"] = frame["ci_high"] = np.nan
|
frame["ci_low"] = frame["ci_high"] = np.nan
|
||||||
frame["input_values"] = np.repeat([
|
frame["input_values"] = np.repeat(
|
||||||
|
[
|
||||||
json.dumps({k: None if pd.isna(v) else v for k, v in row.items()}, default=str)
|
json.dumps({k: None if pd.isna(v) else v for k, v in row.items()}, default=str)
|
||||||
for row in members[list(predictors)].to_dict("records")], h)
|
for row in members[list(predictors)].to_dict("records")
|
||||||
|
],
|
||||||
|
h,
|
||||||
|
)
|
||||||
return frame[[*OUTPUT, "input_values"]]
|
return frame[[*OUTPUT, "input_values"]]
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+10
-5
@@ -96,7 +96,9 @@ class CacuDevelopmentEvaluation(dg.Config):
|
|||||||
|
|
||||||
|
|
||||||
@dg.op
|
@dg.op
|
||||||
def evaluate_cacu_development(context: dg.OpExecutionContext, config: CacuDevelopmentEvaluation) -> str:
|
def evaluate_cacu_development(
|
||||||
|
context: dg.OpExecutionContext, config: CacuDevelopmentEvaluation
|
||||||
|
) -> str:
|
||||||
"""Opt-in research evaluation only: no registered model, promotion or patient scores."""
|
"""Opt-in research evaluation only: no registered model, promotion or patient scores."""
|
||||||
import mlflow
|
import mlflow
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
@@ -112,8 +114,9 @@ def evaluate_cacu_development(context: dg.OpExecutionContext, config: CacuDevelo
|
|||||||
if events.empty:
|
if events.empty:
|
||||||
raise EmptyCohort(f"no eligible patients in {cohort}")
|
raise EmptyCohort(f"no eligible patients in {cohort}")
|
||||||
encoded = encoders.encode(events, gold.cervical_forms(cohort))
|
encoded = encoders.encode(events, gold.cervical_forms(cohort))
|
||||||
outcome = features.windowed_outcome(features.prepared(events), cacu.CIN2_PLUS, 1.0,
|
outcome = features.windowed_outcome(
|
||||||
pd.Timestamp(as_of))
|
features.prepared(events), cacu.CIN2_PLUS, 1.0, pd.Timestamp(as_of)
|
||||||
|
)
|
||||||
rows = encoded.merge(outcome, on="person_id", validate="one_to_one")
|
rows = encoded.merge(outcome, on="person_id", validate="one_to_one")
|
||||||
rows = rows[rows["known"]].reset_index(drop=True)
|
rows = rows[rows["known"]].reset_index(drop=True)
|
||||||
X = rows.drop(columns=["person_id", "index_date", "known", "y"])
|
X = rows.drop(columns=["person_id", "index_date", "known", "y"])
|
||||||
@@ -185,5 +188,7 @@ nightly = (
|
|||||||
else []
|
else []
|
||||||
)
|
)
|
||||||
|
|
||||||
defs = dg.Definitions(jobs=[ingest, train, score, analyze, rebuild, backup,
|
defs = dg.Definitions(
|
||||||
cacu_development_evaluation], schedules=nightly)
|
jobs=[ingest, train, score, analyze, rebuild, backup, cacu_development_evaluation],
|
||||||
|
schedules=nightly,
|
||||||
|
)
|
||||||
|
|||||||
+2
-1
@@ -73,7 +73,8 @@ class Jobs:
|
|||||||
}
|
}
|
||||||
if hasattr(fitted, "variance_diagnostics"):
|
if hasattr(fitted, "variance_diagnostics"):
|
||||||
found["variance_diagnostics"] = fitted.variance_diagnostics(
|
found["variance_diagnostics"] = fitted.variance_diagnostics(
|
||||||
data["coded"][spec.features])
|
data["coded"][spec.features]
|
||||||
|
)
|
||||||
# Bootstraps ran on joblib's worker pool: release it now, or the job's process waits
|
# Bootstraps ran on joblib's worker pool: release it now, or the job's process waits
|
||||||
# for its idle workers to time out (5 minutes) before it can end.
|
# for its idle workers to time out (5 minutes) before it can end.
|
||||||
get_reusable_executor().shutdown(wait=True)
|
get_reusable_executor().shutdown(wait=True)
|
||||||
|
|||||||
+25
-8
@@ -351,9 +351,13 @@ class Spec:
|
|||||||
"scenarios": np.repeat(np.asarray(scenarios, dtype=object), h),
|
"scenarios": np.repeat(np.asarray(scenarios, dtype=object), h),
|
||||||
})[OUTPUT] # fmt: skip
|
})[OUTPUT] # fmt: skip
|
||||||
if self.cohort.startswith("cacu_"):
|
if self.cohort.startswith("cacu_"):
|
||||||
result["input_values"] = np.repeat([
|
result["input_values"] = np.repeat(
|
||||||
|
[
|
||||||
json.dumps({k: None if pd.isna(v) else v for k, v in row.items()}, default=str)
|
json.dumps({k: None if pd.isna(v) else v for k, v in row.items()}, default=str)
|
||||||
for row in members[list(self.features)].to_dict("records")], h)
|
for row in members[list(self.features)].to_dict("records")
|
||||||
|
],
|
||||||
|
h,
|
||||||
|
)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
@@ -462,7 +466,10 @@ def _combination_curves(spec: Spec, model: IntervalSurvival, members: pd.DataFra
|
|||||||
entry["points"] = {"COMB": point}
|
entry["points"] = {"COMB": point}
|
||||||
entry["horizons_months"] = list(spec.borders[1:])
|
entry["horizons_months"] = list(spec.borders[1:])
|
||||||
entry["km"]["interval"] = {
|
entry["km"]["interval"] = {
|
||||||
"available": True, "level": 0.95, "method": "greenwood_log_log"}
|
"available": True,
|
||||||
|
"level": 0.95,
|
||||||
|
"method": "greenwood_log_log",
|
||||||
|
}
|
||||||
for name in ("weibull", "weibull_fractional"):
|
for name in ("weibull", "weibull_fractional"):
|
||||||
entry[name]["interval"] = {"available": False, "level": None, "method": None}
|
entry[name]["interval"] = {"available": False, "level": None, "method": None}
|
||||||
found.append(entry)
|
found.append(entry)
|
||||||
@@ -550,20 +557,30 @@ def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
|
|||||||
}
|
}
|
||||||
if spec.cohort.startswith("cacu_"):
|
if spec.cohort.startswith("cacu_"):
|
||||||
for curve in report["curves"]:
|
for curve in report["curves"]:
|
||||||
method = ("greenwood_log_log" if curve["name"].startswith("Kaplan-Meier")
|
method = (
|
||||||
else "delta_method")
|
"greenwood_log_log" if curve["name"].startswith("Kaplan-Meier") else "delta_method"
|
||||||
|
)
|
||||||
curve["interval"] = {"available": True, "level": 0.95, "method": method}
|
curve["interval"] = {"available": True, "level": 0.95, "method": method}
|
||||||
report["predicted"]["interval"] = {
|
report["predicted"]["interval"] = {
|
||||||
"available": True, "level": 0.95, "method": "bootstrap_percentile"}
|
"available": True,
|
||||||
|
"level": 0.95,
|
||||||
|
"method": "bootstrap_percentile",
|
||||||
|
}
|
||||||
for combination in report["combinations"]:
|
for combination in report["combinations"]:
|
||||||
combination["interval"] = {"available": False, "level": None, "method": None}
|
combination["interval"] = {"available": False, "level": None, "method": None}
|
||||||
for scenario in report["escenarios"]:
|
for scenario in report["escenarios"]:
|
||||||
scenario["km"]["interval"] = {
|
scenario["km"]["interval"] = {
|
||||||
"available": True, "level": 0.95, "method": "greenwood_log_log"}
|
"available": True,
|
||||||
|
"level": 0.95,
|
||||||
|
"method": "greenwood_log_log",
|
||||||
|
}
|
||||||
for name in ("weibull", "weibull_fractional"):
|
for name in ("weibull", "weibull_fractional"):
|
||||||
scenario[name]["interval"] = {"available": False, "level": None, "method": None}
|
scenario[name]["interval"] = {"available": False, "level": None, "method": None}
|
||||||
scenario["points"]["COMB"]["interval"] = {
|
scenario["points"]["COMB"]["interval"] = {
|
||||||
"available": True, "level": 0.95, "method": "bootstrap_percentile"}
|
"available": True,
|
||||||
|
"level": 0.95,
|
||||||
|
"method": "bootstrap_percentile",
|
||||||
|
}
|
||||||
for scenario in report["escenarios_sin_curvas"]:
|
for scenario in report["escenarios_sin_curvas"]:
|
||||||
scenario["reason"] = "insufficient_deaths"
|
scenario["reason"] = "insufficient_deaths"
|
||||||
report["km_combinaciones"] = _combination_curves(spec, model, members)
|
report["km_combinaciones"] = _combination_curves(spec, model, members)
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
import pytest
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
import pytest
|
||||||
from scipy.stats import norm
|
from scipy.stats import norm
|
||||||
|
|
||||||
from models.cacu.bayes_development import prevalence_gibbs as PG
|
from models.cacu.bayes_development import prevalence_gibbs as PG
|
||||||
|
|
||||||
|
|
||||||
def test_normal_posterior_is_least_squares_under_a_flat_prior():
|
def test_normal_posterior_is_least_squares_under_a_flat_prior():
|
||||||
"""Fails if the conjugate mean does not reduce to least squares when the prior carries no information."""
|
"""Fails if the conjugate mean does not reduce to least squares when the prior carries no\
|
||||||
|
information."""
|
||||||
rng = np.random.default_rng(1)
|
rng = np.random.default_rng(1)
|
||||||
X = np.column_stack([np.ones(200), rng.normal(size=200)])
|
X = np.column_stack([np.ones(200), rng.normal(size=200)])
|
||||||
z = X @ [0.5, -1.0] + rng.normal(size=200)
|
z = X @ [0.5, -1.0] + rng.normal(size=200)
|
||||||
@@ -24,7 +25,8 @@ def test_latent_sign_follows_g():
|
|||||||
|
|
||||||
|
|
||||||
def test_prob_g_by_observation():
|
def test_prob_g_by_observation():
|
||||||
"""Fails if a tested positive is not certainly diseased, an untested woman does not keep her prior, or a tested
|
"""Fails if a tested positive is not certainly diseased, an untested woman does not keep\
|
||||||
|
her prior, or a tested
|
||||||
negative is not discounted by 1 - kappa."""
|
negative is not discounted by 1 - kappa."""
|
||||||
p, k = np.full(3, 0.2), 0.7
|
p, k = np.full(3, 0.2), 0.7
|
||||||
out = PG.prob_g(p, np.array([1, 0, 1]), np.array([1.0, np.nan, 0.0]), k)
|
out = PG.prob_g(p, np.array([1, 0, 1]), np.array([1.0, np.nan, 0.0]), k)
|
||||||
@@ -33,7 +35,8 @@ def test_prob_g_by_observation():
|
|||||||
|
|
||||||
|
|
||||||
def test_gibbs_recovers_the_prevalence_with_known_sensitivity():
|
def test_gibbs_recovers_the_prevalence_with_known_sensitivity():
|
||||||
"""Fails if, with kappa pinned by a strong prior, the chain misses the true probit coefficients of a simulated
|
"""Fails if, with kappa pinned by a strong prior, the chain misses the true probit\
|
||||||
|
coefficients of a simulated
|
||||||
cross-sectional sample (60 % tested, one test each)."""
|
cross-sectional sample (60 % tested, one test each)."""
|
||||||
rng = np.random.default_rng(3)
|
rng = np.random.default_rng(3)
|
||||||
n, beta, kappa = 6000, np.array([-1.2, 0.8]), 0.7
|
n, beta, kappa = 6000, np.array([-1.2, 0.8]), 0.7
|
||||||
@@ -41,13 +44,24 @@ def test_gibbs_recovers_the_prevalence_with_known_sensitivity():
|
|||||||
g = rng.random(n) < norm.cdf(X @ beta)
|
g = rng.random(n) < norm.cdf(X @ beta)
|
||||||
r = (rng.random(n) < 0.6).astype(int)
|
r = (rng.random(n) < 0.6).astype(int)
|
||||||
y = np.where(r == 1, g & (rng.random(n) < kappa), np.nan)
|
y = np.where(r == 1, g & (rng.random(n) < kappa), np.nan)
|
||||||
out = PG.gibbs(X, r, y, np.zeros(2), np.eye(2) * 4, kappa_ab=(7000, 3000), iterations=1500, warmup=500, seed=4)
|
out = PG.gibbs(
|
||||||
|
X,
|
||||||
|
r,
|
||||||
|
y,
|
||||||
|
np.zeros(2),
|
||||||
|
np.eye(2) * 4,
|
||||||
|
kappa_ab=(7000, 3000),
|
||||||
|
iterations=1500,
|
||||||
|
warmup=500,
|
||||||
|
seed=4,
|
||||||
|
)
|
||||||
assert np.allclose(out["beta"].mean(0), beta, atol=0.12)
|
assert np.allclose(out["beta"].mean(0), beta, atol=0.12)
|
||||||
assert abs(out["kappa"].mean() - 0.7) < 0.02
|
assert abs(out["kappa"].mean() - 0.7) < 0.02
|
||||||
|
|
||||||
|
|
||||||
def test_referral_odds():
|
def test_referral_odds():
|
||||||
"""Fails if the arc ratio is not 1 where the arc is off, or not Phi(eta + gamma_g) / Phi(eta) for a tested woman
|
"""Fails if the arc ratio is not 1 where the arc is off, or not Phi(eta + gamma_g) /\
|
||||||
|
Phi(eta) for a tested woman
|
||||||
and the same with the survival function for an untested one."""
|
and the same with the survival function for an untested one."""
|
||||||
eta, gg = np.array([-1.0, -1.0, 0.5]), 0.8
|
eta, gg = np.array([-1.0, -1.0, 0.5]), 0.8
|
||||||
out = PG.referral_odds(eta, gg, np.array([0.0, 1.0, 1.0]), np.array([1, 1, 0]))
|
out = PG.referral_odds(eta, gg, np.array([0.0, 1.0, 1.0]), np.array([1, 1, 0]))
|
||||||
@@ -57,8 +71,10 @@ def test_referral_odds():
|
|||||||
|
|
||||||
|
|
||||||
def _referral_sample(n=8000, seed=5):
|
def _referral_sample(n=8000, seed=5):
|
||||||
"""Two cells: the protocol refers the abnormal one (84 %); the normal one is referred mostly when diseased
|
"""Two cells: the protocol refers the abnormal one (84 %); the normal one is referred\
|
||||||
(3.6 % healthy, 38 % diseased: gamma_g = 1.5). True prevalence of the normal cell: Phi(-1.6) = 5.5 %."""
|
mostly when diseased
|
||||||
|
(3.6 % healthy, 38 % diseased: gamma_g = 1.5). True prevalence of the normal cell:\
|
||||||
|
Phi(-1.6) = 5.5 %."""
|
||||||
rng = np.random.default_rng(seed)
|
rng = np.random.default_rng(seed)
|
||||||
abnormal = (rng.random(n) < 0.2).astype(float)
|
abnormal = (rng.random(n) < 0.2).astype(float)
|
||||||
X = np.column_stack([np.ones(n), abnormal])
|
X = np.column_stack([np.ones(n), abnormal])
|
||||||
@@ -71,10 +87,13 @@ def _referral_sample(n=8000, seed=5):
|
|||||||
|
|
||||||
|
|
||||||
def test_the_arc_removes_the_selection_bias():
|
def test_the_arc_removes_the_selection_bias():
|
||||||
"""Fails if ignoring who gets referred does not overstate the prevalence of the unreferred cell, or if the arc
|
"""Fails if ignoring who gets referred does not overstate the prevalence of the unreferred\
|
||||||
|
cell, or if the arc
|
||||||
with an informative prior on gamma_g does not bring it back to the truth (5.5 %)."""
|
with an informative prior on gamma_g does not bring it back to the truth (5.5 %)."""
|
||||||
X, r, y, U, arc = _referral_sample()
|
X, r, y, U, arc = _referral_sample()
|
||||||
common = dict(b0=np.zeros(2), B0=np.eye(2) * 4, kappa_ab=(7000, 3000), iterations=1500, warmup=500, seed=6)
|
common = dict(
|
||||||
|
b0=np.zeros(2), B0=np.eye(2) * 4, kappa_ab=(7000, 3000), iterations=1500, warmup=500, seed=6
|
||||||
|
)
|
||||||
without = PG.gibbs(X, r, y, **common)
|
without = PG.gibbs(X, r, y, **common)
|
||||||
with_arc = PG.gibbs(X, r, y, U=U, arc=arc, d0=[0, 0, 1.5], D0=np.diag([4, 4, 0.09]), **common)
|
with_arc = PG.gibbs(X, r, y, U=U, arc=arc, d0=[0, 0, 1.5], D0=np.diag([4, 4, 0.09]), **common)
|
||||||
assert norm.cdf(without["beta"][:, 0]).mean() > 0.2
|
assert norm.cdf(without["beta"][:, 0]).mean() > 0.2
|
||||||
@@ -83,7 +102,8 @@ def test_the_arc_removes_the_selection_bias():
|
|||||||
|
|
||||||
|
|
||||||
def test_split_rhat():
|
def test_split_rhat():
|
||||||
"""Fails if well-mixed chains do not give R-hat near 1, or chains stuck at different levels do not exceed 1.1."""
|
"""Fails if well-mixed chains do not give R-hat near 1, or chains stuck at different\
|
||||||
|
levels do not exceed 1.1."""
|
||||||
rng = np.random.default_rng(7)
|
rng = np.random.default_rng(7)
|
||||||
assert abs(PG.split_rhat(rng.normal(size=(4, 2000))) - 1) < 0.01
|
assert abs(PG.split_rhat(rng.normal(size=(4, 2000))) - 1) < 0.01
|
||||||
assert PG.split_rhat(rng.normal(size=(4, 2000)) + np.arange(4)[:, None]) > 1.1
|
assert PG.split_rhat(rng.normal(size=(4, 2000)) + np.arange(4)[:, None]) > 1.1
|
||||||
@@ -94,12 +114,15 @@ def test_patterns_keep_every_woman():
|
|||||||
X, r, y, U, arc = _referral_sample(n=500)
|
X, r, y, U, arc = _referral_sample(n=500)
|
||||||
d = PG.patterns(X, r, y, U, arc)
|
d = PG.patterns(X, r, y, U, arc)
|
||||||
assert d["n"].sum() == 500
|
assert d["n"].sum() == 500
|
||||||
assert len(d["n"]) == len(np.unique(np.column_stack([X, r, np.nan_to_num(y, nan=-1), U, arc]), axis=0))
|
assert len(d["n"]) == len(
|
||||||
|
np.unique(np.column_stack([X, r, np.nan_to_num(y, nan=-1), U, arc]), axis=0)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def test_summed_likelihood_matches_a_direct_sum():
|
def test_summed_likelihood_matches_a_direct_sum():
|
||||||
pytest.importorskip("pymc") # optional dependency, not in the production environment
|
pytest.importorskip("pymc") # optional dependency, not in the production environment
|
||||||
"""Fails if the PyMC likelihood with g summed out differs from summing P(data | g) P(g) woman by woman."""
|
"""Fails if the PyMC likelihood with g summed out differs from summing P(data | g) P(g)\
|
||||||
|
woman by woman."""
|
||||||
X, r, y, U, arc = _referral_sample(n=400)
|
X, r, y, U, arc = _referral_sample(n=400)
|
||||||
beta, kappa, delta = np.array([-1.0, 0.9]), 0.65, np.array([-1.5, 2.5, 1.2])
|
beta, kappa, delta = np.array([-1.0, 0.9]), 0.65, np.array([-1.5, 2.5, 1.2])
|
||||||
model = PG.pymc_model(X, r, y, np.zeros(2), np.eye(2), (2, 2), U, arc, np.zeros(3), np.eye(3))
|
model = PG.pymc_model(X, r, y, np.zeros(2), np.eye(2), (2, 2), U, arc, np.zeros(3), np.eye(3))
|
||||||
@@ -107,8 +130,13 @@ def test_summed_likelihood_matches_a_direct_sum():
|
|||||||
point.update({"beta": beta, "kappa_logodds__": np.log(kappa / (1 - kappa)), "delta": delta})
|
point.update({"beta": beta, "kappa_logodds__": np.log(kappa / (1 - kappa)), "delta": delta})
|
||||||
got = model.compile_logp(vars=model.potentials)(point)
|
got = model.compile_logp(vars=model.potentials)(point)
|
||||||
p = norm.cdf(X @ beta)
|
p = norm.cdf(X @ beta)
|
||||||
pr = lambda shift: np.where(r == 1, norm.cdf(shift), norm.sf(shift))
|
|
||||||
|
def pr(shift):
|
||||||
|
return np.where(r == 1, norm.cdf(shift), norm.sf(shift))
|
||||||
|
|
||||||
py1 = np.where(r == 1, np.where(y == 1, kappa, 1 - kappa), 1.0)
|
py1 = np.where(r == 1, np.where(y == 1, kappa, 1 - kappa), 1.0)
|
||||||
py0 = np.where((r == 1) & (y == 1), 0.0, 1.0)
|
py0 = np.where((r == 1) & (y == 1), 0.0, 1.0)
|
||||||
direct = np.log(p * pr(U @ delta[:2] + delta[2] * arc) * py1 + (1 - p) * pr(U @ delta[:2]) * py0).sum()
|
direct = np.log(
|
||||||
|
p * pr(U @ delta[:2] + delta[2] * arc) * py1 + (1 - p) * pr(U @ delta[:2]) * py0
|
||||||
|
).sum()
|
||||||
assert np.isclose(got, direct)
|
assert np.isclose(got, direct)
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ from models.cacu.development_firth import FirthFamily
|
|||||||
from models.cacu.development_selection import METHODS, _candidates, _matrix, evaluate
|
from models.cacu.development_selection import METHODS, _candidates, _matrix, evaluate
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize('method', METHODS)
|
@pytest.mark.parametrize("method", METHODS)
|
||||||
def test_methods_fit_simulated_data(method):
|
def test_methods_fit_simulated_data(method):
|
||||||
X = np.array([[0], [0], [0], [1], [1], [1], [2], [2], [2], [3], [3], [3]], float)
|
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])
|
y = np.array([0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0])
|
||||||
@@ -15,28 +15,28 @@ def test_methods_fit_simulated_data(method):
|
|||||||
|
|
||||||
|
|
||||||
def test_candidates_and_imputation_use_only_training_rows():
|
def test_candidates_and_imputation_use_only_training_rows():
|
||||||
train = pd.DataFrame({'a': [0., 1., np.nan, 1.], 'copy': [0., 1., np.nan, 1.],
|
train = pd.DataFrame(
|
||||||
'absent': [np.nan] * 4})
|
{"a": [0.0, 1.0, np.nan, 1.0], "copy": [0.0, 1.0, np.nan, 1.0], "absent": [np.nan] * 4}
|
||||||
assert _candidates(train, 0.7, 5) == ['a']
|
)
|
||||||
a, b = _matrix(train, pd.DataFrame({'a': [np.nan]}), ['a'])
|
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
|
assert b[0, 0] == np.nanmedian(a[:, 0]) == 1
|
||||||
|
|
||||||
|
|
||||||
def test_nested_cv_and_loocv_record_every_attempt():
|
def test_nested_cv_and_loocv_record_every_attempt():
|
||||||
X = pd.DataFrame({'a': [0, 0, 1, 1, 0, 1, 0, 1],
|
X = pd.DataFrame({"a": [0, 0, 1, 1, 0, 1, 0, 1], "b": [0, 1, 0, 1, 1, 0, 0, 1]})
|
||||||
'b': [0, 1, 0, 1, 1, 0, 0, 1]})
|
|
||||||
y = np.array([0, 1, 0, 1, 0, 1, 1, 0])
|
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)
|
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 report["development_only"] and report["max_subsets"] == 4
|
||||||
assert set(report['validation']) == {'cv', 'loocv'}
|
assert set(report["validation"]) == {"cv", "loocv"}
|
||||||
assert {a['method'] for a in report['attempts']} == set(METHODS)
|
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("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)
|
assert all(len(report["validation"]["loocv"][m]["selected"]) == len(X) for m in METHODS)
|
||||||
|
|
||||||
|
|
||||||
def test_budget_rejects_large_loocv_before_fitting():
|
def test_budget_rejects_large_loocv_before_fitting():
|
||||||
X = pd.DataFrame({'a': [0, 1] * 10})
|
X = pd.DataFrame({"a": [0, 1] * 10})
|
||||||
with pytest.raises(ValueError, match='exceeds configured limit'):
|
with pytest.raises(ValueError, match="exceeds configured limit"):
|
||||||
evaluate(X, [0, 1] * 10, candidate_limit=2, subset_limit=2, max_fits=1)
|
evaluate(X, [0, 1] * 10, candidate_limit=2, subset_limit=2, max_fits=1)
|
||||||
|
|
||||||
|
|
||||||
@@ -44,9 +44,9 @@ def test_development_job_is_not_a_production_score():
|
|||||||
from core.models import DEVELOPMENT
|
from core.models import DEVELOPMENT
|
||||||
from models.definitions import defs
|
from models.definitions import defs
|
||||||
|
|
||||||
assert 'cacu.cin2_firth_development' in DEVELOPMENT
|
assert "cacu.cin2_firth_development" in DEVELOPMENT
|
||||||
job = defs.get_job_def('cacu_development_evaluation')
|
job = defs.get_job_def("cacu_development_evaluation")
|
||||||
assert job.name == 'cacu_development_evaluation'
|
assert job.name == "cacu_development_evaluation"
|
||||||
|
|
||||||
|
|
||||||
def test_development_job_writes_evaluation_to_isolated_mlflow(tmp_path, monkeypatch):
|
def test_development_job_writes_evaluation_to_isolated_mlflow(tmp_path, monkeypatch):
|
||||||
@@ -58,26 +58,37 @@ def test_development_job_writes_evaluation_to_isolated_mlflow(tmp_path, monkeypa
|
|||||||
from models.definitions import CacuDevelopmentEvaluation, evaluate_cacu_development
|
from models.definitions import CacuDevelopmentEvaluation, evaluate_cacu_development
|
||||||
from persistance import gold
|
from persistance import gold
|
||||||
|
|
||||||
monkeypatch.setenv('MLFLOW_TRACKING_URI', (tmp_path / 'mlruns').as_uri())
|
monkeypatch.setenv("MLFLOW_TRACKING_URI", (tmp_path / "mlruns").as_uri())
|
||||||
monkeypatch.setenv('MLFLOW_ALLOW_FILE_STORE', 'true')
|
monkeypatch.setenv("MLFLOW_ALLOW_FILE_STORE", "true")
|
||||||
monkeypatch.setattr(tracking_utils, '_tracking_uri', tracking_utils._tracking_uri)
|
monkeypatch.setattr(tracking_utils, "_tracking_uri", tracking_utils._tracking_uri)
|
||||||
mlflow.set_tracking_uri((tmp_path / 'mlruns').as_uri())
|
mlflow.set_tracking_uri((tmp_path / "mlruns").as_uri())
|
||||||
patients = [str(i) for i in range(8)]
|
patients = [str(i) for i in range(8)]
|
||||||
events = pd.DataFrame({'person_id': patients, 'date': ['2025-01-01'] * 8,
|
events = pd.DataFrame(
|
||||||
'index_date': ['2025-01-01'] * 8})
|
{"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]})
|
encoded = pd.DataFrame(
|
||||||
outcomes = pd.DataFrame({'person_id': patients, 'known': [True] * 8,
|
{
|
||||||
'y': [0, 1, 0, 1, 0, 1, 1, 0]})
|
"person_id": patients,
|
||||||
monkeypatch.setattr(gold, 'evidence_timelines', lambda *a: events)
|
"index_date": ["2025-01-01"] * 8,
|
||||||
monkeypatch.setattr(gold, 'cervical_forms', lambda *a: pd.DataFrame())
|
"factor": [0, 0, 1, 1, 0, 1, 0, 1],
|
||||||
monkeypatch.setattr(encoders, 'encode', lambda *a: encoded)
|
}
|
||||||
monkeypatch.setattr(features, 'windowed_outcome', lambda *a: outcomes)
|
)
|
||||||
|
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
|
real = development_selection.evaluate
|
||||||
monkeypatch.setattr(development_selection, 'evaluate',
|
monkeypatch.setattr(
|
||||||
lambda X, y, **kw: real(X, y, candidate_limit=1, subset_limit=1,
|
development_selection,
|
||||||
outer_folds=2, inner_folds=2, **kw))
|
"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:
|
with dg.build_op_context() as context:
|
||||||
run_id = evaluate_cacu_development(context, CacuDevelopmentEvaluation(as_of='2026-01-01'))
|
run_id = evaluate_cacu_development(context, CacuDevelopmentEvaluation(as_of="2026-01-01"))
|
||||||
artifacts = mlflow.MlflowClient().list_artifacts(run_id, 'reports')
|
artifacts = mlflow.MlflowClient().list_artifacts(run_id, "reports")
|
||||||
assert [a.path for a in artifacts] == ['reports/development_evaluation.json']
|
assert [a.path for a in artifacts] == ["reports/development_evaluation.json"]
|
||||||
|
|||||||
@@ -10,4 +10,7 @@ def test_without_an_hpv_result_she_is_not_evaluated():
|
|||||||
rows += [("negative", day, day, "hpv", "negative"), ("positive", day, day, "hpv", "positive")]
|
rows += [("negative", day, day, "hpv", "negative"), ("positive", day, day, "hpv", "positive")]
|
||||||
events = pd.DataFrame(rows, columns=["person_id", "index_date", "date", "type", "value_code"])
|
events = pd.DataFrame(rows, columns=["person_id", "index_date", "date", "type", "value_code"])
|
||||||
found = f.index_results(events, cacu.KPNC)
|
found = f.index_results(events, cacu.KPNC)
|
||||||
assert dict(zip(found["person_id"], found["hpv_positive"])) == {"negative": 0.0, "positive": 1.0}
|
assert dict(zip(found["person_id"], found["hpv_positive"], strict=False)) == {
|
||||||
|
"negative": 0.0,
|
||||||
|
"positive": 1.0,
|
||||||
|
}
|
||||||
|
|||||||
@@ -68,7 +68,9 @@ def hpv_missing_as_the_current_platform_read_it(events: pd.DataFrame) -> pd.Data
|
|||||||
near = days(prepared(events)).between(0, cacu.INDEX_SAMPLE_DAYS)
|
near = days(prepared(events)).between(0, cacu.INDEX_SAMPLE_DAYS)
|
||||||
has = events[(events["type"] == "hpv") & near]
|
has = events[(events["type"] == "hpv") & near]
|
||||||
missing = index[~index["person_id"].isin(has["person_id"])]
|
missing = index[~index["person_id"].isin(has["person_id"])]
|
||||||
assumed = missing.assign(date=missing["index_date"], type="hpv", value_code="assumed") # not positive, and not a negative visit
|
assumed = missing.assign(
|
||||||
|
date=missing["index_date"], type="hpv", value_code="assumed"
|
||||||
|
) # not positive, and not a negative visit
|
||||||
return pd.concat([events, assumed[events.columns]], ignore_index=True)
|
return pd.concat([events, assumed[events.columns]], ignore_index=True)
|
||||||
|
|
||||||
|
|
||||||
@@ -100,8 +102,9 @@ def test_predictions_match_the_current_models(name):
|
|||||||
# Older reference intervals include non-estimable covariance estimates. Preserve
|
# Older reference intervals include non-estimable covariance estimates. Preserve
|
||||||
# parity for point estimates and for intervals that remain estimable.
|
# parity for point estimates and for intervals that remain estimable.
|
||||||
comparable = both[ours].notna() if ours != "probability" else np.ones(len(both), bool)
|
comparable = both[ours].notna() if ours != "probability" else np.ones(len(both), bool)
|
||||||
np.testing.assert_allclose(both.loc[comparable, ours], both.loc[comparable, theirs],
|
np.testing.assert_allclose(
|
||||||
rtol=RTOL, atol=0)
|
both.loc[comparable, ours], both.loc[comparable, theirs], rtol=RTOL, atol=0
|
||||||
|
)
|
||||||
if spec.method != "logistic regression":
|
if spec.method != "logistic regression":
|
||||||
assert (pd.to_datetime(both["index_date"]) == pd.to_datetime(both["fecha_indice"])).all()
|
assert (pd.to_datetime(both["index_date"]) == pd.to_datetime(both["fecha_indice"])).all()
|
||||||
|
|
||||||
@@ -128,7 +131,7 @@ def test_survival_matches_the_current_model_and_publishes_patient_scenarios(monk
|
|||||||
"stack_w_lr_36m", "stack_w_lr_60m"): # fmt: skip
|
"stack_w_lr_36m", "stack_w_lr_60m"): # fmt: skip
|
||||||
assert metrics[name] == pytest.approx(current["metrics"][name], rel=RTOL), name
|
assert metrics[name] == pytest.approx(current["metrics"][name], rel=RTOL), name
|
||||||
found = spec.predict(model, events)
|
found = spec.predict(model, events)
|
||||||
assert all(set(json.loads(value)) == set(spec.features) for value in found['input_values'])
|
assert all(set(json.loads(value)) == set(spec.features) for value in found["input_values"])
|
||||||
reference = pd.read_parquet(REFERENCE / "ref" / "survival.parquet")
|
reference = pd.read_parquet(REFERENCE / "ref" / "survival.parquet")
|
||||||
both = found.merge(reference, left_on=["person_id", "horizon_years"],
|
both = found.merge(reference, left_on=["person_id", "horizon_years"],
|
||||||
right_on=["pac_id", "horizonte_anios"], validate="1:1") # fmt: skip
|
right_on=["pac_id", "horizonte_anios"], validate="1:1") # fmt: skip
|
||||||
|
|||||||
@@ -7,12 +7,16 @@ from models.cacu.specs import _rows
|
|||||||
|
|
||||||
|
|
||||||
def test_each_scored_horizon_keeps_the_inputs_of_its_patient():
|
def test_each_scored_horizon_keeps_the_inputs_of_its_patient():
|
||||||
members = pd.DataFrame([
|
members = pd.DataFrame(
|
||||||
|
[
|
||||||
{"person_id": "a", "index_date": "2026-01-01", "cytology": "NILM", "hpv": 0},
|
{"person_id": "a", "index_date": "2026-01-01", "cytology": "NILM", "hpv": 0},
|
||||||
{"person_id": "b", "index_date": "2026-02-01", "cytology": "HSIL", "hpv": 1},
|
{"person_id": "b", "index_date": "2026-02-01", "cytology": "HSIL", "hpv": 1},
|
||||||
])
|
]
|
||||||
result = _rows(members, np.array([[0.1, 0.2], [0.3, 0.4]]), (0, 5),
|
)
|
||||||
("cytology", "hpv"))
|
result = _rows(members, np.array([[0.1, 0.2], [0.3, 0.4]]), (0, 5), ("cytology", "hpv"))
|
||||||
assert [json.loads(v) for v in result.input_values] == [
|
assert [json.loads(v) for v in result.input_values] == [
|
||||||
{"cytology": "NILM", "hpv": 0}, {"cytology": "NILM", "hpv": 0},
|
{"cytology": "NILM", "hpv": 0},
|
||||||
{"cytology": "HSIL", "hpv": 1}, {"cytology": "HSIL", "hpv": 1}]
|
{"cytology": "NILM", "hpv": 0},
|
||||||
|
{"cytology": "HSIL", "hpv": 1},
|
||||||
|
{"cytology": "HSIL", "hpv": 1},
|
||||||
|
]
|
||||||
|
|||||||
@@ -10,8 +10,11 @@ def test_unestimable_covariances_never_produce_zero_width_intervals():
|
|||||||
X, Z = np.ones((1, 1)), np.empty((1, 0))
|
X, Z = np.ones((1, 1)), np.empty((1, 0))
|
||||||
good = Fit(1, 0, baseline, params, np.eye(len(params)), 0, True)
|
good = Fit(1, 0, baseline, params, np.eye(len(params)), 0, True)
|
||||||
assert np.isfinite(good.risk_with_variance(X, Z, [0, 1])[1]).all()
|
assert np.isfinite(good.risk_with_variance(X, Z, [0, 1])[1]).all()
|
||||||
for covariance in (np.full((len(params), len(params)), np.nan),
|
for covariance in (
|
||||||
-np.eye(len(params)), np.zeros((len(params), len(params)))):
|
np.full((len(params), len(params)), np.nan),
|
||||||
|
-np.eye(len(params)),
|
||||||
|
np.zeros((len(params), len(params))),
|
||||||
|
):
|
||||||
broken = Fit(1, 0, baseline, params, covariance, 0, True)
|
broken = Fit(1, 0, baseline, params, covariance, 0, True)
|
||||||
assert np.isnan(broken.risk_with_variance(X, Z, [0, 1])[1]).all()
|
assert np.isnan(broken.risk_with_variance(X, Z, [0, 1])[1]).all()
|
||||||
|
|
||||||
@@ -35,6 +38,6 @@ def test_diagnostics_count_rows_without_intervals():
|
|||||||
model.fits_ = {(): Fit(1, 0, baseline, params, -np.eye(len(params)), 0, True)}
|
model.fits_ = {(): Fit(1, 0, baseline, params, -np.eye(len(params)), 0, True)}
|
||||||
model.seen_ = {(): {}}
|
model.seen_ = {(): {}}
|
||||||
report = model.variance_diagnostics(pd.DataFrame(index=range(2)))
|
report = model.variance_diagnostics(pd.DataFrame(index=range(2)))
|
||||||
assert report['strata'][0]['rows_without_interval'] == 2
|
assert report["strata"][0]["rows_without_interval"] == 2
|
||||||
assert report['strata'][0]['negative_variances']
|
assert report["strata"][0]["negative_variances"]
|
||||||
assert report['strata'][0]['status'] == 'not_estimable'
|
assert report["strata"][0]["status"] == "not_estimable"
|
||||||
|
|||||||
Reference in New Issue
Block a user