mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 15:26:15 +00:00
- 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.
309 lines
12 KiB
Python
309 lines
12 KiB
Python
"""ML-based predictor for ski station conditions.
|
||
|
||
Loads pre-trained models from the ml/models/ directory and generates
|
||
probabilistic predictions for station opening, skiable kilometres, and
|
||
crowd level. When models are absent the predictor degrades gracefully
|
||
and returns None so callers can fall back to rule-based logic.
|
||
|
||
Expected model files under ml/models/:
|
||
- open_model.joblib : binary classifier -> open_probability
|
||
- km_model.joblib : regressor -> km_open_prediction
|
||
- crowd_model.joblib : multiclass classifier -> crowd_level
|
||
"""
|
||
|
||
import logging
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
import joblib
|
||
import numpy as np
|
||
import pandas as pd
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
_MODELS_DIR = Path(__file__).parent.parent / "ml" / "models"
|
||
|
||
_CROWD_LABELS: list[str] = ["low", "medium", "high"]
|
||
|
||
# Filename constants make it easy to swap model artefacts without touching logic
|
||
_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:
|
||
"""Load a joblib model artefact from disk.
|
||
|
||
Args:
|
||
path: Absolute path to the ``.joblib`` file.
|
||
|
||
Returns:
|
||
The deserialised model object, or None if the file does not exist
|
||
or cannot be loaded.
|
||
"""
|
||
if not path.exists():
|
||
logger.warning("Model file not found: %s", path)
|
||
return None
|
||
|
||
try:
|
||
model = joblib.load(path)
|
||
logger.info("Loaded model from %s", path)
|
||
return model
|
||
except Exception as exc: # pylint: disable=broad-except
|
||
logger.error("Failed to load model %s: %s", path, exc)
|
||
return None
|
||
|
||
|
||
class MLPredictor:
|
||
"""Generates ML-based predictions for ski station conditions.
|
||
|
||
Models are loaded lazily from ``ml/models/`` the first time
|
||
:meth:`predict` is called, or eagerly if ``eager_load=True`` is passed
|
||
to the constructor.
|
||
|
||
When a required model file is missing the corresponding output field
|
||
is omitted from the returned dict and a warning is logged. The caller
|
||
(typically :class:`~predictor.hybrid_predictor.HybridPredictor`) must
|
||
handle a ``None`` return gracefully.
|
||
|
||
Usage::
|
||
|
||
predictor = MLPredictor()
|
||
result = predictor.predict(features_df)
|
||
if result is None:
|
||
# No models available; fall back to rules only
|
||
...
|
||
|
||
Args:
|
||
models_dir: Optional override for the directory containing model
|
||
artefacts. Defaults to ``ml/models/`` in the repository
|
||
root.
|
||
eager_load: If True, models are loaded during ``__init__``.
|
||
Defaults to False.
|
||
"""
|
||
|
||
def __init__(
|
||
self,
|
||
models_dir: Path | None = None,
|
||
eager_load: bool = False,
|
||
) -> None:
|
||
self._models_dir = Path(models_dir) if models_dir else _MODELS_DIR
|
||
self._open_model: Any | None = None
|
||
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:
|
||
self._load_all_models()
|
||
|
||
# ------------------------------------------------------------------
|
||
# Private helpers
|
||
# ------------------------------------------------------------------
|
||
|
||
def _load_all_models(self) -> None:
|
||
"""Load all model artefacts from disk."""
|
||
self._open_model = _load_model(self._models_dir / _OPEN_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_encoder = _load_model(self._models_dir / _CROWD_ENCODER_FILE)
|
||
self._station_encoder = _load_model(self._models_dir / _STATION_ENCODER_FILE)
|
||
self._loaded = True
|
||
|
||
available = [
|
||
name
|
||
for name, mdl in [
|
||
("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
|
||
]
|
||
logger.info(
|
||
"MLPredictor loaded %d/%d model(s): %s",
|
||
len(available),
|
||
3,
|
||
available,
|
||
)
|
||
|
||
def _ensure_loaded(self) -> None:
|
||
"""Lazy-load models on first prediction call."""
|
||
if not self._loaded:
|
||
self._load_all_models()
|
||
|
||
def _prepare_features(self, df: pd.DataFrame) -> pd.DataFrame:
|
||
"""Select and align features to match the trained model inputs.
|
||
|
||
Drops non-feature columns (date, station_id, target variables) and
|
||
fills any missing feature columns with 0.0 so the model always
|
||
receives the expected input shape.
|
||
"""
|
||
# Determine expected features from the first available model
|
||
ref_model = self._open_model or self._km_model or self._crowd_model
|
||
if ref_model is None:
|
||
return df
|
||
|
||
try:
|
||
expected = list(ref_model.feature_names_in_)
|
||
except AttributeError:
|
||
# Fallback: drop known non-feature columns
|
||
drop_cols = {
|
||
"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 == "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
|
||
logger.debug("Feature '%s' missing in input; filled with 0.0.", col)
|
||
|
||
return result
|
||
|
||
# ------------------------------------------------------------------
|
||
# Public API
|
||
# ------------------------------------------------------------------
|
||
|
||
def predict(self, features_df: pd.DataFrame) -> dict[str, Any] | None:
|
||
"""Generate predictions from a feature row.
|
||
|
||
Args:
|
||
features_df: A ``pandas.DataFrame`` with exactly one row
|
||
containing the engineered features for the prediction day.
|
||
Column names must match those expected by the trained models
|
||
(as defined in ``config/features.yaml``).
|
||
|
||
Returns:
|
||
A dict with the following keys, or ``None`` if no models are
|
||
available at all:
|
||
|
||
- ``open_probability`` (float 0–1): Probability the station opens.
|
||
- ``km_open_prediction`` (float): Predicted km of open slopes.
|
||
- ``crowd_level`` (str): Most likely crowd level
|
||
(``"low"``, ``"medium"``, or ``"high"``).
|
||
- ``crowd_probabilities`` (dict): Probability for each crowd
|
||
level, e.g. ``{"low": 0.1, "medium": 0.4, "high": 0.5}``.
|
||
|
||
Any key whose model is missing is omitted from the dict.
|
||
|
||
Raises:
|
||
ValueError: If ``features_df`` is empty or has more than one row.
|
||
"""
|
||
if features_df is None or features_df.empty:
|
||
raise ValueError("features_df must be a non-empty DataFrame.")
|
||
if len(features_df) != 1:
|
||
raise ValueError(
|
||
f"features_df must contain exactly one row; got {len(features_df)}."
|
||
)
|
||
|
||
self._ensure_loaded()
|
||
|
||
any_model_available = any(
|
||
m is not None
|
||
for m in [self._open_model, self._km_model, self._crowd_model]
|
||
)
|
||
if not any_model_available:
|
||
logger.warning(
|
||
"No ML models are available in %s. "
|
||
"Returning None; hybrid predictor will rely on rules only.",
|
||
self._models_dir,
|
||
)
|
||
return None
|
||
|
||
# Select only the features the models were trained on, dropping
|
||
# non-feature columns (date, station_id, target variables, etc.).
|
||
features_df = self._prepare_features(features_df)
|
||
|
||
result: dict[str, Any] = {}
|
||
|
||
# ---- Open probability -------------------------------------------
|
||
if self._open_model is not None:
|
||
try:
|
||
proba = self._open_model.predict_proba(features_df)
|
||
# scikit-learn convention: class order matches model.classes_
|
||
classes = list(self._open_model.classes_)
|
||
open_idx = classes.index(1) if 1 in classes else -1
|
||
open_prob = float(proba[0][open_idx]) if open_idx >= 0 else float(proba[0][1])
|
||
result["open_probability"] = float(np.clip(open_prob, 0.0, 1.0))
|
||
logger.debug("open_probability: %.3f", result["open_probability"])
|
||
except Exception as exc: # pylint: disable=broad-except
|
||
logger.error("open_model prediction failed: %s", exc)
|
||
else:
|
||
logger.warning("open_model not loaded; 'open_probability' will be absent.")
|
||
|
||
# ---- km open prediction -----------------------------------------
|
||
if self._km_model is not None:
|
||
try:
|
||
km_pred = float(self._km_model.predict(features_df)[0])
|
||
result["km_open_prediction"] = max(0.0, km_pred)
|
||
logger.debug("km_open_prediction: %.2f", result["km_open_prediction"])
|
||
except Exception as exc: # pylint: disable=broad-except
|
||
logger.error("km_model prediction failed: %s", exc)
|
||
else:
|
||
logger.warning("km_model not loaded; 'km_open_prediction' will be absent.")
|
||
|
||
# ---- Crowd level -------------------------------------------------
|
||
if self._crowd_model is not None:
|
||
try:
|
||
crowd_proba = self._crowd_model.predict_proba(features_df)[0]
|
||
predicted_encoded = int(np.argmax(crowd_proba))
|
||
|
||
# Decode numeric class back to string label
|
||
if self._crowd_encoder is not None:
|
||
encoded_classes = list(self._crowd_model.classes_)
|
||
decoded_classes = list(
|
||
self._crowd_encoder.inverse_transform(encoded_classes)
|
||
)
|
||
predicted_crowd = str(
|
||
self._crowd_encoder.inverse_transform(
|
||
[encoded_classes[predicted_encoded]]
|
||
)[0]
|
||
)
|
||
else:
|
||
# Fallback: assume classes map directly to _CROWD_LABELS
|
||
decoded_classes = _CROWD_LABELS[: len(self._crowd_model.classes_)]
|
||
predicted_crowd = decoded_classes[predicted_encoded]
|
||
|
||
# Build probability dict aligned to canonical label order
|
||
crowd_prob_dict: dict[str, float] = {}
|
||
for i, label in enumerate(decoded_classes):
|
||
crowd_prob_dict[label] = float(crowd_proba[i])
|
||
# Ensure all canonical labels present
|
||
for label in _CROWD_LABELS:
|
||
if label not in crowd_prob_dict:
|
||
crowd_prob_dict[label] = 0.0
|
||
|
||
result["crowd_level"] = predicted_crowd
|
||
result["crowd_probabilities"] = crowd_prob_dict
|
||
logger.debug(
|
||
"crowd_level: %s | probabilities: %s",
|
||
result["crowd_level"],
|
||
crowd_prob_dict,
|
||
)
|
||
except Exception as exc: # pylint: disable=broad-except
|
||
logger.error("crowd_model prediction failed: %s", exc)
|
||
else:
|
||
logger.warning("crowd_model not loaded; crowd fields will be absent.")
|
||
|
||
logger.info("MLPredictor result keys: %s", list(result.keys()))
|
||
return result if result else None
|