CaCu models: prevalence-incidence mixture and logistic, equal to the current predictions
This commit is contained in:
@@ -0,0 +1,265 @@
|
||||
"""Prevalence-incidence mixture for interval-censored outcomes (PIMixture, Cheung et al.).
|
||||
|
||||
A patient either has the outcome at the index visit (prevalence, a logistic model) or may
|
||||
develop it later (incidence, a proportional-hazards model with an I-spline baseline). Each
|
||||
patient is coded `c` = 1 (prevalent), 0 (known free at the index), or UNKNOWN, with the
|
||||
interval (l, r] in years where an incident outcome happened. No library fits this model, so
|
||||
the likelihood is written here; everything else is scipy.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from scipy.interpolate import BSpline
|
||||
from scipy.optimize import minimize
|
||||
from scipy.special import expit
|
||||
from scipy.stats import norm
|
||||
from sklearn.base import BaseEstimator
|
||||
|
||||
UNKNOWN = -999
|
||||
TINY = 1e-12 # floor inside every log
|
||||
FROZEN = 15.0 # a parameter this far out sits on the boundary: fixed, not estimated
|
||||
HESSIAN_STEP = 1e-4
|
||||
|
||||
|
||||
def ispline_basis(t, degree: int, knots) -> np.ndarray:
|
||||
"""Integrated B-splines: monotone from 0 at the first knot to 1 at the last."""
|
||||
t, knots = np.asarray(t, dtype=float), np.asarray(knots, dtype=float)
|
||||
full = np.r_[np.repeat(knots[0], degree + 1), knots[1:-1], np.repeat(knots[-1], degree + 1)]
|
||||
inside = np.clip(np.nan_to_num(t, posinf=knots[-1]), knots[0], knots[-1])
|
||||
bsplines = BSpline.design_matrix(inside, full, degree, extrapolate=False).toarray()
|
||||
basis = np.cumsum(bsplines[:, ::-1], axis=1)[:, ::-1][:, 1:]
|
||||
basis[t >= knots[-1]] = 1.0
|
||||
basis[t <= knots[0]] = 0.0
|
||||
return basis
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ISpline:
|
||||
"""Baseline cumulative hazard: I-splines with non-negative (exp) coefficients."""
|
||||
|
||||
knots: tuple[float, ...]
|
||||
degree: int
|
||||
|
||||
@classmethod
|
||||
def at_quantiles(cls, l, r, n_knots: int, degree: int) -> "ISpline":
|
||||
times = np.unique(np.r_[l, r[np.isfinite(r)]])
|
||||
return cls(tuple(float(k) for k in np.quantile(times, np.linspace(0, 1, n_knots))), degree)
|
||||
|
||||
@property
|
||||
def n_params(self) -> int:
|
||||
return len(self.knots) + self.degree - 2
|
||||
|
||||
def cumulative_hazard(self, t, params) -> np.ndarray:
|
||||
return ispline_basis(t, self.degree, self.knots) @ np.exp(params)
|
||||
|
||||
def start(self, c, l, r) -> np.ndarray:
|
||||
"""Every coefficient equal, so the hazard is the crude event rate."""
|
||||
at_risk, finite = c != 1, np.isfinite(r)
|
||||
exposure = np.where(finite, (l + r) / 2, l)[at_risk].sum()
|
||||
events = (at_risk & finite & (r > 0)).sum()
|
||||
# exp(-log(...)), not a plain division: on a flat likelihood BFGS follows the start's
|
||||
# last bit, and this is the start the current models were fitted from.
|
||||
rate = np.exp(-np.log(max(exposure, 1e-6) / (events + 0.5)))
|
||||
return np.full(self.n_params, np.log(max(rate * self.knots[-1], 1e-6) / self.n_params))
|
||||
|
||||
|
||||
def survival(t, baseline: ISpline, baseline_params, beta, Z) -> np.ndarray:
|
||||
t = np.asarray(t, dtype=float)
|
||||
with np.errstate(over="ignore", invalid="ignore"):
|
||||
found = np.exp(-baseline.cumulative_hazard(t, baseline_params) * np.exp(Z @ beta))
|
||||
found = np.where(t <= 0, 1.0, found)
|
||||
return np.where(np.isinf(t), 0.0, found)
|
||||
|
||||
|
||||
def neg_loglik(params, c, l, r, X, Z, baseline: ISpline, w) -> float:
|
||||
n_x, n_z = X.shape[1], Z.shape[1]
|
||||
theta, beta, rest = params[:n_x], params[n_x : n_x + n_z], params[n_x + n_z :]
|
||||
pi = expit(X @ theta)
|
||||
interval = survival(l, baseline, rest, beta, Z) - survival(r, baseline, rest, beta, Z)
|
||||
interval = np.maximum(interval, TINY)
|
||||
row = np.zeros(len(c))
|
||||
prevalent, free, unknown = c == 1, c == 0, c == UNKNOWN
|
||||
row[prevalent] = np.log(pi[prevalent] + TINY)
|
||||
row[free] = np.log(1 - pi[free] + TINY) + np.log(interval[free])
|
||||
row[unknown] = np.log(pi[unknown] + (1 - pi[unknown]) * interval[unknown] + TINY)
|
||||
return -np.sum(w * row)
|
||||
|
||||
|
||||
def hessian(f, x, step: float = HESSIAN_STEP) -> np.ndarray:
|
||||
"""Central-difference Hessian of f at x."""
|
||||
p = len(x)
|
||||
out = np.zeros((p, p))
|
||||
for i in range(p):
|
||||
for j in range(i, p):
|
||||
ei, ej = np.zeros(p), np.zeros(p)
|
||||
ei[i], ej[j] = step, step
|
||||
value = (f(x + ei + ej) - f(x + ei - ej) - f(x - ei + ej) + f(x - ei - ej)) / (
|
||||
4 * step * step
|
||||
)
|
||||
out[i, j] = out[j, i] = value
|
||||
return out
|
||||
|
||||
|
||||
def _ridge_logistic(c, X, ridge: float = 1e-3) -> np.ndarray:
|
||||
"""Prevalence coefficients from the patients whose index status is known."""
|
||||
known = c != UNKNOWN
|
||||
if not known.any():
|
||||
return np.zeros(X.shape[1])
|
||||
y, Xk = (c[known] == 1).astype(float), X[known]
|
||||
|
||||
def loss(theta):
|
||||
eta = Xk @ theta
|
||||
return np.sum(np.logaddexp(0, eta) - y * eta) + ridge * theta @ theta
|
||||
|
||||
return minimize(loss, np.zeros(X.shape[1]), method="BFGS").x
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Fit:
|
||||
n_x: int
|
||||
n_z: int
|
||||
baseline: ISpline
|
||||
params: np.ndarray
|
||||
covariance: np.ndarray # NaN where a parameter is frozen
|
||||
neg_loglik: float
|
||||
converged: bool
|
||||
|
||||
def risk(self, X, Z, years, params=None) -> np.ndarray:
|
||||
"""Cumulative risk at each horizon: prevalent, or incident by then."""
|
||||
p = self.params if params is None else params
|
||||
theta, beta, rest = (
|
||||
p[: self.n_x],
|
||||
p[self.n_x : self.n_x + self.n_z],
|
||||
p[self.n_x + self.n_z :],
|
||||
)
|
||||
pi = expit(X @ theta)
|
||||
return np.column_stack([
|
||||
pi + (1 - pi) * (1 - survival(np.full(len(X), float(t)), self.baseline, rest, beta, Z))
|
||||
for t in years
|
||||
]) # fmt: skip
|
||||
|
||||
def risk_with_variance(self, X, Z, years) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Risk and its delta-method variance (central-difference gradient)."""
|
||||
gradient = np.empty((len(self.params), len(X), len(years)))
|
||||
for k, value in enumerate(self.params):
|
||||
step = 1e-5 * max(1.0, abs(value))
|
||||
up, down = self.params.copy(), self.params.copy()
|
||||
up[k] += step
|
||||
down[k] -= step
|
||||
gradient[k] = (self.risk(X, Z, years, up) - self.risk(X, Z, years, down)) / (2 * step)
|
||||
covariance = np.nan_to_num(self.covariance, nan=0.0)
|
||||
variance = np.einsum("kij,kl,lij->ij", gradient, covariance, gradient)
|
||||
return self.risk(X, Z, years), np.maximum(variance, 0.0)
|
||||
|
||||
|
||||
def fit(c, l, r, X, Z, baseline: ISpline, w) -> Fit:
|
||||
"""Maximum likelihood from two starts (BFGS); covariance from the numerical Hessian."""
|
||||
n_x, n_z = X.shape[1], Z.shape[1]
|
||||
start = baseline.start(c, l, r)
|
||||
starts = [np.r_[_ridge_logistic(c, X), np.zeros(n_z), start], np.r_[np.zeros(n_x + n_z), start]]
|
||||
args = (c, l, r, X, Z, baseline, w)
|
||||
results = [minimize(neg_loglik, s, args=args, method="BFGS") for s in starts]
|
||||
best = min(results, key=lambda res: res.fun if np.isfinite(res.fun) else np.inf)
|
||||
free = np.abs(best.x) < FROZEN
|
||||
covariance = np.full((len(best.x), len(best.x)), np.nan)
|
||||
h = hessian(lambda p: neg_loglik(p, *args), best.x)
|
||||
try:
|
||||
covariance[np.ix_(free, free)] = np.linalg.inv(h[np.ix_(free, free)])
|
||||
except np.linalg.LinAlgError:
|
||||
pass
|
||||
converged = bool(np.max(np.abs(best.jac[free]), initial=0.0) < 1e-3)
|
||||
return Fit(n_x, n_z, baseline, best.x, covariance, float(best.fun), converged)
|
||||
|
||||
|
||||
class Mixture(BaseEstimator):
|
||||
"""One mixture per stratum. Categorical features get one dummy per level after the first
|
||||
level seen in the stratum (`levels` gives their order); rows at a level the stratum never
|
||||
saw are left out. Every feature enters prevalence; `incidence_features` also incidence."""
|
||||
|
||||
def __init__(self, horizons_years, incidence_features, strata, levels, knots=3, degree=4,
|
||||
interval_level=0.95): # fmt: skip
|
||||
self.horizons_years = horizons_years
|
||||
self.incidence_features = incidence_features
|
||||
self.strata = strata
|
||||
self.levels = levels
|
||||
self.knots = knots
|
||||
self.degree = degree
|
||||
self.interval_level = interval_level
|
||||
|
||||
def _seen(self, X: pd.DataFrame) -> dict:
|
||||
return {
|
||||
f: [v for v in values if (X[f] == v).any()]
|
||||
for f, values in self.levels.items()
|
||||
if f in X.columns and f not in self.strata
|
||||
}
|
||||
|
||||
def _placed(self, X: pd.DataFrame, seen: dict) -> np.ndarray:
|
||||
if not seen:
|
||||
return np.ones(len(X), dtype=bool)
|
||||
return np.all([X[f].isin(values).to_numpy() for f, values in seen.items()], axis=0)
|
||||
|
||||
def _columns(self, X: pd.DataFrame, features, seen: dict) -> np.ndarray:
|
||||
columns = []
|
||||
for f in features:
|
||||
if f in self.strata:
|
||||
continue
|
||||
if f in seen:
|
||||
columns += [(X[f] == v).to_numpy(dtype=float) for v in seen[f][1:]]
|
||||
else:
|
||||
columns.append(X[f].to_numpy(dtype=float))
|
||||
return np.column_stack(columns) if columns else np.zeros((len(X), 0))
|
||||
|
||||
def _design(self, X: pd.DataFrame, seen: dict) -> tuple[np.ndarray, np.ndarray]:
|
||||
prevalence = np.column_stack([np.ones(len(X)), self._columns(X, X.columns, seen)])
|
||||
return prevalence, self._columns(X, self.incidence_features, seen)
|
||||
|
||||
def _groups(self, X: pd.DataFrame):
|
||||
if not self.strata:
|
||||
return [((), np.arange(len(X)))]
|
||||
groups = X.groupby(list(self.strata), sort=True).indices.items()
|
||||
return [(key if isinstance(key, tuple) else (key,), rows) for key, rows in groups]
|
||||
|
||||
def fit(self, X: pd.DataFrame, y: pd.DataFrame):
|
||||
"""X: the features; y: c, l, r. Identical rows are fitted once, weighted."""
|
||||
rows = pd.concat([X.reset_index(drop=True), y[["c", "l", "r"]].reset_index(drop=True)],
|
||||
axis=1).assign(w=1.0) # fmt: skip
|
||||
self.fits_, self.seen_ = {}, {}
|
||||
for key, index in self._groups(X):
|
||||
group = rows.iloc[index]
|
||||
seen = self._seen(group)
|
||||
group = group[self._placed(group, seen)]
|
||||
group = group.groupby([*X.columns, "c", "l", "r"], as_index=False)["w"].sum()
|
||||
prevalence, incidence = self._design(group[X.columns], seen)
|
||||
c, l, r = (group[k].to_numpy(dtype=float) for k in ("c", "l", "r"))
|
||||
baseline = ISpline.at_quantiles(l, r, self.knots, self.degree)
|
||||
self.seen_[key] = seen
|
||||
self.fits_[key] = fit(c, l, r, prevalence, incidence, baseline, group["w"].to_numpy())
|
||||
self.neg_loglik_ = float(sum(f.neg_loglik for f in self.fits_.values()))
|
||||
self.converged_ = all(f.converged for f in self.fits_.values())
|
||||
return self
|
||||
|
||||
def predict(self, X: pd.DataFrame) -> np.ndarray:
|
||||
"""Per row and horizon: (risk, low, high) as three blocks of columns; NaN where the
|
||||
row's stratum or level was never seen."""
|
||||
h = len(self.horizons_years)
|
||||
out = np.full((len(X), 3 * h), np.nan)
|
||||
z = norm.ppf(0.5 + self.interval_level / 2)
|
||||
for key, index in self._groups(X):
|
||||
if key not in self.fits_:
|
||||
continue
|
||||
members = X.iloc[index]
|
||||
placed = self._placed(members, self.seen_[key])
|
||||
prevalence, incidence = self._design(members[placed], self.seen_[key])
|
||||
design = np.column_stack([prevalence, incidence])
|
||||
unique, inverse = np.unique(design, axis=0, return_inverse=True)
|
||||
n_x = prevalence.shape[1]
|
||||
point, variance = self.fits_[key].risk_with_variance(
|
||||
unique[:, :n_x], unique[:, n_x:], self.horizons_years
|
||||
)
|
||||
relative = np.where(point > 0, np.sqrt(variance) / np.maximum(point, 1e-300), 0.0)
|
||||
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
|
||||
out[index[placed]] = band[inverse.ravel()]
|
||||
return out
|
||||
Reference in New Issue
Block a user