Spaces:
Sleeping
Sleeping
Update SQL
Browse files
SQL
CHANGED
|
@@ -1,523 +1,29 @@
|
|
| 1 |
-
|
| 2 |
|
| 3 |
-
|
|
|
|
| 4 |
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
- TB2P is excluded from 12.5C (CONDITIONAL PASS — deferred to future batch).
|
| 8 |
-
- Hit model is excluded due to PA-to-game-level anchor mismatch and 100%-positive delta distribution.
|
| 9 |
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
|
|
|
| 16 |
|
| 17 |
-
|
|
|
|
|
|
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
- Do NOT modify existing hit_prob, hr_prob, tb2p_prob outputs
|
| 22 |
-
- No production blending or decision impact
|
| 23 |
-
- Shadow fields added to output dict only — invisible to downstream unless explicitly consumed
|
| 24 |
-
- Load HR model only; TB2P deferred
|
| 25 |
|
| 26 |
-
|
|
|
|
| 27 |
|
| 28 |
-
|
| 29 |
-
│ File │ Change │
|
| 30 |
-
├──────────────────────────────────┼────────────────────────────────────────────────────────────────────────────────────────────────────────┤
|
| 31 |
-
│ config/settings.py │ Add ENABLE_XGB_SHADOW flag │
|
| 32 |
-
├──────────────────────────────────┼────────────────────────────────────────────────────────────────────────────────────────────────────────┤
|
| 33 |
-
│ models/xgb_shadow.py │ NEW — HR model loading + inference function │
|
| 34 |
-
├──────────────────────────────────┼────────────────────────────────────────────────────────────────────────────────────────────────────────┤
|
| 35 |
-
│ models/live_fair_simulator_v3.py │ Import shadow module, call after all B9/10/11 adjustments + final hr_prob, add 3 fields to output dict │
|
| 36 |
-
└──────────────────────────────────┴─────────────────��──────────────────────────────────────────────────────────────────────────────────────┘
|
| 37 |
|
| 38 |
-
-
|
| 39 |
-
Step 1 — config/settings.py change
|
| 40 |
-
|
| 41 |
-
Add after line 15 (ENABLE_ENTERPRISE_PROVIDER = False):
|
| 42 |
-
|
| 43 |
-
# Batch 12.5C: XGBoost shadow inference
|
| 44 |
-
# Set ENABLE_XGB_SHADOW=false in env to disable (default: enabled)
|
| 45 |
-
ENABLE_XGB_SHADOW = os.getenv("ENABLE_XGB_SHADOW", "true").lower() == "true"
|
| 46 |
-
|
| 47 |
-
---
|
| 48 |
-
Step 2 — models/xgb_shadow.py (new file)
|
| 49 |
-
|
| 50 |
-
Complete module: lazy HR model loading, strict feature validation, numeric stability, inference.
|
| 51 |
-
|
| 52 |
-
Module header + lazy registry
|
| 53 |
-
|
| 54 |
-
"""
|
| 55 |
-
models/xgb_shadow.py
|
| 56 |
-
|
| 57 |
-
Batch 12.5C: XGBoost shadow inference layer.
|
| 58 |
-
|
| 59 |
-
Loads pre-trained HR delta model (from models/artifacts/xgb_hr_v1.json)
|
| 60 |
-
and computes shadow outputs for each simulated batter row.
|
| 61 |
-
|
| 62 |
-
SHADOW ONLY: outputs are informational. Do not use for production
|
| 63 |
-
probability blending until 12.5D review.
|
| 64 |
-
|
| 65 |
-
Models included: xgb_hr_v1.json
|
| 66 |
-
Models excluded: xgb_hit_v1.json (anchor mismatch — see 12.5B audit)
|
| 67 |
-
xgb_tb2p_v1.json (CONDITIONAL PASS — deferred to future batch)
|
| 68 |
-
"""
|
| 69 |
-
|
| 70 |
-
import logging
|
| 71 |
-
import os
|
| 72 |
-
from typing import Any
|
| 73 |
-
|
| 74 |
-
import numpy as np
|
| 75 |
-
import pandas as pd
|
| 76 |
-
|
| 77 |
-
logger = logging.getLogger(__name__)
|
| 78 |
-
|
| 79 |
-
# ---------------------------------------------------------------------------
|
| 80 |
-
# Lazy model registry (HR only)
|
| 81 |
-
# ---------------------------------------------------------------------------
|
| 82 |
-
|
| 83 |
-
_MODEL = None # XGBRegressor instance
|
| 84 |
-
_FEATURE_NAMES = None # list[str] — from booster.feature_names
|
| 85 |
-
_LOAD_ATTEMPTED = False
|
| 86 |
-
_LOAD_OK = False
|
| 87 |
-
_ARTIFACTS_DIR = os.path.join(os.path.dirname(__file__), "artifacts")
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
def _maybe_load_model() -> bool:
|
| 91 |
-
"""Lazy-load HR model on first call. Returns True if successful."""
|
| 92 |
-
global _MODEL, _FEATURE_NAMES, _LOAD_ATTEMPTED, _LOAD_OK
|
| 93 |
-
if _LOAD_ATTEMPTED:
|
| 94 |
-
return _LOAD_OK
|
| 95 |
-
_LOAD_ATTEMPTED = True
|
| 96 |
-
try:
|
| 97 |
-
import xgboost as xgb
|
| 98 |
-
path = os.path.join(_ARTIFACTS_DIR, "xgb_hr_v1.json")
|
| 99 |
-
if not os.path.exists(path):
|
| 100 |
-
raise FileNotFoundError(f"Missing artifact: {path}")
|
| 101 |
-
model = xgb.XGBRegressor()
|
| 102 |
-
model.load_model(path)
|
| 103 |
-
_MODEL = model
|
| 104 |
-
booster = model.get_booster()
|
| 105 |
-
_FEATURE_NAMES = booster.feature_names or []
|
| 106 |
-
_LOAD_OK = True
|
| 107 |
-
logger.info("[xgb_shadow] HR model loaded successfully")
|
| 108 |
-
except Exception as e:
|
| 109 |
-
logger.warning(f"[xgb_shadow] inference skipped (failed to load model: {e})")
|
| 110 |
-
_LOAD_OK = False
|
| 111 |
-
return _LOAD_OK
|
| 112 |
-
|
| 113 |
-
Feature construction helper
|
| 114 |
-
|
| 115 |
-
def _build_feature_row(
|
| 116 |
-
batter_features: dict[str, Any],
|
| 117 |
-
pitcher_row: dict[str, Any],
|
| 118 |
-
zone_adj: dict,
|
| 119 |
-
arsenal_adj: dict,
|
| 120 |
-
family_zone_adj: dict,
|
| 121 |
-
traj_row: dict,
|
| 122 |
-
env_adj: dict,
|
| 123 |
-
hr_prob: float,
|
| 124 |
-
hit_prob: float,
|
| 125 |
-
tb2p_prob: float,
|
| 126 |
-
archetype: str,
|
| 127 |
-
) -> dict[str, Any]:
|
| 128 |
-
"""
|
| 129 |
-
Construct the inference feature dict matching the 12.5A training schema.
|
| 130 |
-
Mirrors the feature population logic in xgb_dataset_builder.py::build_feature_row().
|
| 131 |
-
All one-hot encodings match the training-time encoding.
|
| 132 |
-
"""
|
| 133 |
-
bs = str(batter_features.get("batter_stand", "R") or "R").strip().upper()
|
| 134 |
-
pt = str(pitcher_row.get("p_throws", "R") or "R").strip().upper()
|
| 135 |
-
archetypes = ("power", "contact", "gap", "balanced")
|
| 136 |
-
|
| 137 |
-
feat: dict[str, Any] = {
|
| 138 |
-
# Batter baseline
|
| 139 |
-
"ev90": batter_features.get("ev90"),
|
| 140 |
-
"avg_launch_angle": batter_features.get("avg_launch_angle"),
|
| 141 |
-
"barrel_rate": batter_features.get("barrel_rate"),
|
| 142 |
-
"hard_hit_rate": batter_features.get("hard_hit_rate"),
|
| 143 |
-
"xwoba": batter_features.get("xwoba"),
|
| 144 |
-
"pull_rate": batter_features.get("pull_rate"),
|
| 145 |
-
"air_ball_rate": batter_features.get("air_ball_rate"),
|
| 146 |
-
"pull_air_rate": batter_features.get("pull_air_rate"),
|
| 147 |
-
"pulled_hard_air_rate": batter_features.get("pulled_hard_air_rate"),
|
| 148 |
-
"pulled_barrel_rate": batter_features.get("pulled_barrel_rate"),
|
| 149 |
-
"plate_appearances": batter_features.get("plate_appearances", 0),
|
| 150 |
-
# 12A shape
|
| 151 |
-
"gb_rate": batter_features.get("gb_rate", 0.0),
|
| 152 |
-
"ld_rate": batter_features.get("ld_rate", 0.0),
|
| 153 |
-
"fb_rate": batter_features.get("fb_rate", 0.0),
|
| 154 |
-
"popup_rate": batter_features.get("popup_rate", 0.0),
|
| 155 |
-
"la_sweet_spot_rate": batter_features.get("la_sweet_spot_rate", 0.0),
|
| 156 |
-
"la_optimal_hr_rate": batter_features.get("la_optimal_hr_rate", 0.0),
|
| 157 |
-
# Handedness one-hot
|
| 158 |
-
"batter_stand_R": int(bs == "R"),
|
| 159 |
-
# 12B trend
|
| 160 |
-
"ev90_7d": batter_features.get("ev90_7d"),
|
| 161 |
-
"ev90_30d": batter_features.get("ev90_30d"),
|
| 162 |
-
"barrel_7d": batter_features.get("barrel_7d"),
|
| 163 |
-
"barrel_30d": batter_features.get("barrel_30d"),
|
| 164 |
-
"xwoba_7d": batter_features.get("xwoba_7d"),
|
| 165 |
-
"xwoba_30d": batter_features.get("xwoba_30d"),
|
| 166 |
-
"trend_delta_ev90": batter_features.get("trend_delta_ev90"),
|
| 167 |
-
"trend_delta_barrel": batter_features.get("trend_delta_barrel"),
|
| 168 |
-
"trend_sample_size_7d": batter_features.get("trend_sample_size_7d", 0),
|
| 169 |
-
"trend_sample_size_30d": batter_features.get("trend_sample_size_30d", 0),
|
| 170 |
-
# 12C archetype one-hot
|
| 171 |
-
**{f"archetype_{a}": int(archetype == a) for a in archetypes},
|
| 172 |
-
# Pitcher baseline
|
| 173 |
-
"ev_allowed": pitcher_row.get("ev_allowed"),
|
| 174 |
-
"hard_hit_rate_allowed": pitcher_row.get("hard_hit_rate_allowed"),
|
| 175 |
-
"barrel_rate_allowed": pitcher_row.get("barrel_rate_allowed"),
|
| 176 |
-
"avg_release_speed": pitcher_row.get("avg_release_speed"),
|
| 177 |
-
"avg_release_spin_rate": pitcher_row.get("avg_release_spin_rate"),
|
| 178 |
-
"avg_release_extension": pitcher_row.get("avg_release_extension"),
|
| 179 |
-
"avg_pfx_x": pitcher_row.get("avg_pfx_x"),
|
| 180 |
-
"avg_pfx_z": pitcher_row.get("avg_pfx_z"),
|
| 181 |
-
# 12G shape allowed
|
| 182 |
-
"gb_rate_allowed": pitcher_row.get("gb_rate_allowed", 0.0),
|
| 183 |
-
"ld_rate_allowed": pitcher_row.get("ld_rate_allowed", 0.0),
|
| 184 |
-
"fb_rate_allowed": pitcher_row.get("fb_rate_allowed", 0.0),
|
| 185 |
-
"popup_rate_allowed": pitcher_row.get("popup_rate_allowed", 0.0),
|
| 186 |
-
"la_sweet_spot_allowed_rate": pitcher_row.get("la_sweet_spot_allowed_rate", 0.0),
|
| 187 |
-
"la_optimal_hr_allowed_rate": pitcher_row.get("la_optimal_hr_allowed_rate", 0.0),
|
| 188 |
-
"avg_launch_angle_allowed": pitcher_row.get("avg_launch_angle_allowed"),
|
| 189 |
-
# Pitcher handedness one-hot
|
| 190 |
-
"p_throws_R": int(pt == "R"),
|
| 191 |
-
# Zone (Batch 9 — may be None if DB unavailable)
|
| 192 |
-
"zone_hr_boost": zone_adj.get("hr_zone_boost"),
|
| 193 |
-
"zone_hit_boost": zone_adj.get("hit_zone_boost"),
|
| 194 |
-
"zone_tb2p_boost": zone_adj.get("tb2p_zone_boost"),
|
| 195 |
-
# Arsenal (Batch 9)
|
| 196 |
-
"arsenal_hr_boost": arsenal_adj.get("arsenal_hr_boost"),
|
| 197 |
-
"arsenal_hit_boost": arsenal_adj.get("arsenal_hit_boost"),
|
| 198 |
-
"arsenal_tb2p_boost": arsenal_adj.get("arsenal_tb2p_boost"),
|
| 199 |
-
"arsenal_whiff_risk": arsenal_adj.get("arsenal_whiff_risk"),
|
| 200 |
-
# Family-zone (Batch 9)
|
| 201 |
-
"family_zone_hr_boost": family_zone_adj.get("family_zone_hr_boost"),
|
| 202 |
-
"family_zone_hit_boost": family_zone_adj.get("family_zone_hit_boost"),
|
| 203 |
-
"family_zone_tb2p_boost": family_zone_adj.get("family_zone_tb2p_boost"),
|
| 204 |
-
"family_zone_whiff_risk": family_zone_adj.get("family_zone_whiff_risk"),
|
| 205 |
-
# Trajectory (Batch 10)
|
| 206 |
-
"deception_score": traj_row.get("deception_score"),
|
| 207 |
-
"tunnel_score": traj_row.get("tunnel_score"),
|
| 208 |
-
"release_consistency_score": traj_row.get("release_consistency_score"),
|
| 209 |
-
# Park/env (Batch 11)
|
| 210 |
-
"park_hr_boost": env_adj.get("park_hr_boost", 0.0),
|
| 211 |
-
"park_hit_boost": env_adj.get("park_hit_boost", 0.0),
|
| 212 |
-
"park_tb2p_boost": env_adj.get("park_tb2p_boost", 0.0),
|
| 213 |
-
"env_run_env_score": env_adj.get("park_run_env_score", 0.0),
|
| 214 |
-
# Anchor probs
|
| 215 |
-
"hr_prob": hr_prob,
|
| 216 |
-
"hit_prob": hit_prob,
|
| 217 |
-
"tb2p_prob": tb2p_prob,
|
| 218 |
-
}
|
| 219 |
-
return feat
|
| 220 |
-
|
| 221 |
-
Main inference function
|
| 222 |
-
|
| 223 |
-
def compute_xgb_shadow_outputs(
|
| 224 |
-
batter_features: dict[str, Any],
|
| 225 |
-
pitcher_row: dict[str, Any],
|
| 226 |
-
zone_adj: dict,
|
| 227 |
-
arsenal_adj: dict,
|
| 228 |
-
family_zone_adj: dict,
|
| 229 |
-
traj_row: dict,
|
| 230 |
-
env_adj: dict,
|
| 231 |
-
hr_prob: float,
|
| 232 |
-
hit_prob: float,
|
| 233 |
-
tb2p_prob: float,
|
| 234 |
-
archetype: str,
|
| 235 |
-
) -> dict[str, Any]:
|
| 236 |
-
"""
|
| 237 |
-
Run shadow XGBoost HR inference. Returns dict with shadow fields.
|
| 238 |
-
|
| 239 |
-
All fields are None on failure (missing artifacts, feature mismatch, etc.).
|
| 240 |
-
Never raises — designed to be safely inserted into simulator flow.
|
| 241 |
-
"""
|
| 242 |
-
null_result = {
|
| 243 |
-
"xgb_hr_delta": None,
|
| 244 |
-
"xgb_hr_adjusted": None,
|
| 245 |
-
"xgb_shadow_active": False,
|
| 246 |
-
}
|
| 247 |
-
|
| 248 |
-
if not _maybe_load_model():
|
| 249 |
-
return null_result
|
| 250 |
-
|
| 251 |
-
try:
|
| 252 |
-
feat = _build_feature_row(
|
| 253 |
-
batter_features, pitcher_row,
|
| 254 |
-
zone_adj, arsenal_adj, family_zone_adj,
|
| 255 |
-
traj_row, env_adj,
|
| 256 |
-
hr_prob, hit_prob, tb2p_prob, archetype,
|
| 257 |
-
)
|
| 258 |
-
|
| 259 |
-
# --- Strict feature validation ---
|
| 260 |
-
missing = [f for f in _FEATURE_NAMES if f not in feat]
|
| 261 |
-
if missing:
|
| 262 |
-
logger.warning(
|
| 263 |
-
f"[xgb_shadow] inference skipped ({len(missing)} missing features: "
|
| 264 |
-
f"{missing[:5]}{'...' if len(missing) > 5 else ''})"
|
| 265 |
-
)
|
| 266 |
-
return null_result
|
| 267 |
-
|
| 268 |
-
# --- Build DataFrame with EXACT column order from training ---
|
| 269 |
-
row_df = pd.DataFrame([[feat.get(k) for k in _FEATURE_NAMES]], columns=_FEATURE_NAMES)
|
| 270 |
-
|
| 271 |
-
# --- Numeric stability: coerce types, replace inf/NaN with 0.0 ---
|
| 272 |
-
row_df = row_df.apply(pd.to_numeric, errors="coerce")
|
| 273 |
-
row_df = row_df.replace([np.inf, -np.inf], np.nan).fillna(0.0)
|
| 274 |
-
|
| 275 |
-
# --- Inference ---
|
| 276 |
-
delta = float(_MODEL.predict(row_df)[0])
|
| 277 |
-
adjusted = float(max(0.0, min(1.0, hr_prob + delta))) # clamp adjusted only
|
| 278 |
-
|
| 279 |
-
logger.debug(f"[xgb_shadow] HR delta={delta:.4f}, adjusted={adjusted:.4f}")
|
| 280 |
-
|
| 281 |
-
return {
|
| 282 |
-
"xgb_hr_delta": delta,
|
| 283 |
-
"xgb_hr_adjusted": adjusted,
|
| 284 |
-
"xgb_shadow_active": True,
|
| 285 |
-
}
|
| 286 |
-
|
| 287 |
-
except Exception as e:
|
| 288 |
-
logger.warning(f"[xgb_shadow] inference skipped ({e})")
|
| 289 |
-
return null_result
|
| 290 |
-
|
| 291 |
-
---
|
| 292 |
-
Step 3 — models/live_fair_simulator_v3.py changes
|
| 293 |
-
|
| 294 |
-
3a. Imports (top of file, after existing imports)
|
| 295 |
-
|
| 296 |
-
from config.settings import ENABLE_XGB_SHADOW
|
| 297 |
-
if ENABLE_XGB_SHADOW:
|
| 298 |
-
try:
|
| 299 |
-
from models.xgb_shadow import compute_xgb_shadow_outputs
|
| 300 |
-
_XGB_SHADOW_AVAILABLE = True
|
| 301 |
-
except ImportError:
|
| 302 |
-
_XGB_SHADOW_AVAILABLE = False
|
| 303 |
-
else:
|
| 304 |
-
_XGB_SHADOW_AVAILABLE = False
|
| 305 |
-
|
| 306 |
-
3b. Insertion point (AFTER all B9/10/11 adjustments + final hr_prob is set, BEFORE output dict)
|
| 307 |
-
|
| 308 |
-
Insert after tb2p_prob = sim["tb2p_prob"] (line 464):
|
| 309 |
-
|
| 310 |
-
# Batch 12.5C: XGBoost HR shadow inference (Hit and TB2P excluded)
|
| 311 |
-
_shadow = {}
|
| 312 |
-
if _XGB_SHADOW_AVAILABLE:
|
| 313 |
-
_shadow = compute_xgb_shadow_outputs(
|
| 314 |
-
batter_features=batter_features,
|
| 315 |
-
pitcher_row=pitcher_row,
|
| 316 |
-
zone_adj=zone_adj if _ZONE_MODELS_AVAILABLE else {},
|
| 317 |
-
arsenal_adj=arsenal_adj if _ZONE_MODELS_AVAILABLE else {},
|
| 318 |
-
family_zone_adj=family_zone_adj if _ZONE_MODELS_AVAILABLE else {},
|
| 319 |
-
traj_row=trajectory_row,
|
| 320 |
-
env_adj=env_adj,
|
| 321 |
-
hr_prob=hr_prob,
|
| 322 |
-
hit_prob=hit_prob,
|
| 323 |
-
tb2p_prob=tb2p_prob,
|
| 324 |
-
archetype=classify_batter_archetype(batter_features),
|
| 325 |
-
)
|
| 326 |
-
|
| 327 |
-
3c. Output dict (after "tb2p_bet_ev", line ~515)
|
| 328 |
-
|
| 329 |
-
# Batch 12.5C shadow outputs (HR only)
|
| 330 |
-
"xgb_hr_delta": _shadow.get("xgb_hr_delta"),
|
| 331 |
-
"xgb_hr_adjusted": _shadow.get("xgb_hr_adjusted"),
|
| 332 |
-
"xgb_shadow_active": _shadow.get("xgb_shadow_active", False),
|
| 333 |
-
|
| 334 |
-
Invariant: hr_prob, hit_prob, tb2p_prob in output dict are untouched. Shadow fields are additive only.
|
| 335 |
-
|
| 336 |
-
---
|
| 337 |
-
Example Output Row (new shadow fields only)
|
| 338 |
-
|
| 339 |
-
{
|
| 340 |
-
"batter_name": "Aaron Judge",
|
| 341 |
-
"hr_prob": 0.094,
|
| 342 |
-
"hit_prob": 0.318,
|
| 343 |
-
"tb2p_prob": 0.198,
|
| 344 |
-
|
| 345 |
-
"xgb_hr_delta": 0.011,
|
| 346 |
-
"xgb_hr_adjusted": 0.105,
|
| 347 |
-
"xgb_shadow_active": true
|
| 348 |
-
}
|
| 349 |
-
|
| 350 |
-
When shadow is disabled or artifacts missing:
|
| 351 |
-
{
|
| 352 |
-
"xgb_hr_delta": null,
|
| 353 |
-
"xgb_hr_adjusted": null,
|
| 354 |
-
"xgb_shadow_active": false
|
| 355 |
-
}
|
| 356 |
-
|
| 357 |
-
---
|
| 358 |
-
Critical Files
|
| 359 |
-
|
| 360 |
-
┌──────────────────────────────────┬───────────────────────────────────────────┐
|
| 361 |
-
│ File │ Change │
|
| 362 |
-
├──────────────────────────────────┼───────────────────────────────────────────┤
|
| 363 |
-
│ config/settings.py │ +2 lines: ENABLE_XGB_SHADOW flag │
|
| 364 |
-
├──────────────────────────────────┼───────────────────────────────────────────┤
|
| 365 |
-
│ models/xgb_shadow.py │ NEW — ~130 lines (HR only) │
|
| 366 |
-
├──────────────────────────────────┼───────────────────────────────────────────┤
|
| 367 |
-
│ models/live_fair_simulator_v3.py │ +~13 lines: import, call, 3 output fields │
|
| 368 |
-
├──────────────────────────────────┼───────────────────────────────────────────┤
|
| 369 |
-
│ models/artifacts/xgb_hr_v1.json │ Read-only (artifact) │
|
| 370 |
-
└──────────────────────────────────┴───────────────────────────────────────────┘
|
| 371 |
-
|
| 372 |
-
---
|
| 373 |
-
Verification
|
| 374 |
-
|
| 375 |
-
1. Run simulator with ENABLE_XGB_SHADOW=true (default)
|
| 376 |
-
2. Check output row contains xgb_hr_delta (float), xgb_hr_adjusted (float in [0,1]), xgb_shadow_active=True
|
| 377 |
-
3. Confirm hr_prob, hit_prob, tb2p_prob are identical to pre-shadow values
|
| 378 |
-
4. Disable: ENABLE_XGB_SHADOW=false → check shadow fields are None, xgb_shadow_active=False
|
| 379 |
-
5. Delete artifact: verify graceful fallback (null result, warning logged, no crash)
|
| 380 |
-
|
| 381 |
-
---
|
| 382 |
-
---
|
| 383 |
-
PART 2 — Hit Model Remediation Plan
|
| 384 |
-
|
| 385 |
-
Root Cause Analysis
|
| 386 |
-
|
| 387 |
-
What went wrong
|
| 388 |
-
|
| 389 |
-
The Hit model's anchor (hit_prob, mean=0.292) is a per-plate-appearance probability:
|
| 390 |
-
the probability that the batter gets a hit in a single at-bat (~29% for average hitters).
|
| 391 |
-
|
| 392 |
-
The label (realized_hit, mean=0.592) is a game-level binary event:
|
| 393 |
-
did the batter record at least one hit across ALL plate appearances in the game (~59%)?
|
| 394 |
-
|
| 395 |
-
These are fundamentally different quantities. The relationship between them is:
|
| 396 |
-
|
| 397 |
-
P(any hit | N PAs) = 1 - (1 - hit_prob_pa)^N
|
| 398 |
-
|
| 399 |
-
For N=4 PAs and hit_prob_pa=0.29:
|
| 400 |
-
P(any hit) = 1 - (0.71)^4 = 1 - 0.254 = 0.746
|
| 401 |
-
|
| 402 |
-
But the observed rate is ~0.592, suggesting average N is closer to 2.5 in our dataset
|
| 403 |
-
(reflecting that the training CSV contains only contact events, not full game PA counts).
|
| 404 |
-
|
| 405 |
-
Why the model learned a constant uplift
|
| 406 |
-
|
| 407 |
-
The XGBoost model saw ~9,742 rows where:
|
| 408 |
-
- target_delta = realized_hit - hit_prob ≈ 0.592 - 0.292 = +0.300 (mean)
|
| 409 |
-
- All deltas are positive (range +0.05 to +0.50 based on individual batter anchors)
|
| 410 |
-
|
| 411 |
-
The model quickly learned: "always predict +0.30" (early stopping at 45 iterations).
|
| 412 |
-
It has no incentive to predict negative deltas because no label is ever below the anchor.
|
| 413 |
-
The XGBoost model is acting as a constant intercept, not a residual learner.
|
| 414 |
-
|
| 415 |
-
Why hit_prob doesn't appear in the model's top 20 features
|
| 416 |
-
|
| 417 |
-
Once the model learns a near-constant offset, hit_prob provides no additional information
|
| 418 |
-
above the offset. The model uses tb2p_prob and batter quality metrics instead because
|
| 419 |
-
they capture relative batter quality variance (discriminative signal), while hit_prob
|
| 420 |
-
is just being shifted upward uniformly.
|
| 421 |
-
|
| 422 |
-
---
|
| 423 |
-
Two Viable Correction Approaches
|
| 424 |
-
|
| 425 |
-
Approach 1 — Anchor Transformation (Recommended)
|
| 426 |
-
|
| 427 |
-
Idea: Convert per-PA hit probability to game-level "any hit" probability BEFORE computing deltas.
|
| 428 |
-
|
| 429 |
-
Formula:
|
| 430 |
-
hit_prob_game = 1 - (1 - hit_prob_pa)^n_pa_estimate
|
| 431 |
-
|
| 432 |
-
Implementation:
|
| 433 |
-
- Estimate n_pa_estimate per row from the training data
|
| 434 |
-
- Options for n_pa:
|
| 435 |
-
a. Fixed estimate: Use n_pa=3.5 (league average PAs per game for a typical batter)
|
| 436 |
-
b. Data-derived: Compute actual PA count from the batter CSV
|
| 437 |
-
(count of distinct game_date+player_name pairs in the batter contact CSV as a proxy;
|
| 438 |
-
actual PA count requires the full event CSV including outs/walks)
|
| 439 |
-
c. Feature-based: Use plate_appearances column from the parquet (which already represents
|
| 440 |
-
the batter's historical PA context)
|
| 441 |
-
|
| 442 |
-
Pros: Minimal dataset rebuild. Just add a transformation step in xgb_trainer.py
|
| 443 |
-
before computing deltas. Hit model retrain only.
|
| 444 |
-
|
| 445 |
-
Cons: n_pa is estimated, not exact. If n_pa is wrong, the game-level anchor is still biased.
|
| 446 |
-
|
| 447 |
-
Expected improvement: For n_pa=3.5 and hit_prob_pa=0.29:
|
| 448 |
-
hit_prob_game = 1 - (0.71)^3.5 ≈ 0.710
|
| 449 |
-
This overshoots (realized=0.592 < predicted=0.71). Need to calibrate n_pa more carefully.
|
| 450 |
-
|
| 451 |
-
For mean delta to be near zero: realized_hit ≈ 1 - (1 - hit_prob_pa)^n_pa
|
| 452 |
-
→ 0.592 = 1 - (1 - 0.292)^n → 0.408 = 0.708^n → n ≈ 2.5
|
| 453 |
-
|
| 454 |
-
So n_pa_estimate ≈ 2.5 would center the deltas. But this may vary by batter and game context.
|
| 455 |
-
|
| 456 |
-
Approach 2 — Label Redesign
|
| 457 |
-
|
| 458 |
-
Idea: Replace the game-level binary realized_hit label with a PA-aligned label that matches the per-PA anchor calibration.
|
| 459 |
-
|
| 460 |
-
Two sub-options:
|
| 461 |
-
|
| 462 |
-
2a. Use per-PA binary labels: Expand the dataset to per-PA rows (not per-game).
|
| 463 |
-
- Each PA is a row: did the batter get a hit on THIS plate appearance?
|
| 464 |
-
- Anchor: hit_prob_pa (already calibrated at PA level)
|
| 465 |
-
- Delta: 0 on average (same unit scale)
|
| 466 |
-
- Cons: Requires a full event-level CSV (including outs and walks, not just contact events).
|
| 467 |
-
Current training CSV excludes non-contact events. Significant data rebuild.
|
| 468 |
-
|
| 469 |
-
2b. Expected hits label: Define realized label as expected hits per game:
|
| 470 |
-
realized_expected_hits = (# hits in game) / (# PAs in game)
|
| 471 |
-
This normalizes the label to a per-PA rate, matching the anchor.
|
| 472 |
-
- Pros: Computable from existing CSV. Does not require new data.
|
| 473 |
-
- Cons: Continuous target instead of binary; different interpretation.
|
| 474 |
-
Model predicts "expected hit rate per PA in this game" as delta correction.
|
| 475 |
-
|
| 476 |
-
---
|
| 477 |
-
Recommended Path
|
| 478 |
-
|
| 479 |
-
Approach 1 with n_pa calibration (lowest implementation cost):
|
| 480 |
-
|
| 481 |
-
1. In xgb_trainer.py, add anchor transformation step for hit model:
|
| 482 |
-
# Compute game-level hit anchor from PA-level hit_prob
|
| 483 |
-
n_pa_estimate = 2.5 # calibrated so mean delta is near zero
|
| 484 |
-
df["hit_prob_game"] = 1 - (1 - df["hit_prob"]) ** n_pa_estimate
|
| 485 |
-
# Replace hit_prob in feature matrix with hit_prob_game
|
| 486 |
-
df["hit_prob"] = df["hit_prob_game"]
|
| 487 |
-
# Recompute delta: target_hit_delta = realized_hit - hit_prob_game
|
| 488 |
-
df["target_hit_delta"] = df["realized_hit"] - df["hit_prob"]
|
| 489 |
-
2. Verify post-transformation:
|
| 490 |
-
- Mean delta should be ~0.0 (not +0.30)
|
| 491 |
-
- Distribution should be bidirectional (both positive and negative deltas)
|
| 492 |
-
- hit_prob (now game-level) should have correlation > 0.10 with realized_hit
|
| 493 |
-
3. Retrain Hit model with the corrected anchor (keeping all other settings unchanged).
|
| 494 |
-
|
| 495 |
-
Explicit blocker for retrain: n_pa_estimate requires empirical validation. Check
|
| 496 |
-
the actual mean PA count in the training dataset before hardcoding 2.5.
|
| 497 |
-
Compute: actual_n_pa = df.groupby('batter_name')['plate_appearances'].first().mean()
|
| 498 |
-
then solve for n that centers the distribution.
|
| 499 |
-
|
| 500 |
-
---
|
| 501 |
-
Summary
|
| 502 |
-
|
| 503 |
-
┌────────────────────────────────────┬──────────────────────────────────────────────────────────────┐
|
| 504 |
-
│ Item │ Status │
|
| 505 |
-
├────────────────────────────────────┼──────────────────────────────────────────────────────────────┤
|
| 506 |
-
│ 12.5C shadow integration (HR only) │ READY TO IMPLEMENT │
|
| 507 |
-
├────────────────────────────────────┼──────────────────────────────────────────────────────────────┤
|
| 508 |
-
│ 12.5C TB2P shadow │ DEFERRED (future batch) │
|
| 509 |
-
├────────────────────────────────────┼──────────────────────────────────────────────────────────────┤
|
| 510 |
-
│ Hit model — root cause │ PA-level anchor vs game-level label mismatch │
|
| 511 |
-
├────────────────────────────────────┼──────────────────────────────────────────────────────────────┤
|
| 512 |
-
│ Hit model — recommended fix │ Anchor transformation: hit_prob_game = 1 - (1-hit_prob_pa)^n │
|
| 513 |
-
├────────────────────────────────────┼──────────────────────────────────────────────────────────────┤
|
| 514 |
-
│ Hit model — retrain timing │ After n_pa calibration — do NOT retrain yet │
|
| 515 |
-
└────────────────────────────────────┴──────────────────────────────────────────────────────────────┘
|
| 516 |
-
╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌
|
| 517 |
-
|
| 518 |
-
Claude has written up a plan and is ready to execute. Would you like to proceed?
|
| 519 |
-
|
| 520 |
-
❯ 1. Yes, clear context (32% used) and auto-accept edits
|
| 521 |
-
2. Yes, auto-accept edits
|
| 522 |
-
3. Yes, manually approve edits
|
| 523 |
-
4. Type here to tell Claude what to change
|
|
|
|
| 1 |
+
Make two required corrections before execution:
|
| 2 |
|
| 3 |
+
1. Preserve NaNs for model inference.
|
| 4 |
+
Do NOT replace all missing values with 0.0 in xgb_shadow.py.
|
| 5 |
|
| 6 |
+
Current plan has:
|
| 7 |
+
row_df = row_df.replace([np.inf, -np.inf], np.nan).fillna(0.0)
|
|
|
|
|
|
|
| 8 |
|
| 9 |
+
Change this to:
|
| 10 |
+
row_df = row_df.apply(pd.to_numeric, errors="coerce")
|
| 11 |
+
row_df = row_df.replace([np.inf, -np.inf], np.nan)
|
| 12 |
|
| 13 |
+
Reason:
|
| 14 |
+
- 12.5B training intentionally relied on XGBoost native missing-value routing
|
| 15 |
+
- filling NaNs with 0.0 at inference changes the feature semantics and can invalidate the model behavior
|
| 16 |
|
| 17 |
+
2. Fix the environment score feature key alignment.
|
| 18 |
+
Training schema uses:
|
| 19 |
+
env_run_env_score
|
| 20 |
|
| 21 |
+
The shadow feature builder currently uses:
|
| 22 |
+
env_adj.get("park_run_env_score", 0.0)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
+
Correct this so the feature source and feature name match training-time construction exactly.
|
| 25 |
+
Use the same env score key that was used in the training dataset / parquet schema.
|
| 26 |
|
| 27 |
+
Everything else can stay the same.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
+
Return the revised 12.5C HR-only shadow integration plan with only these two corrections.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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