File size: 7,652 Bytes
2e2e965
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
"""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()