"""Standalone predictor for the final solution selected by the SuperAgent. Usage: python predict.py The input must have the same feature columns as the standardized data produced by prepare_data.py (run `python prepare_data.py ` to build it from raw task files). Output: one row per input row with the predicted label and class probabilities. """ import importlib.util import json import sys from pathlib import Path import numpy as np import pandas as pd HERE = Path(__file__).resolve().parent def _load(member_dir: Path, name: str): spec = importlib.util.spec_from_file_location(name, member_dir / "solution.py") mod = importlib.util.module_from_spec(spec) sys.path.insert(0, str(member_dir)) spec.loader.exec_module(mod) sys.path.remove(str(member_dir)) return mod def _compat(df: pd.DataFrame) -> pd.DataFrame: """Same conversion as the harness: text columns as plain object dtype (pandas >= 3 "str" dtype).""" df = df.copy() for c in df.columns: if pd.api.types.is_string_dtype(df[c]) and not isinstance(df[c].dtype, pd.CategoricalDtype): df[c] = df[c].astype(object).where(df[c].notna(), None) return df def predict_proba(df: pd.DataFrame) -> np.ndarray: df = _compat(df) ens = json.loads((HERE / "ensemble.json").read_text(encoding="utf-8")) total, acc = 0.0, None for m in ens["members"]: d = HERE / "members" / m["id"] p = np.asarray(_load(d, "member_" + m["id"]).predict_proba(df.copy(), str(d / "artifacts")), dtype=float) if p.ndim == 1: p = np.stack([1 - p, p], 1) acc = p * m["weight"] if acc is None else acc + p * m["weight"] total += m["weight"] return acc / total def main(): src, dst = Path(sys.argv[1]), Path(sys.argv[2]) df = pd.read_pickle(src) if src.suffix == ".pkl" else pd.read_csv(src) df = df.drop(columns=["__label__"], errors="ignore") proba = predict_proba(df) classes = json.loads((HERE / "ensemble.json").read_text(encoding="utf-8"))["classes"] out = pd.DataFrame({"row": range(len(df)), "prediction": [classes[i] for i in proba.argmax(1)]}) for i, c in enumerate(classes): out[f"proba_{c}"] = proba[:, i] out.to_csv(dst, index=False) print(f"wrote {len(out)} predictions to {dst}") if __name__ == "__main__": main()