File size: 1,924 Bytes
6cbbcc4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | import json
from pathlib import Path
import cloudpickle
import numpy as np
import pandas as pd
class PacePredictor:
def __init__(self, artifact_dir="."):
self.artifact_dir = Path(artifact_dir)
self.config = json.loads((self.artifact_dir / "model_config.json").read_text(encoding="utf-8"))
with (self.artifact_dir / self.config["model_file"]).open("rb") as model_file:
self.model = cloudpickle.load(model_file)
self.feature_names = list(self.config["feature_order"])
self.threshold = float(self.config["decision_threshold"])
self.positive_class = self.config.get("positive_class", 1)
classes = list(np.asarray(self.model.classes_))
if self.positive_class not in classes:
raise ValueError("The configured positive class is missing from the fitted model.")
self.positive_index = classes.index(self.positive_class)
def predict(self, records):
if isinstance(records, pd.DataFrame):
frame = records.copy()
elif isinstance(records, dict):
frame = pd.DataFrame([records])
else:
frame = pd.DataFrame(records)
missing = [name for name in self.feature_names if name not in frame.columns]
if missing:
raise ValueError("Missing required model inputs: " + ", ".join(missing))
frame = frame.reindex(columns=self.feature_names)
probabilities = self.model.predict_proba(frame)[:, self.positive_index]
predictions = (probabilities >= self.threshold).astype(int)
return pd.DataFrame({
"positive_class_probability": probabilities,
"probability_percent": probabilities * 100.0,
"predicted_label": predictions,
"decision_threshold": self.threshold
}, index=frame.index)
def load_predictor(artifact_dir="."):
return PacePredictor(artifact_dir=artifact_dir)
|