mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 23:36:17 +00:00
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.
This commit is contained in:
1 parent
6aa37f88e7
commit
b5b62e582e
3 files changed
+37
-39
No files matched your search
@@ -220,6 +220,7 @@ class ModelTrainer:
|
|||||||
non_feature_cols = target_cols | {
|
non_feature_cols = target_cols | {
|
||||||
"date",
|
"date",
|
||||||
"station",
|
"station",
|
||||||
|
# station_id is handled separately as a categorical feature
|
||||||
"station_id",
|
"station_id",
|
||||||
# open_status is an alias for station_open (target); exclude it
|
# open_status is an alias for station_open (target); exclude it
|
||||||
"open_status",
|
"open_status",
|
||||||
@@ -227,6 +228,9 @@ class ModelTrainer:
|
|||||||
"snow_quality",
|
"snow_quality",
|
||||||
# season is a string label, not a numeric feature
|
# season is a string label, not a numeric feature
|
||||||
"season",
|
"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
|
# Also exclude any remaining object/string columns to prevent sklearn errors
|
||||||
string_cols = set(
|
string_cols = set(
|
||||||
@@ -237,6 +241,9 @@ class ModelTrainer:
|
|||||||
self._feature_columns = [
|
self._feature_columns = [
|
||||||
col for col in self._df.columns if col not in non_feature_cols
|
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(
|
logger.info(
|
||||||
"Dataset loaded: %d rows, %d features",
|
"Dataset loaded: %d rows, %d features",
|
||||||
len(self._df),
|
len(self._df),
|
||||||
@@ -256,6 +263,13 @@ class ModelTrainer:
|
|||||||
)
|
)
|
||||||
|
|
||||||
X = df[self._feature_columns].copy()
|
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))
|
X = X.fillna(X.median(numeric_only=True))
|
||||||
|
|
||||||
# Calculate sample weights based on date recency
|
# Calculate sample weights based on date recency
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ _OPEN_MODEL_FILE = "station_open_model.joblib"
|
|||||||
_KM_MODEL_FILE = "km_open_model.joblib"
|
_KM_MODEL_FILE = "km_open_model.joblib"
|
||||||
_CROWD_MODEL_FILE = "crowd_level_model.joblib"
|
_CROWD_MODEL_FILE = "crowd_level_model.joblib"
|
||||||
_CROWD_ENCODER_FILE = "crowd_level_label_encoder.joblib"
|
_CROWD_ENCODER_FILE = "crowd_level_label_encoder.joblib"
|
||||||
|
_STATION_ENCODER_FILE = "station_id_label_encoder.joblib"
|
||||||
|
|
||||||
|
|
||||||
def _load_model(path: Path) -> Any | None:
|
def _load_model(path: Path) -> Any | None:
|
||||||
@@ -93,6 +94,7 @@ class MLPredictor:
|
|||||||
self._km_model: Any | None = None
|
self._km_model: Any | None = None
|
||||||
self._crowd_model: Any | None = None
|
self._crowd_model: Any | None = None
|
||||||
self._crowd_encoder: Any | None = None
|
self._crowd_encoder: Any | None = None
|
||||||
|
self._station_encoder: Any | None = None
|
||||||
self._loaded = False
|
self._loaded = False
|
||||||
|
|
||||||
if eager_load:
|
if eager_load:
|
||||||
@@ -108,6 +110,7 @@ class MLPredictor:
|
|||||||
self._km_model = _load_model(self._models_dir / _KM_MODEL_FILE)
|
self._km_model = _load_model(self._models_dir / _KM_MODEL_FILE)
|
||||||
self._crowd_model = _load_model(self._models_dir / _CROWD_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._crowd_encoder = _load_model(self._models_dir / _CROWD_ENCODER_FILE)
|
||||||
|
self._station_encoder = _load_model(self._models_dir / _STATION_ENCODER_FILE)
|
||||||
self._loaded = True
|
self._loaded = True
|
||||||
|
|
||||||
available = [
|
available = [
|
||||||
@@ -116,6 +119,7 @@ class MLPredictor:
|
|||||||
("open_model", self._open_model),
|
("open_model", self._open_model),
|
||||||
("km_model", self._km_model),
|
("km_model", self._km_model),
|
||||||
("crowd_model", self._crowd_model),
|
("crowd_model", self._crowd_model),
|
||||||
|
("station_encoder", self._station_encoder),
|
||||||
]
|
]
|
||||||
if mdl is not None
|
if mdl is not None
|
||||||
]
|
]
|
||||||
@@ -148,15 +152,26 @@ class MLPredictor:
|
|||||||
except AttributeError:
|
except AttributeError:
|
||||||
# Fallback: drop known non-feature columns
|
# Fallback: drop known non-feature columns
|
||||||
drop_cols = {
|
drop_cols = {
|
||||||
"date", "station_id", "station_open", "open_status",
|
"date", "station_open", "open_status",
|
||||||
"km_open", "crowd_level", "snow_quality", "season",
|
"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]
|
expected = [c for c in df.columns if c not in drop_cols]
|
||||||
|
|
||||||
# Select only expected columns, adding missing ones as 0
|
# Select only expected columns, adding missing ones as 0
|
||||||
result = pd.DataFrame(index=df.index)
|
result = pd.DataFrame(index=df.index)
|
||||||
for col in expected:
|
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)
|
result[col] = pd.to_numeric(df[col], errors="coerce").fillna(0.0)
|
||||||
else:
|
else:
|
||||||
result[col] = 0.0
|
result[col] = 0.0
|
||||||
|
|||||||
+6
-37
@@ -19,21 +19,12 @@ logger = logging.getLogger(__name__)
|
|||||||
# Path relative to repository root
|
# Path relative to repository root
|
||||||
_CONFIG_PATH = Path(__file__).parent.parent / "config" / "stations.yaml"
|
_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"
|
# Fresh snowfall (cm in 24 h) considered "heavy"
|
||||||
_HEAVY_FRESH_SNOW_THRESHOLD_CM = 20.0
|
_HEAVY_FRESH_SNOW_THRESHOLD_CM = 20.0
|
||||||
|
|
||||||
# Wind gust (km/h) considered "moderate" when combined with heavy snow
|
# Wind gust (km/h) considered "moderate" when combined with heavy snow
|
||||||
_MODERATE_WIND_THRESHOLD_KMH = 40.0
|
_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]:
|
def _load_station_configs() -> dict[str, Any]:
|
||||||
"""Load all station configurations from stations.yaml.
|
"""Load all station configurations from stations.yaml.
|
||||||
@@ -187,29 +178,7 @@ class RulesEngine:
|
|||||||
min_snow,
|
min_snow,
|
||||||
)
|
)
|
||||||
|
|
||||||
# ---- Rule 3: High temperature + rain -> reduce km_factor ---------
|
# ---- Rule 3: Heavy fresh snow + moderate wind -> likely open -----
|
||||||
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 -----
|
|
||||||
snowfall_24h = weather_data.get("snowfall_sum")
|
snowfall_24h = weather_data.get("snowfall_sum")
|
||||||
wind_speed = weather_data.get("wind_gusts_10m_max", 0.0)
|
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."
|
f"({wind_speed:.1f} km/h); es muy probable que la estación abra y esté concurrida."
|
||||||
)
|
)
|
||||||
logger.info(
|
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,
|
station_name,
|
||||||
snowfall_24h,
|
snowfall_24h,
|
||||||
wind_speed,
|
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_weekend = bool(weather_data.get("is_weekend", False))
|
||||||
is_holiday = bool(weather_data.get("is_holiday", False))
|
is_holiday = bool(weather_data.get("is_holiday", False))
|
||||||
is_busy_day = is_weekend or is_holiday
|
is_busy_day = is_weekend or is_holiday
|
||||||
@@ -242,16 +211,16 @@ class RulesEngine:
|
|||||||
reasons.append(
|
reasons.append(
|
||||||
"Día laborable sin nevadas significativas; se espera un nivel de afluencia bajo."
|
"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:
|
if is_busy_day and snowfall_24h is not None and snowfall_24h >= 5.0 and not force_closed:
|
||||||
reasons.append(
|
reasons.append(
|
||||||
f"Fin de semana o festivo con {snowfall_24h:.1f} cm de nieve fresca; "
|
f"Fin de semana o festivo con {snowfall_24h:.1f} cm de nieve fresca; "
|
||||||
"se espera un nivel de afluencia alto."
|
"se espera un nivel de afluencia alto."
|
||||||
)
|
)
|
||||||
logger.debug(
|
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,
|
station_name,
|
||||||
snowfall_24h,
|
snowfall_24h,
|
||||||
)
|
)
|
||||||
|
|||||||
Reference in new issue
Block a user