sport-intelligence-benchmark / run_benchmark.py
FedCal's picture
Mirror sport-intelligence-benchmark on HF (Zenodo concept DOI 10.5281/zenodo.21602378)
2e2e965 verified
Raw
History Blame Contribute Delete
7.65 kB
"""run_benchmark.py - trains and evaluates a LightGBM ensemble on the
portable, DERIVED/synthetic sample dataset (data/derived_sample.csv).
This mirrors the meta-learner methodology used by the production pipeline
(app/sport_intelligence/training.py fit_meta_learner + compute_metrics /
app/sport_intelligence/train_advanced.py), decoupled from any live
database connection. No network access, no DB credentials, no external
service is required: the script reads ONLY data/derived_sample.csv.
It prints the multi-class Brier score (3-class-summed definition, range
0.0-2.0 per sample, averaged across the evaluation set - see
DATA_PROVENANCE.md for the exact formula and how it relates to the
production headline number, 0.5783 over 97,000 real matches).
Because the shipped CSV is a synthetic sample (not the real 97k-match
production dataset), the Brier value printed here will differ from
0.5783 - this script demonstrates and verifies the METHODOLOGY, not a
bit-exact reproduction of the production number. See DATA_PROVENANCE.md.
IMPORTANT METHODOLOGY NOTE (documented in full in DATA_PROVENANCE.md):
the production headline metric (train_advanced.py / training.py
compute_metrics) is computed on the SAME rows used to fit the
meta-learner and the isotonic calibrators - it is an in-sample metric,
not a held-out validation score. This script reproduces that exact
methodology (fit and evaluate on the full shipped sample) so the number
it prints is directly comparable in KIND to the production number, even
though the underlying data differs. A held-out variant (--holdout) is
also provided for readers who want the more conservative, generalization
-aware number.
Usage:
python run_benchmark.py [--data data/derived_sample.csv] [--seed 42]
python run_benchmark.py --holdout # stricter out-of-sample variant
"""
from __future__ import annotations
import argparse
from pathlib import Path
import numpy as np
import pandas as pd
from sklearn.isotonic import IsotonicRegression
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
FEATURE_COLUMNS = [
"dc_p_home", "dc_p_draw", "dc_p_away",
"elo_p_home", "elo_p_draw", "elo_p_away",
"imp_home", "imp_draw", "imp_away",
"home_form5_pts", "away_form5_pts",
"home_form5_goals_for", "away_form5_goals_for",
"home_form5_goals_against", "away_form5_goals_against",
"home_form5_avg_xg", "away_form5_avg_xg",
"home_form5_avg_xga", "away_form5_avg_xga",
"home_days_rest", "away_days_rest",
"h2h_home_win_rate_5", "h2h_avg_total_goals_5",
"home_lineup_rating", "away_lineup_rating",
]
# Documented, honest range for this DERIVED-SAMPLE reproduction (in-sample
# variant, mirroring the production methodology - see DATA_PROVENANCE.md).
# The uniform-prior baseline (33/33/33) scores 0.667; a fitted model
# evaluated in-sample on this synthetic dataset lands meaningfully below
# that. This range is NOT the production range.
EXPECTED_BRIER_MIN = 0.0
EXPECTED_BRIER_MAX = 0.66
# Held-out (--holdout) variant is stricter and may land closer to or even
# above the uniform baseline on a small synthetic sample - documented
# separately, not asserted by tests/test_reproduce.py.
EXPECTED_BRIER_MAX_HOLDOUT = 2.0
def fit_meta_learner(X: np.ndarray, y: np.ndarray):
"""Fit a LightGBM classifier if available, else LogisticRegression.
Mirrors app/sport_intelligence/training.py fit_meta_learner (priority:
LightGBM > LogisticRegression fallback), decoupled from CatBoost/DB.
"""
try:
from lightgbm import LGBMClassifier
meta = LGBMClassifier(
num_leaves=31, learning_rate=0.05, n_estimators=200,
min_child_samples=20, random_state=42, verbosity=-1,
)
meta.fit(X, y)
kind = "LightGBM"
except ImportError:
meta = LogisticRegression(solver="lbfgs", max_iter=500, C=1.0, random_state=42)
meta.fit(X, y)
kind = "LogisticRegression (LightGBM not installed, fallback)"
probas = meta.predict_proba(X)
calibrators: list[IsotonicRegression] = []
for class_idx in range(3):
iso = IsotonicRegression(out_of_bounds="clip", y_min=0.0, y_max=1.0)
iso.fit(probas[:, class_idx], (y == class_idx).astype(float))
calibrators.append(iso)
return meta, calibrators, kind
def compute_brier(meta, calibrators, X: np.ndarray, y: np.ndarray) -> tuple[float, float]:
"""Multi-class Brier score + log-loss (3-class summed, range 0.0-2.0).
Exact reimplementation of app/sport_intelligence/training.py
compute_metrics - see DATA_PROVENANCE.md for the formula and scale
discussion.
"""
raw = meta.predict_proba(X)
calibrated = np.zeros_like(raw)
for i, cal in enumerate(calibrators):
calibrated[:, i] = cal.predict(raw[:, i])
row_sums = calibrated.sum(axis=1, keepdims=True)
row_sums[row_sums == 0] = 1.0
calibrated = calibrated / row_sums
onehot = np.zeros_like(calibrated)
onehot[np.arange(len(y)), y] = 1.0
brier = float(np.mean(np.sum((calibrated - onehot) ** 2, axis=1)))
logloss = float(-np.mean(np.log(np.clip(calibrated[np.arange(len(y)), y], 1e-9, 1.0))))
return brier, logloss
def run_benchmark(data_path: Path, seed: int = 42, holdout: bool = False) -> dict[str, float]:
df = pd.read_csv(data_path)
X = df[FEATURE_COLUMNS].to_numpy(dtype=np.float64)
y = df["outcome"].to_numpy(dtype=np.int64)
if holdout:
X_train, X_eval, y_train, y_eval = train_test_split(
X, y, test_size=0.25, random_state=seed, stratify=y,
)
else:
# Mirrors app/sport_intelligence/training.py train_full_pipeline:
# fit and evaluate on the SAME rows (in-sample headline metric,
# same methodology as the production 0.5783 figure).
X_train, X_eval, y_train, y_eval = X, X, y, y
meta, calibrators, kind = fit_meta_learner(X_train, y_train)
brier, logloss = compute_brier(meta, calibrators, X_eval, y_eval)
return {
"brier": brier,
"logloss": logloss,
"n_train": len(X_train),
"n_eval": len(X_eval),
"meta_learner": kind,
"mode": "holdout (25% test split)" if holdout else "in-sample (matches production methodology)",
}
def _parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--data", type=Path, default=Path("data/derived_sample.csv"))
parser.add_argument("--seed", type=int, default=42)
parser.add_argument(
"--holdout", action="store_true",
help="Use a 25%% held-out split instead of the in-sample production methodology.",
)
return parser.parse_args()
def main() -> None:
args = _parse_args()
result = run_benchmark(args.data, seed=args.seed, holdout=args.holdout)
print("=" * 60)
print("Sport Intelligence Benchmark - derived-sample reproduction")
print("=" * 60)
print(f"Mode: {result['mode']}")
print(f"Meta-learner: {result['meta_learner']}")
print(f"Train rows: {result['n_train']}")
print(f"Eval rows: {result['n_eval']}")
print(f"Brier score: {result['brier']:.4f} (3-class summed, range 0.0-2.0)")
print(f"Log loss: {result['logloss']:.4f}")
print("=" * 60)
print(
"NOTE: this is a reproduction of the METHODOLOGY on a synthetic "
"sample, not a bit-exact reproduction of the production headline "
"number (Brier 0.5783 over 97,000 real matches). See "
"DATA_PROVENANCE.md for the full explanation."
)
if __name__ == "__main__":
main()