71 lines
2.5 KiB
Python
71 lines
2.5 KiB
Python
from collections.abc import Callable
|
|
from dataclasses import dataclass
|
|
from datetime import date
|
|
import mlflow.pyfunc
|
|
import pandas as pd
|
|
from joblib.externals.loky import get_reusable_executor
|
|
from persistance import gold, registry
|
|
|
|
|
|
class EmptyCohort(ValueError):
|
|
pass
|
|
|
|
|
|
class Predictor(mlflow.pyfunc.PythonModel):
|
|
def __init__(self, spec, fitted):
|
|
self.spec, self.fitted = (spec, fitted)
|
|
|
|
def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame:
|
|
return self.spec.predict(self.fitted, model_input)
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Jobs:
|
|
domain: str
|
|
models: dict
|
|
technical_validation: Callable[..., dict]
|
|
interpretability: Callable[..., dict]
|
|
|
|
@property
|
|
def events(self) -> str:
|
|
return f"{self.domain}_events"
|
|
|
|
def routine(self) -> list[str]:
|
|
return list(self.models)
|
|
|
|
def scored(self) -> list[str]:
|
|
return list(self.models)
|
|
|
|
def registered(self, name: str) -> str:
|
|
return f"{self.domain}.{name}"
|
|
|
|
def train(self, name: str, as_of: date | None = None) -> int:
|
|
spec, as_of = (self.models[name], as_of or date.today())
|
|
if getattr(spec, "reports", False):
|
|
events = gold.timelines(self.events, spec.cohort, as_of)
|
|
if events.empty:
|
|
raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}")
|
|
fitted, metrics, found = spec.train(events, as_of)
|
|
else:
|
|
events = gold.timelines(self.events, spec.cohort, as_of)
|
|
if events.empty:
|
|
raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}")
|
|
fitted, metrics, data = spec.train(events, as_of)
|
|
found = {
|
|
"technical_validation": self.technical_validation(spec, metrics, data),
|
|
"interpretability": self.interpretability(spec, fitted, data),
|
|
}
|
|
get_reusable_executor().shutdown(wait=True)
|
|
params = {"cohort": spec.cohort, "method": spec.method, "as_of": as_of.isoformat()}
|
|
model = Predictor(spec, fitted)
|
|
return registry.register(self.registered(name), model, params, metrics, found)
|
|
|
|
def score(self, name: str) -> int | None:
|
|
found = registry.champion(self.registered(name))
|
|
if found is None:
|
|
return None
|
|
version, model = found
|
|
risks = model.predict(gold.timelines(self.events, self.models[name].cohort))
|
|
gold.save_scores(self.registered(name), version, risks)
|
|
return version
|