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