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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""run_benchmark.py - trains and evaluates a LightGBM ensemble on the
|
| 2 |
+
portable, DERIVED/synthetic sample dataset (data/derived_sample.csv).
|
| 3 |
+
|
| 4 |
+
This mirrors the meta-learner methodology used by the production pipeline
|
| 5 |
+
(app/sport_intelligence/training.py fit_meta_learner + compute_metrics /
|
| 6 |
+
app/sport_intelligence/train_advanced.py), decoupled from any live
|
| 7 |
+
database connection. No network access, no DB credentials, no external
|
| 8 |
+
service is required: the script reads ONLY data/derived_sample.csv.
|
| 9 |
+
|
| 10 |
+
It prints the multi-class Brier score (3-class-summed definition, range
|
| 11 |
+
0.0-2.0 per sample, averaged across the evaluation set - see
|
| 12 |
+
DATA_PROVENANCE.md for the exact formula and how it relates to the
|
| 13 |
+
production headline number, 0.5783 over 97,000 real matches).
|
| 14 |
+
|
| 15 |
+
Because the shipped CSV is a synthetic sample (not the real 97k-match
|
| 16 |
+
production dataset), the Brier value printed here will differ from
|
| 17 |
+
0.5783 - this script demonstrates and verifies the METHODOLOGY, not a
|
| 18 |
+
bit-exact reproduction of the production number. See DATA_PROVENANCE.md.
|
| 19 |
+
|
| 20 |
+
IMPORTANT METHODOLOGY NOTE (documented in full in DATA_PROVENANCE.md):
|
| 21 |
+
the production headline metric (train_advanced.py / training.py
|
| 22 |
+
compute_metrics) is computed on the SAME rows used to fit the
|
| 23 |
+
meta-learner and the isotonic calibrators - it is an in-sample metric,
|
| 24 |
+
not a held-out validation score. This script reproduces that exact
|
| 25 |
+
methodology (fit and evaluate on the full shipped sample) so the number
|
| 26 |
+
it prints is directly comparable in KIND to the production number, even
|
| 27 |
+
though the underlying data differs. A held-out variant (--holdout) is
|
| 28 |
+
also provided for readers who want the more conservative, generalization
|
| 29 |
+
-aware number.
|
| 30 |
+
|
| 31 |
+
Usage:
|
| 32 |
+
python run_benchmark.py [--data data/derived_sample.csv] [--seed 42]
|
| 33 |
+
python run_benchmark.py --holdout # stricter out-of-sample variant
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
from __future__ import annotations
|
| 37 |
+
|
| 38 |
+
import argparse
|
| 39 |
+
from pathlib import Path
|
| 40 |
+
|
| 41 |
+
import numpy as np
|
| 42 |
+
import pandas as pd
|
| 43 |
+
from sklearn.isotonic import IsotonicRegression
|
| 44 |
+
from sklearn.linear_model import LogisticRegression
|
| 45 |
+
from sklearn.model_selection import train_test_split
|
| 46 |
+
|
| 47 |
+
FEATURE_COLUMNS = [
|
| 48 |
+
"dc_p_home", "dc_p_draw", "dc_p_away",
|
| 49 |
+
"elo_p_home", "elo_p_draw", "elo_p_away",
|
| 50 |
+
"imp_home", "imp_draw", "imp_away",
|
| 51 |
+
"home_form5_pts", "away_form5_pts",
|
| 52 |
+
"home_form5_goals_for", "away_form5_goals_for",
|
| 53 |
+
"home_form5_goals_against", "away_form5_goals_against",
|
| 54 |
+
"home_form5_avg_xg", "away_form5_avg_xg",
|
| 55 |
+
"home_form5_avg_xga", "away_form5_avg_xga",
|
| 56 |
+
"home_days_rest", "away_days_rest",
|
| 57 |
+
"h2h_home_win_rate_5", "h2h_avg_total_goals_5",
|
| 58 |
+
"home_lineup_rating", "away_lineup_rating",
|
| 59 |
+
]
|
| 60 |
+
|
| 61 |
+
# Documented, honest range for this DERIVED-SAMPLE reproduction (in-sample
|
| 62 |
+
# variant, mirroring the production methodology - see DATA_PROVENANCE.md).
|
| 63 |
+
# The uniform-prior baseline (33/33/33) scores 0.667; a fitted model
|
| 64 |
+
# evaluated in-sample on this synthetic dataset lands meaningfully below
|
| 65 |
+
# that. This range is NOT the production range.
|
| 66 |
+
EXPECTED_BRIER_MIN = 0.0
|
| 67 |
+
EXPECTED_BRIER_MAX = 0.66
|
| 68 |
+
|
| 69 |
+
# Held-out (--holdout) variant is stricter and may land closer to or even
|
| 70 |
+
# above the uniform baseline on a small synthetic sample - documented
|
| 71 |
+
# separately, not asserted by tests/test_reproduce.py.
|
| 72 |
+
EXPECTED_BRIER_MAX_HOLDOUT = 2.0
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def fit_meta_learner(X: np.ndarray, y: np.ndarray):
|
| 76 |
+
"""Fit a LightGBM classifier if available, else LogisticRegression.
|
| 77 |
+
|
| 78 |
+
Mirrors app/sport_intelligence/training.py fit_meta_learner (priority:
|
| 79 |
+
LightGBM > LogisticRegression fallback), decoupled from CatBoost/DB.
|
| 80 |
+
"""
|
| 81 |
+
try:
|
| 82 |
+
from lightgbm import LGBMClassifier
|
| 83 |
+
|
| 84 |
+
meta = LGBMClassifier(
|
| 85 |
+
num_leaves=31, learning_rate=0.05, n_estimators=200,
|
| 86 |
+
min_child_samples=20, random_state=42, verbosity=-1,
|
| 87 |
+
)
|
| 88 |
+
meta.fit(X, y)
|
| 89 |
+
kind = "LightGBM"
|
| 90 |
+
except ImportError:
|
| 91 |
+
meta = LogisticRegression(solver="lbfgs", max_iter=500, C=1.0, random_state=42)
|
| 92 |
+
meta.fit(X, y)
|
| 93 |
+
kind = "LogisticRegression (LightGBM not installed, fallback)"
|
| 94 |
+
|
| 95 |
+
probas = meta.predict_proba(X)
|
| 96 |
+
calibrators: list[IsotonicRegression] = []
|
| 97 |
+
for class_idx in range(3):
|
| 98 |
+
iso = IsotonicRegression(out_of_bounds="clip", y_min=0.0, y_max=1.0)
|
| 99 |
+
iso.fit(probas[:, class_idx], (y == class_idx).astype(float))
|
| 100 |
+
calibrators.append(iso)
|
| 101 |
+
|
| 102 |
+
return meta, calibrators, kind
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def compute_brier(meta, calibrators, X: np.ndarray, y: np.ndarray) -> tuple[float, float]:
|
| 106 |
+
"""Multi-class Brier score + log-loss (3-class summed, range 0.0-2.0).
|
| 107 |
+
|
| 108 |
+
Exact reimplementation of app/sport_intelligence/training.py
|
| 109 |
+
compute_metrics - see DATA_PROVENANCE.md for the formula and scale
|
| 110 |
+
discussion.
|
| 111 |
+
"""
|
| 112 |
+
raw = meta.predict_proba(X)
|
| 113 |
+
calibrated = np.zeros_like(raw)
|
| 114 |
+
for i, cal in enumerate(calibrators):
|
| 115 |
+
calibrated[:, i] = cal.predict(raw[:, i])
|
| 116 |
+
row_sums = calibrated.sum(axis=1, keepdims=True)
|
| 117 |
+
row_sums[row_sums == 0] = 1.0
|
| 118 |
+
calibrated = calibrated / row_sums
|
| 119 |
+
|
| 120 |
+
onehot = np.zeros_like(calibrated)
|
| 121 |
+
onehot[np.arange(len(y)), y] = 1.0
|
| 122 |
+
|
| 123 |
+
brier = float(np.mean(np.sum((calibrated - onehot) ** 2, axis=1)))
|
| 124 |
+
logloss = float(-np.mean(np.log(np.clip(calibrated[np.arange(len(y)), y], 1e-9, 1.0))))
|
| 125 |
+
return brier, logloss
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def run_benchmark(data_path: Path, seed: int = 42, holdout: bool = False) -> dict[str, float]:
|
| 129 |
+
df = pd.read_csv(data_path)
|
| 130 |
+
X = df[FEATURE_COLUMNS].to_numpy(dtype=np.float64)
|
| 131 |
+
y = df["outcome"].to_numpy(dtype=np.int64)
|
| 132 |
+
|
| 133 |
+
if holdout:
|
| 134 |
+
X_train, X_eval, y_train, y_eval = train_test_split(
|
| 135 |
+
X, y, test_size=0.25, random_state=seed, stratify=y,
|
| 136 |
+
)
|
| 137 |
+
else:
|
| 138 |
+
# Mirrors app/sport_intelligence/training.py train_full_pipeline:
|
| 139 |
+
# fit and evaluate on the SAME rows (in-sample headline metric,
|
| 140 |
+
# same methodology as the production 0.5783 figure).
|
| 141 |
+
X_train, X_eval, y_train, y_eval = X, X, y, y
|
| 142 |
+
|
| 143 |
+
meta, calibrators, kind = fit_meta_learner(X_train, y_train)
|
| 144 |
+
brier, logloss = compute_brier(meta, calibrators, X_eval, y_eval)
|
| 145 |
+
|
| 146 |
+
return {
|
| 147 |
+
"brier": brier,
|
| 148 |
+
"logloss": logloss,
|
| 149 |
+
"n_train": len(X_train),
|
| 150 |
+
"n_eval": len(X_eval),
|
| 151 |
+
"meta_learner": kind,
|
| 152 |
+
"mode": "holdout (25% test split)" if holdout else "in-sample (matches production methodology)",
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def _parse_args() -> argparse.Namespace:
|
| 157 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 158 |
+
parser.add_argument("--data", type=Path, default=Path("data/derived_sample.csv"))
|
| 159 |
+
parser.add_argument("--seed", type=int, default=42)
|
| 160 |
+
parser.add_argument(
|
| 161 |
+
"--holdout", action="store_true",
|
| 162 |
+
help="Use a 25%% held-out split instead of the in-sample production methodology.",
|
| 163 |
+
)
|
| 164 |
+
return parser.parse_args()
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def main() -> None:
|
| 168 |
+
args = _parse_args()
|
| 169 |
+
result = run_benchmark(args.data, seed=args.seed, holdout=args.holdout)
|
| 170 |
+
|
| 171 |
+
print("=" * 60)
|
| 172 |
+
print("Sport Intelligence Benchmark - derived-sample reproduction")
|
| 173 |
+
print("=" * 60)
|
| 174 |
+
print(f"Mode: {result['mode']}")
|
| 175 |
+
print(f"Meta-learner: {result['meta_learner']}")
|
| 176 |
+
print(f"Train rows: {result['n_train']}")
|
| 177 |
+
print(f"Eval rows: {result['n_eval']}")
|
| 178 |
+
print(f"Brier score: {result['brier']:.4f} (3-class summed, range 0.0-2.0)")
|
| 179 |
+
print(f"Log loss: {result['logloss']:.4f}")
|
| 180 |
+
print("=" * 60)
|
| 181 |
+
print(
|
| 182 |
+
"NOTE: this is a reproduction of the METHODOLOGY on a synthetic "
|
| 183 |
+
"sample, not a bit-exact reproduction of the production headline "
|
| 184 |
+
"number (Brier 0.5783 over 97,000 real matches). See "
|
| 185 |
+
"DATA_PROVENANCE.md for the full explanation."
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
if __name__ == "__main__":
|
| 190 |
+
main()
|