Guardar la deserción de cada cohorte CaCu junto al modelo entrenado
This commit is contained in:
+14
-1
@@ -1,8 +1,21 @@
|
|||||||
"""CaCu's training and scoring jobs (models.jobs) over its models and reports."""
|
"""CaCu's training and scoring jobs (models.jobs) over its models and reports."""
|
||||||
|
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
from models.cacu import reports
|
from models.cacu import reports
|
||||||
from models.cacu.specs import MODELS
|
from models.cacu.specs import MODELS
|
||||||
from models.jobs import Jobs
|
from models.jobs import Jobs
|
||||||
|
from persistance import gold
|
||||||
|
|
||||||
JOBS = Jobs("cacu", MODELS, reports.technical_validation, reports.interpretability)
|
|
||||||
|
def attrition(spec, as_of: date) -> dict | None:
|
||||||
|
"""The attrition of the spec's cohort; None when eligibility doesn't list that cohort."""
|
||||||
|
scenario = reports.COHORT_SCENARIOS.get(spec.cohort)
|
||||||
|
if scenario is None:
|
||||||
|
return None
|
||||||
|
rows = gold.cacu_eligibility_report(scenario, cutoff=as_of)
|
||||||
|
return reports.attrition(spec.cohort, rows, gold.people("cacu_events", as_of), as_of)
|
||||||
|
|
||||||
|
|
||||||
|
JOBS = Jobs("cacu", MODELS, reports.technical_validation, reports.interpretability, attrition)
|
||||||
train, score = JOBS.train, JOBS.score
|
train, score = JOBS.train, JOBS.score
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ validation, is a document the clinical team adds). Both are data the governance
|
|||||||
For the logistic regression, its coefficients and calibration by risk decile.
|
For the logistic regression, its coefficients and calibration by risk decile.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from scipy.stats import norm
|
from scipy.stats import norm
|
||||||
@@ -23,6 +25,43 @@ BOOTSTRAP = 200
|
|||||||
SEED = 20261122
|
SEED = 20261122
|
||||||
Z = norm.ppf(0.975)
|
Z = norm.ppf(0.975)
|
||||||
|
|
||||||
|
# The scenario of gold.cacu_eligibility that lists each cohort's candidates.
|
||||||
|
COHORT_SCENARIOS = {
|
||||||
|
"cacu_cohort_surveillance": "surveillance",
|
||||||
|
"cacu_cohort_post_colposcopy": "post_colposcopy",
|
||||||
|
"cacu_cohort_post_treatment": "post_treatment",
|
||||||
|
"cacu_cohort_survival": "survival",
|
||||||
|
}
|
||||||
|
# Reasons that a result still to arrive could lift.
|
||||||
|
AWAITING = {"unreported_biopsy", "no_index_result"}
|
||||||
|
|
||||||
|
|
||||||
|
def attrition(cohort: str, rows: pd.DataFrame, people: int, as_of: date) -> dict:
|
||||||
|
"""Who a cohort lost and why, up to `as_of`. `rows`: its candidates' eligibility report (one
|
||||||
|
row per candidate and reason). A candidate with several reasons counts once in `excluded`
|
||||||
|
and once in each reason; `pending` are the excluded whose every reason awaits a result."""
|
||||||
|
rows = rows[rows["index_date"].astype(str).str[:10] <= as_of.isoformat()]
|
||||||
|
key = ["person_id", "index_date", "index_sample_id"]
|
||||||
|
candidates = rows[key].drop_duplicates()
|
||||||
|
excluded = rows[rows["criterion"].notna()]
|
||||||
|
reasons = excluded.groupby(key, dropna=False)["criterion"].agg(set)
|
||||||
|
pending = int(sum(found <= AWAITING for found in reasons))
|
||||||
|
return {
|
||||||
|
"cohort": cohort,
|
||||||
|
"scenario": COHORT_SCENARIOS[cohort],
|
||||||
|
"as_of": as_of.isoformat(),
|
||||||
|
"people": people,
|
||||||
|
"without_candidate": people - int(candidates["person_id"].nunique()),
|
||||||
|
"candidates": len(candidates),
|
||||||
|
"eligible": len(candidates) - len(reasons),
|
||||||
|
"excluded": len(reasons),
|
||||||
|
"pending": pending,
|
||||||
|
"by_reason": {
|
||||||
|
str(reason): int(count)
|
||||||
|
for reason, count in excluded["criterion"].value_counts().sort_index().items()
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def technical_validation(spec: Pim | Logistic | survival.Spec, metrics: dict, data: dict) -> dict:
|
def technical_validation(spec: Pim | Logistic | survival.Spec, metrics: dict, data: dict) -> dict:
|
||||||
if isinstance(spec, survival.Spec):
|
if isinstance(spec, survival.Spec):
|
||||||
|
|||||||
@@ -35,6 +35,8 @@ class Jobs:
|
|||||||
models: dict
|
models: dict
|
||||||
technical_validation: Callable[..., dict]
|
technical_validation: Callable[..., dict]
|
||||||
interpretability: Callable[..., dict]
|
interpretability: Callable[..., dict]
|
||||||
|
# (spec, as_of) -> who the model's cohort lost, kept beside the reports; None: not kept
|
||||||
|
attrition: Callable[..., dict | None] | None = None
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def events(self) -> str:
|
def events(self) -> str:
|
||||||
@@ -72,6 +74,8 @@ class Jobs:
|
|||||||
# 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)
|
||||||
|
if self.attrition and (lost := self.attrition(spec, as_of)) is not None:
|
||||||
|
found = {**found, "attrition": lost} # not one of the reports promotion asks for
|
||||||
params = {"cohort": spec.cohort, "method": spec.method, "as_of": as_of.isoformat()}
|
params = {"cohort": spec.cohort, "method": spec.method, "as_of": as_of.isoformat()}
|
||||||
model = Predictor(spec, fitted)
|
model = Predictor(spec, fitted)
|
||||||
return registry.register(self.registered(name), model, params, metrics, found)
|
return registry.register(self.registered(name), model, params, metrics, found)
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
"""Attrition of a CaCu cohort: candidates, eligible, pending and reasons, each counted once."""
|
||||||
|
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
from models.cacu import reports
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_candidate_with_two_reasons_is_excluded_once():
|
||||||
|
"""Pins the totals, the pending rule, the people without a candidate and the as-of cut."""
|
||||||
|
rows = pd.DataFrame(
|
||||||
|
[
|
||||||
|
("eligible", "2025-01-01", None, None),
|
||||||
|
("two", "2025-01-01", None, "hysterectomy"),
|
||||||
|
("two", "2025-01-01", None, "under_18"),
|
||||||
|
("waiting", "2025-01-01", None, "no_index_result"),
|
||||||
|
("waiting_and_out", "2025-01-01", None, "no_index_result"),
|
||||||
|
("waiting_and_out", "2025-01-01", None, "prior_outcome"),
|
||||||
|
("after", "2025-07-01", None, "hysterectomy"),
|
||||||
|
],
|
||||||
|
columns=["person_id", "index_date", "index_sample_id", "criterion"],
|
||||||
|
)
|
||||||
|
|
||||||
|
found = reports.attrition("cacu_cohort_surveillance", rows, 10, date(2025, 6, 30))
|
||||||
|
|
||||||
|
assert (found["candidates"], found["eligible"], found["excluded"]) == (4, 1, 3)
|
||||||
|
assert (found["pending"], found["without_candidate"]) == (1, 6)
|
||||||
|
assert found["by_reason"] == {
|
||||||
|
"hysterectomy": 1, "no_index_result": 2, "prior_outcome": 1, "under_18": 1,
|
||||||
|
} # fmt: skip
|
||||||
Reference in New Issue
Block a user