CaMa survival: a saved model is rehydrated with the current class before scoring
This commit is contained in:
@@ -16,7 +16,7 @@ import pandas as pd
|
||||
|
||||
from models.cama.seer_survival import survival_curves as luis
|
||||
from models.cama.survival import population
|
||||
from models.cama.survival.estimator import FEATURES, survival_settings
|
||||
from models.cama.survival.estimator import FEATURES, IntervalSurvival, survival_settings
|
||||
from models.dags.training import Scenario, dataflow
|
||||
|
||||
MIN_MEMBERS = 30
|
||||
@@ -29,6 +29,15 @@ class QueryError(ValueError):
|
||||
"""The selection cannot be answered; the message says why, in the reader's language."""
|
||||
|
||||
|
||||
def rehydrate(model) -> IntervalSurvival:
|
||||
"""The fitted model as the current `IntervalSurvival` code runs it. A version's saved model carries its class as it was
|
||||
when it was trained; its fitted state (`fitted_`, `weights_`, the codings) is what makes it that version, so that state
|
||||
is put in the current class and its methods are the code's."""
|
||||
current = IntervalSurvival.__new__(IntervalSurvival)
|
||||
current.__dict__.update(model.__dict__)
|
||||
return current
|
||||
|
||||
|
||||
def members(scenario: Scenario, frame: pd.DataFrame, lineage: dict) -> pd.DataFrame:
|
||||
"""Every member of the indexed cohort with her covariates and follow-up (the scenario's `labelled_members`)."""
|
||||
dr = dataflow(*scenario.modules, config=scenario.config)
|
||||
|
||||
@@ -478,3 +478,18 @@ def test_the_monthly_curve_passes_through_the_horizons_and_never_rises():
|
||||
|
||||
assert curve[0] == 1.0 and curve[6] == pytest.approx(0.9) and curve[12] == pytest.approx(0.8) and curve[18] == pytest.approx(0.6)
|
||||
assert (np.diff(curve) <= 1e-12).all() and curve[24] < curve[18]
|
||||
|
||||
|
||||
def test_a_saved_model_whose_class_is_older_still_scores_with_the_current_code(members_frame, production_model):
|
||||
"""Pins down: the fitted state of a model, put in an object of a class without the current methods (what loading a saved
|
||||
model from before a code change gives), scores the same as the model itself once rehydrated. Fails if the live figure
|
||||
depends on the class a version was saved with, which makes every older version unusable after a change."""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from models.cama.survival import live
|
||||
|
||||
stale = SimpleNamespace(**production_model.__dict__)
|
||||
again = live.rehydrate(stale).component_survival(members_frame[FEATURES])
|
||||
|
||||
for name, expected in production_model.component_survival(members_frame[FEATURES]).items():
|
||||
assert again[name] == pytest.approx(expected)
|
||||
|
||||
Reference in New Issue
Block a user