megathon_travellers / predict_catboost.py
nemesis4124's picture
Add CatBoost GP01-GP08 propensity models, code and report
357e8af verified
Raw History Blame Contribute Delete
10.1 kB
"""
predict_catboost.py - reload the saved CatBoost propensity models and score customers WITHOUT retraining.
Needs (written by train_catboost.py): models/catboost_GPxx.cbm, models/manifest.json, data/features_cutoff.parquet
Run : python predict_catboost.py test split, every product in models/manifest.json
python predict_catboost.py --split all --products GP01 GP03
In code (e.g. a notebook, to try more metrics):
from predict_catboost import predict
df = predict("GP01") # customer_id, split, y, raw_score, propensity, true_prob (test customers)
from sklearn.metrics import f1_score; f1_score(df.y, df.propensity > 0.1)
Writes: data/predictions_<split>.csv
"""
import argparse, json
from pathlib import Path
import numpy as np
import pandas as pd
from catboost import CatBoostClassifier
import train_catboost as TC
DATA_DIR, MODEL_DIR = Path("data"), Path("models")
_cache = {}
def _load(name, fn):
if name not in _cache:
_cache[name] = fn()
return _cache[name]
def build_manifest():
"""train_catboost.py saves models/*.cbm + calibration.json; derive manifest.json (features, categoricals, calibration) from them."""
cal = json.loads((MODEL_DIR / "calibration.json").read_text())["products"]
man = {}
for f in sorted(MODEL_DIR.glob("catboost_GP*.cbm")):
pid = f.stem.split("_")[1]
m = CatBoostClassifier().load_model(str(f))
names = list(m.feature_names_)
man[pid] = {"model_file": f.name, "features": names,
"cat_features": [names[i] for i in m.get_cat_feature_indices()], "calibration": cal[pid]}
(MODEL_DIR / "manifest.json").write_text(json.dumps(man, indent=2))
return man
def manifest():
def load():
f = MODEL_DIR / "manifest.json"
return json.loads(f.read_text()) if f.exists() else build_manifest()
return _load("manifest", load)
def calibrate(raw, c):
"""Platt calibration saved at training time: p = sigmoid(a * logit(raw) + b)."""
r = np.clip(raw, 1e-6, 1 - 1e-6)
return 1 / (1 + np.exp(-(c["a"] * np.log(r / (1 - r)) + c["b"])))
def predict(pid, split="test"):
"""Score the ELIGIBLE customers of one product in a split ('train', 'validation', 'test' or 'all')."""
man = manifest()[pid]
model = _load(pid, lambda: CatBoostClassifier().load_model(str(MODEL_DIR / man["model_file"])))
X = _load("X", lambda: pd.read_parquet(DATA_DIR / "features_cutoff.parquet"))
lab = _load("lab", lambda: pd.read_csv(DATA_DIR / "labels_takeup.csv"))
sp = _load("sp", lambda: pd.read_csv(DATA_DIR / "splits.csv").set_index("customer_id").split)
lat = _load("lat", lambda: pd.read_csv(DATA_DIR / "labels_takeup_latent.csv", usecols=["customer_id", "product_id", "true_prob"]))
L = lab[(lab.product_id == pid) & lab.eligible.astype(str).str.lower().eq("true")].set_index("customer_id")
L = L.assign(split=sp.reindex(L.index).values)
if split != "all":
L = L[L.split == split]
missing = set(man["features"]) - set(X.columns)
assert not missing, f"features missing from features_cutoff.parquet (rebuilt with another version?): {missing}"
Xp = TC.prep(X.loc[L.index, man["features"]])
assert sorted(TC.cat_cols(Xp)) == sorted(man["cat_features"]), "categorical columns differ from training"
raw = model.predict_proba(Xp)[:, 1]
tp = lat[lat.product_id == pid].set_index("customer_id").true_prob.reindex(L.index).values
return pd.DataFrame({"customer_id": L.index, "product_id": pid, "split": L.split.values,
"y": L.take_up.astype(int).values, "raw_score": raw, "propensity": calibrate(raw, man["calibration"]),
"true_prob": tp})
def f1_stats(y, s, thr):
pred = s >= thr
tp = int((pred & (y == 1)).sum())
prec, rec = tp / max(pred.sum(), 1), tp / max(y.sum(), 1)
return dict(thr=thr, flagged=int(pred.sum()), precision=prec, recall=rec, f1=2 * prec * rec / max(prec + rec, 1e-12))
def best_f1_threshold(y, s):
"""Threshold maximising F1 (searched over score quantiles)."""
cand = np.unique(np.quantile(s, np.linspace(0.5, 0.999, 300)))
return max(cand, key=lambda t: f1_stats(y, s, t)["f1"])
def md(df, fmt="{:.3f}"):
cols = list(df.columns)
out = ["| " + " | ".join(cols) + " |", "|" + "---|" * len(cols)]
for _, r in df.iterrows():
out.append("| " + " | ".join(fmt.format(v) if isinstance(v, (float, np.floating)) else str(v) for v in r) + " |")
return "\n".join(out)
def write_report(path, split, R, F, data_dir):
mm = pd.read_csv(data_dir / "model_metrics.csv")
ci = R.assign(roc_auc=[f"{a:.3f} [{l:.3f}, {h:.3f}]" for a, l, h in zip(R.roc_auc, R.roc_auc_lo, R.roc_auc_hi)],
pr_auc=[f"{a:.3f} [{l:.3f}, {h:.3f}]" for a, l, h in zip(R.pr_auc, R.pr_auc_lo, R.pr_auc_hi)])
main_cols = ["product_id", "n", "positives", "base_rate", "roc_auc", "oracle_auc", "pr_auc", "lift_top10", "capture_top10"]
cal_cols = ["product_id", "brier", "brier_skill", "log_loss", "ece", "mean_pred"]
tune_cols = ["product_id", "cv_pr_auc", "oof_roc_auc", "oof_ece", "iterations", "minutes"] + [c for c in mm.columns if c.startswith("param_")]
txt = f"""# CatBoost green-product propensity - metrics report
Per-product CatBoost classifiers (GP01-GP08), reloaded from `models/*.cbm` by `predict_catboost.py` (no retraining) and
scored on the **{split}** split: customers never used in training or hyper-parameter tuning.
Training: `train_catboost.py` (Optuna, 20 trials x 3-fold CV maximising PR-AUC; Platt calibration on out-of-fold scores).
## Ranking quality ({split} split)
{md(ci[main_cols])}
ROC-AUC / PR-AUC in brackets: 95% bootstrap CI. `oracle_auc` is the ceiling from the hidden true probabilities.
`lift_top10` / `capture_top10`: lift and recall within the top 10% of scores.
## F1, precision, recall ({split} split)
{md(F)}
`OOF-tuned best-F1 threshold`: the calibrated-propensity cut-off that maximises F1 on dev out-of-fold scores, applied unchanged to the {split} split.
`top 10% flagged`: flag the 10% highest-scoring customers. Take-up is rare, so F1 is inherently low; treat it alongside the ranking metrics.
## Calibration and probabilistic quality
{md(R[cal_cols], "{:.4f}")}
## Training / tuning summary
{md(mm[tune_cols], "{:.4g}")}
"""
Path(path).write_text(txt, encoding="utf-8")
print(f"wrote {path}")
def main():
global DATA_DIR, MODEL_DIR
ap = argparse.ArgumentParser()
ap.add_argument("--split", default="test", choices=["train", "validation", "test", "all"])
ap.add_argument("--products", nargs="+", default=None)
ap.add_argument("--report", default=None, help="also write a markdown report of all metrics to this path")
ap.add_argument("--data-dir", default=str(DATA_DIR))
a = ap.parse_args()
DATA_DIR, MODEL_DIR = Path(a.data_dir), Path(a.data_dir).parent / "models"
products = a.products or sorted(manifest())
rng = np.random.default_rng(TC.SEED)
P = pd.concat([predict(p, a.split) for p in products], ignore_index=True)
out = DATA_DIR / f"predictions_{a.split}.csv"
P.to_csv(out, index=False)
oof = pd.read_csv(DATA_DIR / "propensity_scores.csv")
oof = oof[oof.score_source.eq("out_of_fold")]
lab = pd.read_csv(DATA_DIR / "labels_takeup.csv").dropna(subset=["take_up"]) # ineligible rows have no label
lab = lab.set_index(["customer_id", "product_id"]).take_up.astype(int)
rows, frows = [], []
for pid, g in P.groupby("product_id"):
m = TC.metrics(g.y.values, g.raw_score.values, g.propensity.values, g.true_prob.values, rng)
keys = ["n", "positives", "base_rate", "roc_auc", "roc_auc_lo", "roc_auc_hi", "oracle_auc", "pr_auc", "pr_auc_lo",
"pr_auc_hi", "lift_top10", "capture_top10", "brier", "brier_skill", "log_loss", "ece", "mean_pred"]
rows.append({"product_id": pid, **{k: m[k] for k in keys}})
# F1: threshold picked on dev out-of-fold scores (no test peeking), then applied to the split
o = oof[oof.product_id == pid]
yo = lab.reindex(list(zip(o.customer_id, o.product_id))).values
thr = best_f1_threshold(yo, o.propensity.values)
k = max(1, int(round(0.10 * len(g))))
top10 = np.sort(g.propensity.values)[::-1][k - 1]
for name, t in [("OOF-tuned best-F1 threshold", thr), ("top 10% flagged", top10)]:
frows.append({"product_id": pid, "rule": name, **f1_stats(g.y.values, g.propensity.values, t)})
R, F = pd.DataFrame(rows), pd.DataFrame(frows)
print(f"{a.split} split, models reloaded from {MODEL_DIR} (no retraining):")
print(R.to_string(index=False, float_format=lambda v: f"{v:.3f}"))
print("\nF1 / precision / recall:")
print(F.to_string(index=False, float_format=lambda v: f"{v:.3f}"))
F.to_csv(DATA_DIR / f"f1_{a.split}.csv", index=False)
print(f"wrote {out} ({len(P):,} rows)")
# checks: reloaded models reproduce the training run's saved scores exactly
assert P.propensity.between(0, 1).all() and P.propensity.notna().all()
assert not P.duplicated(["customer_id", "product_id"]).any()
ref = pd.read_csv(DATA_DIR / "propensity_scores.csv")
ref = ref[ref.score_source.eq("final_model") & ref.product_id.isin(products)]
chk = ref.merge(P, on=["customer_id", "product_id"], suffixes=("_saved", ""))
assert len(chk) == len(ref), "some test customers from the training run were not re-scored"
diff = (chk.propensity_saved - chk.propensity).abs().max()
assert diff < 1e-5, f"reloaded model disagrees with the training run (max diff {diff})"
print(f"reproduces the training run's test scores (max diff {diff:.1e}) for {len(chk):,} rows")
print("All checks passed.")
if a.report:
write_report(a.report, a.split, R, F, DATA_DIR)
if __name__ == "__main__":
main()