From b5b62e582ed4f234f0d7639eefedf54fb4bd4503 Mon Sep 17 00:00:00 2001 From: Dasemu Date: Fri, 13 Mar 2026 10:01:43 +0100 Subject: [PATCH] fix(ml): resolve km_open under-prediction and remove Rule 3 - Removed data leakage features (lifts_open, snow_depth) from ML training. - Added station_id as an encoded categorical feature to enable station-awareness. - Removed Rule 3 (warm rain reduction) from the rules engine to avoid double-penalization. - Retrained all models with the corrected feature set. --- ml/train_model.py | 14 +++++++++++++ predictor/ml_predictor.py | 19 +++++++++++++++-- predictor/rules.py | 43 ++++++--------------------------------- 3 files changed, 37 insertions(+), 39 deletions(-) diff --git a/ml/train_model.py b/ml/train_model.py index 9834a57..6ac99e9 100644 --- a/ml/train_model.py +++ b/ml/train_model.py @@ -220,6 +220,7 @@ class ModelTrainer: non_feature_cols = target_cols | { "date", "station", + # station_id is handled separately as a categorical feature "station_id", # open_status is an alias for station_open (target); exclude it "open_status", @@ -227,6 +228,9 @@ class ModelTrainer: "snow_quality", # season is a string label, not a numeric feature "season", + # Data leakage: these are targets/status variables not in forecasts + "lifts_open", + "snow_depth", } # Also exclude any remaining object/string columns to prevent sklearn errors string_cols = set( @@ -237,6 +241,9 @@ class ModelTrainer: self._feature_columns = [ col for col in self._df.columns if col not in non_feature_cols ] + # station_id will be added back as an encoded numeric feature + self._feature_columns.append("station_id") + logger.info( "Dataset loaded: %d rows, %d features", len(self._df), @@ -256,6 +263,13 @@ class ModelTrainer: ) X = df[self._feature_columns].copy() + + # Encode station_id + station_le = LabelEncoder() + X["station_id"] = station_le.fit_transform(X["station_id"].astype(str)) + joblib.dump(station_le, self.models_dir / "station_id_label_encoder.joblib") + logger.debug("Encoded station_id using classes: %s", list(station_le.classes_)) + X = X.fillna(X.median(numeric_only=True)) # Calculate sample weights based on date recency diff --git a/predictor/ml_predictor.py b/predictor/ml_predictor.py index 765397b..eac23a8 100644 --- a/predictor/ml_predictor.py +++ b/predictor/ml_predictor.py @@ -30,6 +30,7 @@ _OPEN_MODEL_FILE = "station_open_model.joblib" _KM_MODEL_FILE = "km_open_model.joblib" _CROWD_MODEL_FILE = "crowd_level_model.joblib" _CROWD_ENCODER_FILE = "crowd_level_label_encoder.joblib" +_STATION_ENCODER_FILE = "station_id_label_encoder.joblib" def _load_model(path: Path) -> Any | None: @@ -93,6 +94,7 @@ class MLPredictor: self._km_model: Any | None = None self._crowd_model: Any | None = None self._crowd_encoder: Any | None = None + self._station_encoder: Any | None = None self._loaded = False if eager_load: @@ -108,6 +110,7 @@ class MLPredictor: self._km_model = _load_model(self._models_dir / _KM_MODEL_FILE) self._crowd_model = _load_model(self._models_dir / _CROWD_MODEL_FILE) self._crowd_encoder = _load_model(self._models_dir / _CROWD_ENCODER_FILE) + self._station_encoder = _load_model(self._models_dir / _STATION_ENCODER_FILE) self._loaded = True available = [ @@ -116,6 +119,7 @@ class MLPredictor: ("open_model", self._open_model), ("km_model", self._km_model), ("crowd_model", self._crowd_model), + ("station_encoder", self._station_encoder), ] if mdl is not None ] @@ -148,15 +152,26 @@ class MLPredictor: except AttributeError: # Fallback: drop known non-feature columns drop_cols = { - "date", "station_id", "station_open", "open_status", + "date", "station_open", "open_status", "km_open", "crowd_level", "snow_quality", "season", + "lifts_open", "snow_depth", } + # Note: station_id is NOT in drop_cols as it's now a feature expected = [c for c in df.columns if c not in drop_cols] # Select only expected columns, adding missing ones as 0 result = pd.DataFrame(index=df.index) for col in expected: - if col in df.columns: + if col == "station_id" and self._station_encoder is not None: + # Use the fitted LabelEncoder for station_id + station_val = str(df["station_id"].iloc[0]) + try: + result[col] = self._station_encoder.transform([station_val])[0] + except (ValueError, KeyError): + # Unknown station; fallback to first class as a guess + logger.warning("Unknown station_id '%s' for encoder.", station_val) + result[col] = 0 + elif col in df.columns: result[col] = pd.to_numeric(df[col], errors="coerce").fillna(0.0) else: result[col] = 0.0 diff --git a/predictor/rules.py b/predictor/rules.py index 0a2b9c8..af3f22e 100644 --- a/predictor/rules.py +++ b/predictor/rules.py @@ -19,21 +19,12 @@ logger = logging.getLogger(__name__) # Path relative to repository root _CONFIG_PATH = Path(__file__).parent.parent / "config" / "stations.yaml" -# Temperature above which rain becomes operationally problematic -_RAIN_TEMPERATURE_THRESHOLD_C = 10.0 - -# Precipitation threshold (mm) to be considered rain at high temperature -_RAIN_PRECIPITATION_THRESHOLD_MM = 2.0 - # Fresh snowfall (cm in 24 h) considered "heavy" _HEAVY_FRESH_SNOW_THRESHOLD_CM = 20.0 # Wind gust (km/h) considered "moderate" when combined with heavy snow _MODERATE_WIND_THRESHOLD_KMH = 40.0 -# km_factor reduction applied when warm rain is detected -_WARM_RAIN_KM_FACTOR_REDUCTION = 0.4 - def _load_station_configs() -> dict[str, Any]: """Load all station configurations from stations.yaml. @@ -187,29 +178,7 @@ class RulesEngine: min_snow, ) - # ---- Rule 3: High temperature + rain -> reduce km_factor --------- - temp_max = weather_data.get("temperature_2m_max") - precip = weather_data.get("precipitation_sum", 0.0) - - if ( - temp_max is not None - and temp_max > _RAIN_TEMPERATURE_THRESHOLD_C - and precip > _RAIN_PRECIPITATION_THRESHOLD_MM - ): - km_factor = max(0.0, km_factor - _WARM_RAIN_KM_FACTOR_REDUCTION) - reasons.append( - f"Temperatura de {temp_max:.1f} °C (superior a {_RAIN_TEMPERATURE_THRESHOLD_C} °C) " - f"con {precip:.1f} mm de precipitación; se estima una reducción de pistas abiertas." - ) - logger.info( - "[%s] Rule 3 fired: temp %.1f °C + rain %.1f mm -> km_factor reduced to %.2f", - station_name, - temp_max, - precip, - km_factor, - ) - - # ---- Rule 4: Heavy fresh snow + moderate wind -> likely open ----- + # ---- Rule 3: Heavy fresh snow + moderate wind -> likely open ----- snowfall_24h = weather_data.get("snowfall_sum") wind_speed = weather_data.get("wind_gusts_10m_max", 0.0) @@ -226,13 +195,13 @@ class RulesEngine: f"({wind_speed:.1f} km/h); es muy probable que la estación abra y esté concurrida." ) logger.info( - "[%s] Rule 4 fired: heavy snow %.1f cm + wind %.1f km/h -> force_open", + "[%s] Rule 3 fired: heavy snow %.1f cm + wind %.1f km/h -> force_open", station_name, snowfall_24h, wind_speed, ) - # ---- Rule 5: Weekday + no fresh snow -> low crowd ---------------- + # ---- Rule 4: Weekday + no fresh snow -> low crowd ---------------- is_weekend = bool(weather_data.get("is_weekend", False)) is_holiday = bool(weather_data.get("is_holiday", False)) is_busy_day = is_weekend or is_holiday @@ -242,16 +211,16 @@ class RulesEngine: reasons.append( "Día laborable sin nevadas significativas; se espera un nivel de afluencia bajo." ) - logger.debug("[%s] Rule 5 fired: weekday + no fresh snow -> low crowd", station_name) + logger.debug("[%s] Rule 4 fired: weekday + no fresh snow -> low crowd", station_name) - # ---- Rule 6: Weekend/holiday + fresh snow -> high crowd ---------- + # ---- Rule 5: Weekend/holiday + fresh snow -> high crowd ---------- if is_busy_day and snowfall_24h is not None and snowfall_24h >= 5.0 and not force_closed: reasons.append( f"Fin de semana o festivo con {snowfall_24h:.1f} cm de nieve fresca; " "se espera un nivel de afluencia alto." ) logger.debug( - "[%s] Rule 6 fired: busy day + fresh snow %.1f cm -> high crowd", + "[%s] Rule 5 fired: busy day + fresh snow %.1f cm -> high crowd", station_name, snowfall_24h, )