201 lines
9.5 KiB
Python
201 lines
9.5 KiB
Python
"""The CaCu models: each is a spec (what it reads and how it is set) over one of two methods,
|
|
the prevalence-incidence mixture or a logistic regression. Training and scoring read the
|
|
patient timelines of the spec's cohort (see features)."""
|
|
|
|
from dataclasses import dataclass, field
|
|
from typing import Literal
|
|
|
|
import numpy as np
|
|
import pandas as pd
|
|
from sklearn.linear_model import LogisticRegression
|
|
from sklearn.metrics import brier_score_loss, roc_auc_score
|
|
from sklearn.pipeline import Pipeline
|
|
from sklearn.preprocessing import OneHotEncoder
|
|
|
|
from core import cacu
|
|
from models.cacu import features as f
|
|
from models.cacu.pim import Mixture
|
|
from models.survival import Spec, age_group
|
|
|
|
HORIZONS = (0.0, 1.0, 2.0, 3.0, 4.0, 5.0)
|
|
TRAIN_FRACTION = 0.7
|
|
OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high"]
|
|
|
|
|
|
def _rows(members: pd.DataFrame, risks: np.ndarray, horizons) -> pd.DataFrame:
|
|
"""One row per patient and horizon; patients the model can't score are left out."""
|
|
h = len(horizons)
|
|
scored = ~np.isnan(risks[:, :h]).any(axis=1)
|
|
members, risks = members[scored], risks[scored]
|
|
n = len(members)
|
|
frame = pd.DataFrame({
|
|
"person_id": np.repeat(members["person_id"].to_numpy(), h),
|
|
"index_date": np.repeat(pd.to_datetime(members["index_date"]).dt.date.to_numpy(), h),
|
|
"horizon_years": np.tile(np.asarray(horizons, dtype=float), n),
|
|
"probability": risks[:, :h].ravel(),
|
|
}) # fmt: skip
|
|
if risks.shape[1] == 3 * h:
|
|
frame["ci_low"], frame["ci_high"] = risks[:, h : 2 * h].ravel(), risks[:, 2 * h :].ravel()
|
|
else:
|
|
frame["ci_low"] = frame["ci_high"] = np.nan
|
|
return frame[OUTPUT]
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Pim:
|
|
"""Cumulative risk of the outcome at the index and by each horizon (PIMixture)."""
|
|
|
|
name: str
|
|
cohort: str
|
|
grades: list[str]
|
|
cytology: dict[str, list[str]]
|
|
strata: tuple[str, ...]
|
|
incidence_features: tuple[str, ...]
|
|
history: dict | None = None # a feature from before the index (the referral grade)
|
|
predict_at: Literal["index", "last_screening_cytology"] = "index"
|
|
horizons: tuple[float, ...] = HORIZONS
|
|
method: str = field(default="prevalence-incidence mixture", init=False)
|
|
|
|
@property
|
|
def features(self) -> list[str]:
|
|
return ["cytology", "hpv_positive"] + ([self.history["feature"]] if self.history else [])
|
|
|
|
def _history(self) -> dict | None:
|
|
return self.history and {**self.history, "cytology": self.cytology}
|
|
|
|
def train(self, events: pd.DataFrame, as_of=None) -> tuple[Mixture, dict, dict]:
|
|
"""The fitted mixture, its metrics on the held-out latest patients, and the coded
|
|
members it learned from (for the reports)."""
|
|
events = f.prepared(events)
|
|
coded = f.interval_coded(events, self.grades, self.cytology, self._history())
|
|
train, test = f.split(coded, TRAIN_FRACTION)
|
|
levels = {"cytology": list(self.cytology)}
|
|
if self.history:
|
|
levels[self.history["feature"]] = list(self.history["levels"])
|
|
mixture = Mixture(self.horizons, self.incidence_features, self.strata, levels)
|
|
mixture.fit(train[self.features], train[["c", "l", "r"]])
|
|
return mixture, self.metrics(mixture, train, test), {"coded": coded}
|
|
|
|
def metrics(self, mixture: Mixture, train, test) -> dict:
|
|
found = {
|
|
"n_train": len(train),
|
|
"n_test": len(test),
|
|
"neg_loglik": mixture.neg_loglik_,
|
|
"converged": float(mixture.converged_),
|
|
}
|
|
risks = mixture.predict(test[self.features])
|
|
for column, horizon in enumerate(self.horizons):
|
|
case = (test["c"] == 1) | ((test["c"] != 1) & (test["r"] <= horizon))
|
|
free = (test["c"] == 0) & (test["l"] >= horizon) & ~case
|
|
status = np.where(case, 1.0, np.where(free, 0.0, np.nan))
|
|
known = ~np.isnan(status) & ~np.isnan(risks[:, column])
|
|
y, p, tag = status[known], risks[known, column], f"{horizon:g}y"
|
|
found[f"n_known_{tag}"] = int(known.sum())
|
|
if known.any():
|
|
found[f"observed_{tag}"] = float(y.mean())
|
|
found[f"expected_{tag}"] = float(p.mean())
|
|
found[f"brier_{tag}"] = float(np.mean((p - y) ** 2))
|
|
if len(np.unique(y)) == 2:
|
|
found[f"auc_{tag}"] = float(roc_auc_score(y, p))
|
|
return found
|
|
|
|
def predict(self, mixture: Mixture, events: pd.DataFrame) -> pd.DataFrame:
|
|
events = f.prepared(events)
|
|
if self.predict_at == "last_screening_cytology":
|
|
chosen = f.last_screening_cytology(events)
|
|
events = events[events["person_id"].isin(chosen.index)]
|
|
events = events.assign(index_date=events["person_id"].map(chosen))
|
|
members = f.index_results(events, self.cytology, self._history())
|
|
members = members.sort_values("person_id", kind="stable").reset_index(drop=True)
|
|
return _rows(members, mixture.predict(members[self.features]), self.horizons)
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Logistic:
|
|
"""Probability of the outcome within one year of the index sample."""
|
|
|
|
name: str
|
|
cohort: str
|
|
grades: list[str]
|
|
predictors: tuple[str, ...] = ("bethesda", "hpv", "hpv_16_18")
|
|
years: float = 1.0
|
|
method: str = field(default="logistic regression", init=False)
|
|
|
|
def train(self, events: pd.DataFrame, follow_up_end) -> tuple[Pipeline, dict, dict]:
|
|
"""Patients whose outcome is unknown (followed less than a year, no outcome) are left
|
|
out. Follow-up ends at `follow_up_end`: the date the data are known to."""
|
|
events = f.prepared(events)
|
|
found = f.index_sample(events, list(self.predictors))
|
|
outcome = f.windowed_outcome(events, self.grades, self.years,
|
|
pd.Timestamp(follow_up_end)) # fmt: skip
|
|
labelled = found.merge(outcome, on="person_id")
|
|
labelled = labelled[labelled["known"]].reset_index(drop=True)
|
|
train, test = f.split(labelled, TRAIN_FRACTION)
|
|
X = list(self.predictors)
|
|
model = Pipeline([("encode", OneHotEncoder(handle_unknown="ignore")),
|
|
("classify", LogisticRegression(max_iter=1000))]) # fmt: skip
|
|
model.fit(train[X], train["y"])
|
|
p = model.predict_proba(test[X])[:, 1]
|
|
metrics = {
|
|
"n_train": len(train),
|
|
"n_test": len(test),
|
|
"auc": float(roc_auc_score(test["y"], p)),
|
|
"brier": float(brier_score_loss(test["y"], p)),
|
|
"positive_rate_train": float(train["y"].mean()),
|
|
"positive_rate_test": float(test["y"].mean()),
|
|
"mean_probability_test": float(p.mean()),
|
|
}
|
|
return model, metrics, {"labelled": labelled, "test": test.assign(p=p)}
|
|
|
|
def predict(self, model: Pipeline, events: pd.DataFrame) -> pd.DataFrame:
|
|
members = f.index_sample(f.prepared(events), list(self.predictors))
|
|
members = members.sort_values("person_id", kind="stable").reset_index(drop=True)
|
|
p = model.predict_proba(members[list(self.predictors)])[:, 1]
|
|
return _rows(members, p[:, None], (self.years,))
|
|
|
|
|
|
def survival_covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
|
|
"""Each member's most recent observations up to her index (that day included): her age
|
|
group, the KPNC category of her latest cytology result and her latest HPV result."""
|
|
found = pd.DataFrame(index=members.index)
|
|
found["age_group"] = age_group(events, members, (35, 45, 55))
|
|
prior = events[events["date"] <= events["index_date"]]
|
|
names = list(cacu.KPNC)
|
|
severity = {code: rank for rank, codes in enumerate(cacu.KPNC.values()) for code in codes}
|
|
results = prior[(prior["type"] == "bethesda") & prior["value_code"].notna()]
|
|
latest = results[results["date"] == results.groupby("person_id")["date"].transform("max")]
|
|
ranks = latest["value_code"].map(severity).groupby(latest["person_id"]).max()
|
|
found["cytology"] = ranks.map(lambda r: None if pd.isna(r) else names[int(r)])
|
|
hpv = prior[(prior["type"] == "hpv") & prior["value_code"].notna()]
|
|
hpv = hpv.sort_values(["date", "source_id"])
|
|
found["hpv"] = hpv.groupby("person_id")["value_code"].last()
|
|
return found.astype(object)
|
|
|
|
|
|
_REFERRAL = {
|
|
"feature": "referral_grade", "lookback_days": cacu.REFERRAL_LOOKBACK_DAYS,
|
|
"levels": ["low", "high"], "low": ["ASC-US/LSIL"], "low_if_hpv_positive": ["NILM"],
|
|
"high": ["High Grade"],
|
|
} # fmt: skip
|
|
|
|
MODELS = {
|
|
m.name: m
|
|
for m in [
|
|
Pim("cin2_pim", "cacu_cohort_surveillance", cacu.CIN2_PLUS, cacu.KPNC,
|
|
strata=("hpv_positive",), incidence_features=("cytology",),
|
|
predict_at="last_screening_cytology"),
|
|
Pim("cancer_pim", "cacu_cohort_surveillance", cacu.CANCER, cacu.KPNC,
|
|
strata=("hpv_positive",), incidence_features=("cytology",),
|
|
predict_at="last_screening_cytology"),
|
|
Pim("cin2_pim_post_colposcopy", "cacu_cohort_post_colposcopy", cacu.CIN2_PLUS,
|
|
cacu.KPNC_3, strata=("referral_grade",),
|
|
incidence_features=("cytology", "hpv_positive"), history=_REFERRAL),
|
|
Pim("cin2_pim_post_treatment", "cacu_cohort_post_treatment", cacu.CIN2_PLUS,
|
|
cacu.KPNC_3, strata=(), incidence_features=("cytology", "hpv_positive")),
|
|
Logistic("cin2_logistic", "cacu_cohort_surveillance", cacu.CIN2_PLUS),
|
|
Spec("survival", "cacu_cohort_survival", ("age_group", "cytology", "hpv"),
|
|
survival_covariates, borders=(0, 12, 36, 60), cap_months=60,
|
|
interval_level=0.95),
|
|
]
|
|
} # fmt: skip
|